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/FixedPoint.h"
54 #include "clang/Basic/TargetInfo.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::APInt;
67 using llvm::APSInt;
68 using llvm::APFloat;
69 using llvm::Optional;
70 
71 namespace {
72   struct LValue;
73   class CallStackFrame;
74   class EvalInfo;
75 
76   using SourceLocExprScopeGuard =
77       CurrentSourceLocExprScope::SourceLocExprScopeGuard;
78 
79   static QualType getType(APValue::LValueBase B) {
80     if (!B) return QualType();
81     if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
82       // FIXME: It's unclear where we're supposed to take the type from, and
83       // this actually matters for arrays of unknown bound. Eg:
84       //
85       // extern int arr[]; void f() { extern int arr[3]; };
86       // constexpr int *p = &arr[1]; // valid?
87       //
88       // For now, we take the array bound from the most recent declaration.
89       for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
90            Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
91         QualType T = Redecl->getType();
92         if (!T->isIncompleteArrayType())
93           return T;
94       }
95       return D->getType();
96     }
97 
98     if (B.is<TypeInfoLValue>())
99       return B.getTypeInfoType();
100 
101     if (B.is<DynamicAllocLValue>())
102       return B.getDynamicAllocType();
103 
104     const Expr *Base = B.get<const Expr*>();
105 
106     // For a materialized temporary, the type of the temporary we materialized
107     // may not be the type of the expression.
108     if (const MaterializeTemporaryExpr *MTE =
109             dyn_cast<MaterializeTemporaryExpr>(Base)) {
110       SmallVector<const Expr *, 2> CommaLHSs;
111       SmallVector<SubobjectAdjustment, 2> Adjustments;
112       const Expr *Temp = MTE->getSubExpr();
113       const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
114                                                                Adjustments);
115       // Keep any cv-qualifiers from the reference if we generated a temporary
116       // for it directly. Otherwise use the type after adjustment.
117       if (!Adjustments.empty())
118         return Inner->getType();
119     }
120 
121     return Base->getType();
122   }
123 
124   /// Get an LValue path entry, which is known to not be an array index, as a
125   /// field declaration.
126   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
127     return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
128   }
129   /// Get an LValue path entry, which is known to not be an array index, as a
130   /// base class declaration.
131   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
132     return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
133   }
134   /// Determine whether this LValue path entry for a base class names a virtual
135   /// base class.
136   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
137     return E.getAsBaseOrMember().getInt();
138   }
139 
140   /// Given an expression, determine the type used to store the result of
141   /// evaluating that expression.
142   static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
143     if (E->isRValue())
144       return E->getType();
145     return Ctx.getLValueReferenceType(E->getType());
146   }
147 
148   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
149   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
150     const FunctionDecl *Callee = CE->getDirectCallee();
151     return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
152   }
153 
154   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
155   /// This will look through a single cast.
156   ///
157   /// Returns null if we couldn't unwrap a function with alloc_size.
158   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
159     if (!E->getType()->isPointerType())
160       return nullptr;
161 
162     E = E->IgnoreParens();
163     // If we're doing a variable assignment from e.g. malloc(N), there will
164     // probably be a cast of some kind. In exotic cases, we might also see a
165     // top-level ExprWithCleanups. Ignore them either way.
166     if (const auto *FE = dyn_cast<FullExpr>(E))
167       E = FE->getSubExpr()->IgnoreParens();
168 
169     if (const auto *Cast = dyn_cast<CastExpr>(E))
170       E = Cast->getSubExpr()->IgnoreParens();
171 
172     if (const auto *CE = dyn_cast<CallExpr>(E))
173       return getAllocSizeAttr(CE) ? CE : nullptr;
174     return nullptr;
175   }
176 
177   /// Determines whether or not the given Base contains a call to a function
178   /// with the alloc_size attribute.
179   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
180     const auto *E = Base.dyn_cast<const Expr *>();
181     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
182   }
183 
184   /// The bound to claim that an array of unknown bound has.
185   /// The value in MostDerivedArraySize is undefined in this case. So, set it
186   /// to an arbitrary value that's likely to loudly break things if it's used.
187   static const uint64_t AssumedSizeForUnsizedArray =
188       std::numeric_limits<uint64_t>::max() / 2;
189 
190   /// Determines if an LValue with the given LValueBase will have an unsized
191   /// array in its designator.
192   /// Find the path length and type of the most-derived subobject in the given
193   /// path, and find the size of the containing array, if any.
194   static unsigned
195   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
196                            ArrayRef<APValue::LValuePathEntry> Path,
197                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
198                            bool &FirstEntryIsUnsizedArray) {
199     // This only accepts LValueBases from APValues, and APValues don't support
200     // arrays that lack size info.
201     assert(!isBaseAnAllocSizeCall(Base) &&
202            "Unsized arrays shouldn't appear here");
203     unsigned MostDerivedLength = 0;
204     Type = getType(Base);
205 
206     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
207       if (Type->isArrayType()) {
208         const ArrayType *AT = Ctx.getAsArrayType(Type);
209         Type = AT->getElementType();
210         MostDerivedLength = I + 1;
211         IsArray = true;
212 
213         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
214           ArraySize = CAT->getSize().getZExtValue();
215         } else {
216           assert(I == 0 && "unexpected unsized array designator");
217           FirstEntryIsUnsizedArray = true;
218           ArraySize = AssumedSizeForUnsizedArray;
219         }
220       } else if (Type->isAnyComplexType()) {
221         const ComplexType *CT = Type->castAs<ComplexType>();
222         Type = CT->getElementType();
223         ArraySize = 2;
224         MostDerivedLength = I + 1;
225         IsArray = true;
226       } else if (const FieldDecl *FD = getAsField(Path[I])) {
227         Type = FD->getType();
228         ArraySize = 0;
229         MostDerivedLength = I + 1;
230         IsArray = false;
231       } else {
232         // Path[I] describes a base class.
233         ArraySize = 0;
234         IsArray = false;
235       }
236     }
237     return MostDerivedLength;
238   }
239 
240   /// A path from a glvalue to a subobject of that glvalue.
241   struct SubobjectDesignator {
242     /// True if the subobject was named in a manner not supported by C++11. Such
243     /// lvalues can still be folded, but they are not core constant expressions
244     /// and we cannot perform lvalue-to-rvalue conversions on them.
245     unsigned Invalid : 1;
246 
247     /// Is this a pointer one past the end of an object?
248     unsigned IsOnePastTheEnd : 1;
249 
250     /// Indicator of whether the first entry is an unsized array.
251     unsigned FirstEntryIsAnUnsizedArray : 1;
252 
253     /// Indicator of whether the most-derived object is an array element.
254     unsigned MostDerivedIsArrayElement : 1;
255 
256     /// The length of the path to the most-derived object of which this is a
257     /// subobject.
258     unsigned MostDerivedPathLength : 28;
259 
260     /// The size of the array of which the most-derived object is an element.
261     /// This will always be 0 if the most-derived object is not an array
262     /// element. 0 is not an indicator of whether or not the most-derived object
263     /// is an array, however, because 0-length arrays are allowed.
264     ///
265     /// If the current array is an unsized array, the value of this is
266     /// undefined.
267     uint64_t MostDerivedArraySize;
268 
269     /// The type of the most derived object referred to by this address.
270     QualType MostDerivedType;
271 
272     typedef APValue::LValuePathEntry PathEntry;
273 
274     /// The entries on the path from the glvalue to the designated subobject.
275     SmallVector<PathEntry, 8> Entries;
276 
277     SubobjectDesignator() : Invalid(true) {}
278 
279     explicit SubobjectDesignator(QualType T)
280         : Invalid(false), IsOnePastTheEnd(false),
281           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
282           MostDerivedPathLength(0), MostDerivedArraySize(0),
283           MostDerivedType(T) {}
284 
285     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
286         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
287           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
288           MostDerivedPathLength(0), MostDerivedArraySize(0) {
289       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
290       if (!Invalid) {
291         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
292         ArrayRef<PathEntry> VEntries = V.getLValuePath();
293         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
294         if (V.getLValueBase()) {
295           bool IsArray = false;
296           bool FirstIsUnsizedArray = false;
297           MostDerivedPathLength = findMostDerivedSubobject(
298               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
299               MostDerivedType, IsArray, FirstIsUnsizedArray);
300           MostDerivedIsArrayElement = IsArray;
301           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
302         }
303       }
304     }
305 
306     void truncate(ASTContext &Ctx, APValue::LValueBase Base,
307                   unsigned NewLength) {
308       if (Invalid)
309         return;
310 
311       assert(Base && "cannot truncate path for null pointer");
312       assert(NewLength <= Entries.size() && "not a truncation");
313 
314       if (NewLength == Entries.size())
315         return;
316       Entries.resize(NewLength);
317 
318       bool IsArray = false;
319       bool FirstIsUnsizedArray = false;
320       MostDerivedPathLength = findMostDerivedSubobject(
321           Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
322           FirstIsUnsizedArray);
323       MostDerivedIsArrayElement = IsArray;
324       FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
325     }
326 
327     void setInvalid() {
328       Invalid = true;
329       Entries.clear();
330     }
331 
332     /// Determine whether the most derived subobject is an array without a
333     /// known bound.
334     bool isMostDerivedAnUnsizedArray() const {
335       assert(!Invalid && "Calling this makes no sense on invalid designators");
336       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
337     }
338 
339     /// Determine what the most derived array's size is. Results in an assertion
340     /// failure if the most derived array lacks a size.
341     uint64_t getMostDerivedArraySize() const {
342       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
343       return MostDerivedArraySize;
344     }
345 
346     /// Determine whether this is a one-past-the-end pointer.
347     bool isOnePastTheEnd() const {
348       assert(!Invalid);
349       if (IsOnePastTheEnd)
350         return true;
351       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
352           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
353               MostDerivedArraySize)
354         return true;
355       return false;
356     }
357 
358     /// Get the range of valid index adjustments in the form
359     ///   {maximum value that can be subtracted from this pointer,
360     ///    maximum value that can be added to this pointer}
361     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
362       if (Invalid || isMostDerivedAnUnsizedArray())
363         return {0, 0};
364 
365       // [expr.add]p4: For the purposes of these operators, a pointer to a
366       // nonarray object behaves the same as a pointer to the first element of
367       // an array of length one with the type of the object as its element type.
368       bool IsArray = MostDerivedPathLength == Entries.size() &&
369                      MostDerivedIsArrayElement;
370       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
371                                     : (uint64_t)IsOnePastTheEnd;
372       uint64_t ArraySize =
373           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
374       return {ArrayIndex, ArraySize - ArrayIndex};
375     }
376 
377     /// Check that this refers to a valid subobject.
378     bool isValidSubobject() const {
379       if (Invalid)
380         return false;
381       return !isOnePastTheEnd();
382     }
383     /// Check that this refers to a valid subobject, and if not, produce a
384     /// relevant diagnostic and set the designator as invalid.
385     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
386 
387     /// Get the type of the designated object.
388     QualType getType(ASTContext &Ctx) const {
389       assert(!Invalid && "invalid designator has no subobject type");
390       return MostDerivedPathLength == Entries.size()
391                  ? MostDerivedType
392                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
393     }
394 
395     /// Update this designator to refer to the first element within this array.
396     void addArrayUnchecked(const ConstantArrayType *CAT) {
397       Entries.push_back(PathEntry::ArrayIndex(0));
398 
399       // This is a most-derived object.
400       MostDerivedType = CAT->getElementType();
401       MostDerivedIsArrayElement = true;
402       MostDerivedArraySize = CAT->getSize().getZExtValue();
403       MostDerivedPathLength = Entries.size();
404     }
405     /// Update this designator to refer to the first element within the array of
406     /// elements of type T. This is an array of unknown size.
407     void addUnsizedArrayUnchecked(QualType ElemTy) {
408       Entries.push_back(PathEntry::ArrayIndex(0));
409 
410       MostDerivedType = ElemTy;
411       MostDerivedIsArrayElement = true;
412       // The value in MostDerivedArraySize is undefined in this case. So, set it
413       // to an arbitrary value that's likely to loudly break things if it's
414       // used.
415       MostDerivedArraySize = AssumedSizeForUnsizedArray;
416       MostDerivedPathLength = Entries.size();
417     }
418     /// Update this designator to refer to the given base or member of this
419     /// object.
420     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
421       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
422 
423       // If this isn't a base class, it's a new most-derived object.
424       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
425         MostDerivedType = FD->getType();
426         MostDerivedIsArrayElement = false;
427         MostDerivedArraySize = 0;
428         MostDerivedPathLength = Entries.size();
429       }
430     }
431     /// Update this designator to refer to the given complex component.
432     void addComplexUnchecked(QualType EltTy, bool Imag) {
433       Entries.push_back(PathEntry::ArrayIndex(Imag));
434 
435       // This is technically a most-derived object, though in practice this
436       // is unlikely to matter.
437       MostDerivedType = EltTy;
438       MostDerivedIsArrayElement = true;
439       MostDerivedArraySize = 2;
440       MostDerivedPathLength = Entries.size();
441     }
442     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
443     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
444                                    const APSInt &N);
445     /// Add N to the address of this subobject.
446     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
447       if (Invalid || !N) return;
448       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
449       if (isMostDerivedAnUnsizedArray()) {
450         diagnoseUnsizedArrayPointerArithmetic(Info, E);
451         // Can't verify -- trust that the user is doing the right thing (or if
452         // not, trust that the caller will catch the bad behavior).
453         // FIXME: Should we reject if this overflows, at least?
454         Entries.back() = PathEntry::ArrayIndex(
455             Entries.back().getAsArrayIndex() + TruncatedN);
456         return;
457       }
458 
459       // [expr.add]p4: For the purposes of these operators, a pointer to a
460       // nonarray object behaves the same as a pointer to the first element of
461       // an array of length one with the type of the object as its element type.
462       bool IsArray = MostDerivedPathLength == Entries.size() &&
463                      MostDerivedIsArrayElement;
464       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
465                                     : (uint64_t)IsOnePastTheEnd;
466       uint64_t ArraySize =
467           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
468 
469       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
470         // Calculate the actual index in a wide enough type, so we can include
471         // it in the note.
472         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
473         (llvm::APInt&)N += ArrayIndex;
474         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
475         diagnosePointerArithmetic(Info, E, N);
476         setInvalid();
477         return;
478       }
479 
480       ArrayIndex += TruncatedN;
481       assert(ArrayIndex <= ArraySize &&
482              "bounds check succeeded for out-of-bounds index");
483 
484       if (IsArray)
485         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
486       else
487         IsOnePastTheEnd = (ArrayIndex != 0);
488     }
489   };
490 
491   /// A stack frame in the constexpr call stack.
492   class CallStackFrame : public interp::Frame {
493   public:
494     EvalInfo &Info;
495 
496     /// Parent - The caller of this stack frame.
497     CallStackFrame *Caller;
498 
499     /// Callee - The function which was called.
500     const FunctionDecl *Callee;
501 
502     /// This - The binding for the this pointer in this call, if any.
503     const LValue *This;
504 
505     /// Arguments - Parameter bindings for this function call, indexed by
506     /// parameters' function scope indices.
507     APValue *Arguments;
508 
509     /// Source location information about the default argument or default
510     /// initializer expression we're evaluating, if any.
511     CurrentSourceLocExprScope CurSourceLocExprScope;
512 
513     // Note that we intentionally use std::map here so that references to
514     // values are stable.
515     typedef std::pair<const void *, unsigned> MapKeyTy;
516     typedef std::map<MapKeyTy, APValue> MapTy;
517     /// Temporaries - Temporary lvalues materialized within this stack frame.
518     MapTy Temporaries;
519 
520     /// CallLoc - The location of the call expression for this call.
521     SourceLocation CallLoc;
522 
523     /// Index - The call index of this call.
524     unsigned Index;
525 
526     /// The stack of integers for tracking version numbers for temporaries.
527     SmallVector<unsigned, 2> TempVersionStack = {1};
528     unsigned CurTempVersion = TempVersionStack.back();
529 
530     unsigned getTempVersion() const { return TempVersionStack.back(); }
531 
532     void pushTempVersion() {
533       TempVersionStack.push_back(++CurTempVersion);
534     }
535 
536     void popTempVersion() {
537       TempVersionStack.pop_back();
538     }
539 
540     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
541     // on the overall stack usage of deeply-recursing constexpr evaluations.
542     // (We should cache this map rather than recomputing it repeatedly.)
543     // But let's try this and see how it goes; we can look into caching the map
544     // as a later change.
545 
546     /// LambdaCaptureFields - Mapping from captured variables/this to
547     /// corresponding data members in the closure class.
548     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
549     FieldDecl *LambdaThisCaptureField;
550 
551     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
552                    const FunctionDecl *Callee, const LValue *This,
553                    APValue *Arguments);
554     ~CallStackFrame();
555 
556     // Return the temporary for Key whose version number is Version.
557     APValue *getTemporary(const void *Key, unsigned Version) {
558       MapKeyTy KV(Key, Version);
559       auto LB = Temporaries.lower_bound(KV);
560       if (LB != Temporaries.end() && LB->first == KV)
561         return &LB->second;
562       // Pair (Key,Version) wasn't found in the map. Check that no elements
563       // in the map have 'Key' as their key.
564       assert((LB == Temporaries.end() || LB->first.first != Key) &&
565              (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
566              "Element with key 'Key' found in map");
567       return nullptr;
568     }
569 
570     // Return the current temporary for Key in the map.
571     APValue *getCurrentTemporary(const void *Key) {
572       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
573       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
574         return &std::prev(UB)->second;
575       return nullptr;
576     }
577 
578     // Return the version number of the current temporary for Key.
579     unsigned getCurrentTemporaryVersion(const void *Key) const {
580       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
581       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
582         return std::prev(UB)->first.second;
583       return 0;
584     }
585 
586     /// Allocate storage for an object of type T in this stack frame.
587     /// Populates LV with a handle to the created object. Key identifies
588     /// the temporary within the stack frame, and must not be reused without
589     /// bumping the temporary version number.
590     template<typename KeyT>
591     APValue &createTemporary(const KeyT *Key, QualType T,
592                              bool IsLifetimeExtended, LValue &LV);
593 
594     void describe(llvm::raw_ostream &OS) override;
595 
596     Frame *getCaller() const override { return Caller; }
597     SourceLocation getCallLocation() const override { return CallLoc; }
598     const FunctionDecl *getCallee() const override { return Callee; }
599 
600     bool isStdFunction() const {
601       for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
602         if (DC->isStdNamespace())
603           return true;
604       return false;
605     }
606   };
607 
608   /// Temporarily override 'this'.
609   class ThisOverrideRAII {
610   public:
611     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
612         : Frame(Frame), OldThis(Frame.This) {
613       if (Enable)
614         Frame.This = NewThis;
615     }
616     ~ThisOverrideRAII() {
617       Frame.This = OldThis;
618     }
619   private:
620     CallStackFrame &Frame;
621     const LValue *OldThis;
622   };
623 }
624 
625 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
626                               const LValue &This, QualType ThisType);
627 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
628                               APValue::LValueBase LVBase, APValue &Value,
629                               QualType T);
630 
631 namespace {
632   /// A cleanup, and a flag indicating whether it is lifetime-extended.
633   class Cleanup {
634     llvm::PointerIntPair<APValue*, 1, bool> Value;
635     APValue::LValueBase Base;
636     QualType T;
637 
638   public:
639     Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
640             bool IsLifetimeExtended)
641         : Value(Val, IsLifetimeExtended), Base(Base), T(T) {}
642 
643     bool isLifetimeExtended() const { return Value.getInt(); }
644     bool endLifetime(EvalInfo &Info, bool RunDestructors) {
645       if (RunDestructors) {
646         SourceLocation Loc;
647         if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
648           Loc = VD->getLocation();
649         else if (const Expr *E = Base.dyn_cast<const Expr*>())
650           Loc = E->getExprLoc();
651         return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
652       }
653       *Value.getPointer() = APValue();
654       return true;
655     }
656 
657     bool hasSideEffect() {
658       return T.isDestructedType();
659     }
660   };
661 
662   /// A reference to an object whose construction we are currently evaluating.
663   struct ObjectUnderConstruction {
664     APValue::LValueBase Base;
665     ArrayRef<APValue::LValuePathEntry> Path;
666     friend bool operator==(const ObjectUnderConstruction &LHS,
667                            const ObjectUnderConstruction &RHS) {
668       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
669     }
670     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
671       return llvm::hash_combine(Obj.Base, Obj.Path);
672     }
673   };
674   enum class ConstructionPhase {
675     None,
676     Bases,
677     AfterBases,
678     AfterFields,
679     Destroying,
680     DestroyingBases
681   };
682 }
683 
684 namespace llvm {
685 template<> struct DenseMapInfo<ObjectUnderConstruction> {
686   using Base = DenseMapInfo<APValue::LValueBase>;
687   static ObjectUnderConstruction getEmptyKey() {
688     return {Base::getEmptyKey(), {}}; }
689   static ObjectUnderConstruction getTombstoneKey() {
690     return {Base::getTombstoneKey(), {}};
691   }
692   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
693     return hash_value(Object);
694   }
695   static bool isEqual(const ObjectUnderConstruction &LHS,
696                       const ObjectUnderConstruction &RHS) {
697     return LHS == RHS;
698   }
699 };
700 }
701 
702 namespace {
703   /// A dynamically-allocated heap object.
704   struct DynAlloc {
705     /// The value of this heap-allocated object.
706     APValue Value;
707     /// The allocating expression; used for diagnostics. Either a CXXNewExpr
708     /// or a CallExpr (the latter is for direct calls to operator new inside
709     /// std::allocator<T>::allocate).
710     const Expr *AllocExpr = nullptr;
711 
712     enum Kind {
713       New,
714       ArrayNew,
715       StdAllocator
716     };
717 
718     /// Get the kind of the allocation. This must match between allocation
719     /// and deallocation.
720     Kind getKind() const {
721       if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
722         return NE->isArray() ? ArrayNew : New;
723       assert(isa<CallExpr>(AllocExpr));
724       return StdAllocator;
725     }
726   };
727 
728   struct DynAllocOrder {
729     bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
730       return L.getIndex() < R.getIndex();
731     }
732   };
733 
734   /// EvalInfo - This is a private struct used by the evaluator to capture
735   /// information about a subexpression as it is folded.  It retains information
736   /// about the AST context, but also maintains information about the folded
737   /// expression.
738   ///
739   /// If an expression could be evaluated, it is still possible it is not a C
740   /// "integer constant expression" or constant expression.  If not, this struct
741   /// captures information about how and why not.
742   ///
743   /// One bit of information passed *into* the request for constant folding
744   /// indicates whether the subexpression is "evaluated" or not according to C
745   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
746   /// evaluate the expression regardless of what the RHS is, but C only allows
747   /// certain things in certain situations.
748   class EvalInfo : public interp::State {
749   public:
750     ASTContext &Ctx;
751 
752     /// EvalStatus - Contains information about the evaluation.
753     Expr::EvalStatus &EvalStatus;
754 
755     /// CurrentCall - The top of the constexpr call stack.
756     CallStackFrame *CurrentCall;
757 
758     /// CallStackDepth - The number of calls in the call stack right now.
759     unsigned CallStackDepth;
760 
761     /// NextCallIndex - The next call index to assign.
762     unsigned NextCallIndex;
763 
764     /// StepsLeft - The remaining number of evaluation steps we're permitted
765     /// to perform. This is essentially a limit for the number of statements
766     /// we will evaluate.
767     unsigned StepsLeft;
768 
769     /// Enable the experimental new constant interpreter. If an expression is
770     /// not supported by the interpreter, an error is triggered.
771     bool EnableNewConstInterp;
772 
773     /// BottomFrame - The frame in which evaluation started. This must be
774     /// initialized after CurrentCall and CallStackDepth.
775     CallStackFrame BottomFrame;
776 
777     /// A stack of values whose lifetimes end at the end of some surrounding
778     /// evaluation frame.
779     llvm::SmallVector<Cleanup, 16> CleanupStack;
780 
781     /// EvaluatingDecl - This is the declaration whose initializer is being
782     /// evaluated, if any.
783     APValue::LValueBase EvaluatingDecl;
784 
785     enum class EvaluatingDeclKind {
786       None,
787       /// We're evaluating the construction of EvaluatingDecl.
788       Ctor,
789       /// We're evaluating the destruction of EvaluatingDecl.
790       Dtor,
791     };
792     EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
793 
794     /// EvaluatingDeclValue - This is the value being constructed for the
795     /// declaration whose initializer is being evaluated, if any.
796     APValue *EvaluatingDeclValue;
797 
798     /// Set of objects that are currently being constructed.
799     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
800         ObjectsUnderConstruction;
801 
802     /// Current heap allocations, along with the location where each was
803     /// allocated. We use std::map here because we need stable addresses
804     /// for the stored APValues.
805     std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
806 
807     /// The number of heap allocations performed so far in this evaluation.
808     unsigned NumHeapAllocs = 0;
809 
810     struct EvaluatingConstructorRAII {
811       EvalInfo &EI;
812       ObjectUnderConstruction Object;
813       bool DidInsert;
814       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
815                                 bool HasBases)
816           : EI(EI), Object(Object) {
817         DidInsert =
818             EI.ObjectsUnderConstruction
819                 .insert({Object, HasBases ? ConstructionPhase::Bases
820                                           : ConstructionPhase::AfterBases})
821                 .second;
822       }
823       void finishedConstructingBases() {
824         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
825       }
826       void finishedConstructingFields() {
827         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
828       }
829       ~EvaluatingConstructorRAII() {
830         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
831       }
832     };
833 
834     struct EvaluatingDestructorRAII {
835       EvalInfo &EI;
836       ObjectUnderConstruction Object;
837       bool DidInsert;
838       EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
839           : EI(EI), Object(Object) {
840         DidInsert = EI.ObjectsUnderConstruction
841                         .insert({Object, ConstructionPhase::Destroying})
842                         .second;
843       }
844       void startedDestroyingBases() {
845         EI.ObjectsUnderConstruction[Object] =
846             ConstructionPhase::DestroyingBases;
847       }
848       ~EvaluatingDestructorRAII() {
849         if (DidInsert)
850           EI.ObjectsUnderConstruction.erase(Object);
851       }
852     };
853 
854     ConstructionPhase
855     isEvaluatingCtorDtor(APValue::LValueBase Base,
856                          ArrayRef<APValue::LValuePathEntry> Path) {
857       return ObjectsUnderConstruction.lookup({Base, Path});
858     }
859 
860     /// If we're currently speculatively evaluating, the outermost call stack
861     /// depth at which we can mutate state, otherwise 0.
862     unsigned SpeculativeEvaluationDepth = 0;
863 
864     /// The current array initialization index, if we're performing array
865     /// initialization.
866     uint64_t ArrayInitIndex = -1;
867 
868     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
869     /// notes attached to it will also be stored, otherwise they will not be.
870     bool HasActiveDiagnostic;
871 
872     /// Have we emitted a diagnostic explaining why we couldn't constant
873     /// fold (not just why it's not strictly a constant expression)?
874     bool HasFoldFailureDiagnostic;
875 
876     /// Whether or not we're in a context where the front end requires a
877     /// constant value.
878     bool InConstantContext;
879 
880     /// Whether we're checking that an expression is a potential constant
881     /// expression. If so, do not fail on constructs that could become constant
882     /// later on (such as a use of an undefined global).
883     bool CheckingPotentialConstantExpression = false;
884 
885     /// Whether we're checking for an expression that has undefined behavior.
886     /// If so, we will produce warnings if we encounter an operation that is
887     /// always undefined.
888     bool CheckingForUndefinedBehavior = false;
889 
890     enum EvaluationMode {
891       /// Evaluate as a constant expression. Stop if we find that the expression
892       /// is not a constant expression.
893       EM_ConstantExpression,
894 
895       /// Evaluate as a constant expression. Stop if we find that the expression
896       /// is not a constant expression. Some expressions can be retried in the
897       /// optimizer if we don't constant fold them here, but in an unevaluated
898       /// context we try to fold them immediately since the optimizer never
899       /// gets a chance to look at it.
900       EM_ConstantExpressionUnevaluated,
901 
902       /// Fold the expression to a constant. Stop if we hit a side-effect that
903       /// we can't model.
904       EM_ConstantFold,
905 
906       /// Evaluate in any way we know how. Don't worry about side-effects that
907       /// can't be modeled.
908       EM_IgnoreSideEffects,
909     } EvalMode;
910 
911     /// Are we checking whether the expression is a potential constant
912     /// expression?
913     bool checkingPotentialConstantExpression() const override  {
914       return CheckingPotentialConstantExpression;
915     }
916 
917     /// Are we checking an expression for overflow?
918     // FIXME: We should check for any kind of undefined or suspicious behavior
919     // in such constructs, not just overflow.
920     bool checkingForUndefinedBehavior() const override {
921       return CheckingForUndefinedBehavior;
922     }
923 
924     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
925         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
926           CallStackDepth(0), NextCallIndex(1),
927           StepsLeft(C.getLangOpts().ConstexprStepLimit),
928           EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
929           BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
930           EvaluatingDecl((const ValueDecl *)nullptr),
931           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
932           HasFoldFailureDiagnostic(false), InConstantContext(false),
933           EvalMode(Mode) {}
934 
935     ~EvalInfo() {
936       discardCleanups();
937     }
938 
939     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
940                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
941       EvaluatingDecl = Base;
942       IsEvaluatingDecl = EDK;
943       EvaluatingDeclValue = &Value;
944     }
945 
946     bool CheckCallLimit(SourceLocation Loc) {
947       // Don't perform any constexpr calls (other than the call we're checking)
948       // when checking a potential constant expression.
949       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
950         return false;
951       if (NextCallIndex == 0) {
952         // NextCallIndex has wrapped around.
953         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
954         return false;
955       }
956       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
957         return true;
958       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
959         << getLangOpts().ConstexprCallDepth;
960       return false;
961     }
962 
963     std::pair<CallStackFrame *, unsigned>
964     getCallFrameAndDepth(unsigned CallIndex) {
965       assert(CallIndex && "no call index in getCallFrameAndDepth");
966       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
967       // be null in this loop.
968       unsigned Depth = CallStackDepth;
969       CallStackFrame *Frame = CurrentCall;
970       while (Frame->Index > CallIndex) {
971         Frame = Frame->Caller;
972         --Depth;
973       }
974       if (Frame->Index == CallIndex)
975         return {Frame, Depth};
976       return {nullptr, 0};
977     }
978 
979     bool nextStep(const Stmt *S) {
980       if (!StepsLeft) {
981         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
982         return false;
983       }
984       --StepsLeft;
985       return true;
986     }
987 
988     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
989 
990     Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
991       Optional<DynAlloc*> Result;
992       auto It = HeapAllocs.find(DA);
993       if (It != HeapAllocs.end())
994         Result = &It->second;
995       return Result;
996     }
997 
998     /// Information about a stack frame for std::allocator<T>::[de]allocate.
999     struct StdAllocatorCaller {
1000       unsigned FrameIndex;
1001       QualType ElemType;
1002       explicit operator bool() const { return FrameIndex != 0; };
1003     };
1004 
1005     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1006       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1007            Call = Call->Caller) {
1008         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1009         if (!MD)
1010           continue;
1011         const IdentifierInfo *FnII = MD->getIdentifier();
1012         if (!FnII || !FnII->isStr(FnName))
1013           continue;
1014 
1015         const auto *CTSD =
1016             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1017         if (!CTSD)
1018           continue;
1019 
1020         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1021         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1022         if (CTSD->isInStdNamespace() && ClassII &&
1023             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1024             TAL[0].getKind() == TemplateArgument::Type)
1025           return {Call->Index, TAL[0].getAsType()};
1026       }
1027 
1028       return {};
1029     }
1030 
1031     void performLifetimeExtension() {
1032       // Disable the cleanups for lifetime-extended temporaries.
1033       CleanupStack.erase(
1034           std::remove_if(CleanupStack.begin(), CleanupStack.end(),
1035                          [](Cleanup &C) { return C.isLifetimeExtended(); }),
1036           CleanupStack.end());
1037      }
1038 
1039     /// Throw away any remaining cleanups at the end of evaluation. If any
1040     /// cleanups would have had a side-effect, note that as an unmodeled
1041     /// side-effect and return false. Otherwise, return true.
1042     bool discardCleanups() {
1043       for (Cleanup &C : CleanupStack) {
1044         if (C.hasSideEffect() && !noteSideEffect()) {
1045           CleanupStack.clear();
1046           return false;
1047         }
1048       }
1049       CleanupStack.clear();
1050       return true;
1051     }
1052 
1053   private:
1054     interp::Frame *getCurrentFrame() override { return CurrentCall; }
1055     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1056 
1057     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1058     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1059 
1060     void setFoldFailureDiagnostic(bool Flag) override {
1061       HasFoldFailureDiagnostic = Flag;
1062     }
1063 
1064     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1065 
1066     ASTContext &getCtx() const override { return Ctx; }
1067 
1068     // If we have a prior diagnostic, it will be noting that the expression
1069     // isn't a constant expression. This diagnostic is more important,
1070     // unless we require this evaluation to produce a constant expression.
1071     //
1072     // FIXME: We might want to show both diagnostics to the user in
1073     // EM_ConstantFold mode.
1074     bool hasPriorDiagnostic() override {
1075       if (!EvalStatus.Diag->empty()) {
1076         switch (EvalMode) {
1077         case EM_ConstantFold:
1078         case EM_IgnoreSideEffects:
1079           if (!HasFoldFailureDiagnostic)
1080             break;
1081           // We've already failed to fold something. Keep that diagnostic.
1082           LLVM_FALLTHROUGH;
1083         case EM_ConstantExpression:
1084         case EM_ConstantExpressionUnevaluated:
1085           setActiveDiagnostic(false);
1086           return true;
1087         }
1088       }
1089       return false;
1090     }
1091 
1092     unsigned getCallStackDepth() override { return CallStackDepth; }
1093 
1094   public:
1095     /// Should we continue evaluation after encountering a side-effect that we
1096     /// couldn't model?
1097     bool keepEvaluatingAfterSideEffect() {
1098       switch (EvalMode) {
1099       case EM_IgnoreSideEffects:
1100         return true;
1101 
1102       case EM_ConstantExpression:
1103       case EM_ConstantExpressionUnevaluated:
1104       case EM_ConstantFold:
1105         // By default, assume any side effect might be valid in some other
1106         // evaluation of this expression from a different context.
1107         return checkingPotentialConstantExpression() ||
1108                checkingForUndefinedBehavior();
1109       }
1110       llvm_unreachable("Missed EvalMode case");
1111     }
1112 
1113     /// Note that we have had a side-effect, and determine whether we should
1114     /// keep evaluating.
1115     bool noteSideEffect() {
1116       EvalStatus.HasSideEffects = true;
1117       return keepEvaluatingAfterSideEffect();
1118     }
1119 
1120     /// Should we continue evaluation after encountering undefined behavior?
1121     bool keepEvaluatingAfterUndefinedBehavior() {
1122       switch (EvalMode) {
1123       case EM_IgnoreSideEffects:
1124       case EM_ConstantFold:
1125         return true;
1126 
1127       case EM_ConstantExpression:
1128       case EM_ConstantExpressionUnevaluated:
1129         return checkingForUndefinedBehavior();
1130       }
1131       llvm_unreachable("Missed EvalMode case");
1132     }
1133 
1134     /// Note that we hit something that was technically undefined behavior, but
1135     /// that we can evaluate past it (such as signed overflow or floating-point
1136     /// division by zero.)
1137     bool noteUndefinedBehavior() override {
1138       EvalStatus.HasUndefinedBehavior = true;
1139       return keepEvaluatingAfterUndefinedBehavior();
1140     }
1141 
1142     /// Should we continue evaluation as much as possible after encountering a
1143     /// construct which can't be reduced to a value?
1144     bool keepEvaluatingAfterFailure() const override {
1145       if (!StepsLeft)
1146         return false;
1147 
1148       switch (EvalMode) {
1149       case EM_ConstantExpression:
1150       case EM_ConstantExpressionUnevaluated:
1151       case EM_ConstantFold:
1152       case EM_IgnoreSideEffects:
1153         return checkingPotentialConstantExpression() ||
1154                checkingForUndefinedBehavior();
1155       }
1156       llvm_unreachable("Missed EvalMode case");
1157     }
1158 
1159     /// Notes that we failed to evaluate an expression that other expressions
1160     /// directly depend on, and determine if we should keep evaluating. This
1161     /// should only be called if we actually intend to keep evaluating.
1162     ///
1163     /// Call noteSideEffect() instead if we may be able to ignore the value that
1164     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1165     ///
1166     /// (Foo(), 1)      // use noteSideEffect
1167     /// (Foo() || true) // use noteSideEffect
1168     /// Foo() + 1       // use noteFailure
1169     LLVM_NODISCARD bool noteFailure() {
1170       // Failure when evaluating some expression often means there is some
1171       // subexpression whose evaluation was skipped. Therefore, (because we
1172       // don't track whether we skipped an expression when unwinding after an
1173       // evaluation failure) every evaluation failure that bubbles up from a
1174       // subexpression implies that a side-effect has potentially happened. We
1175       // skip setting the HasSideEffects flag to true until we decide to
1176       // continue evaluating after that point, which happens here.
1177       bool KeepGoing = keepEvaluatingAfterFailure();
1178       EvalStatus.HasSideEffects |= KeepGoing;
1179       return KeepGoing;
1180     }
1181 
1182     class ArrayInitLoopIndex {
1183       EvalInfo &Info;
1184       uint64_t OuterIndex;
1185 
1186     public:
1187       ArrayInitLoopIndex(EvalInfo &Info)
1188           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1189         Info.ArrayInitIndex = 0;
1190       }
1191       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1192 
1193       operator uint64_t&() { return Info.ArrayInitIndex; }
1194     };
1195   };
1196 
1197   /// Object used to treat all foldable expressions as constant expressions.
1198   struct FoldConstant {
1199     EvalInfo &Info;
1200     bool Enabled;
1201     bool HadNoPriorDiags;
1202     EvalInfo::EvaluationMode OldMode;
1203 
1204     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1205       : Info(Info),
1206         Enabled(Enabled),
1207         HadNoPriorDiags(Info.EvalStatus.Diag &&
1208                         Info.EvalStatus.Diag->empty() &&
1209                         !Info.EvalStatus.HasSideEffects),
1210         OldMode(Info.EvalMode) {
1211       if (Enabled)
1212         Info.EvalMode = EvalInfo::EM_ConstantFold;
1213     }
1214     void keepDiagnostics() { Enabled = false; }
1215     ~FoldConstant() {
1216       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1217           !Info.EvalStatus.HasSideEffects)
1218         Info.EvalStatus.Diag->clear();
1219       Info.EvalMode = OldMode;
1220     }
1221   };
1222 
1223   /// RAII object used to set the current evaluation mode to ignore
1224   /// side-effects.
1225   struct IgnoreSideEffectsRAII {
1226     EvalInfo &Info;
1227     EvalInfo::EvaluationMode OldMode;
1228     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1229         : Info(Info), OldMode(Info.EvalMode) {
1230       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1231     }
1232 
1233     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1234   };
1235 
1236   /// RAII object used to optionally suppress diagnostics and side-effects from
1237   /// a speculative evaluation.
1238   class SpeculativeEvaluationRAII {
1239     EvalInfo *Info = nullptr;
1240     Expr::EvalStatus OldStatus;
1241     unsigned OldSpeculativeEvaluationDepth;
1242 
1243     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1244       Info = Other.Info;
1245       OldStatus = Other.OldStatus;
1246       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1247       Other.Info = nullptr;
1248     }
1249 
1250     void maybeRestoreState() {
1251       if (!Info)
1252         return;
1253 
1254       Info->EvalStatus = OldStatus;
1255       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1256     }
1257 
1258   public:
1259     SpeculativeEvaluationRAII() = default;
1260 
1261     SpeculativeEvaluationRAII(
1262         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1263         : Info(&Info), OldStatus(Info.EvalStatus),
1264           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1265       Info.EvalStatus.Diag = NewDiag;
1266       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1267     }
1268 
1269     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1270     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1271       moveFromAndCancel(std::move(Other));
1272     }
1273 
1274     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1275       maybeRestoreState();
1276       moveFromAndCancel(std::move(Other));
1277       return *this;
1278     }
1279 
1280     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1281   };
1282 
1283   /// RAII object wrapping a full-expression or block scope, and handling
1284   /// the ending of the lifetime of temporaries created within it.
1285   template<bool IsFullExpression>
1286   class ScopeRAII {
1287     EvalInfo &Info;
1288     unsigned OldStackSize;
1289   public:
1290     ScopeRAII(EvalInfo &Info)
1291         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1292       // Push a new temporary version. This is needed to distinguish between
1293       // temporaries created in different iterations of a loop.
1294       Info.CurrentCall->pushTempVersion();
1295     }
1296     bool destroy(bool RunDestructors = true) {
1297       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1298       OldStackSize = -1U;
1299       return OK;
1300     }
1301     ~ScopeRAII() {
1302       if (OldStackSize != -1U)
1303         destroy(false);
1304       // Body moved to a static method to encourage the compiler to inline away
1305       // instances of this class.
1306       Info.CurrentCall->popTempVersion();
1307     }
1308   private:
1309     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1310                         unsigned OldStackSize) {
1311       assert(OldStackSize <= Info.CleanupStack.size() &&
1312              "running cleanups out of order?");
1313 
1314       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1315       // for a full-expression scope.
1316       bool Success = true;
1317       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1318         if (!(IsFullExpression &&
1319               Info.CleanupStack[I - 1].isLifetimeExtended())) {
1320           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1321             Success = false;
1322             break;
1323           }
1324         }
1325       }
1326 
1327       // Compact lifetime-extended cleanups.
1328       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1329       if (IsFullExpression)
1330         NewEnd =
1331             std::remove_if(NewEnd, Info.CleanupStack.end(),
1332                            [](Cleanup &C) { return !C.isLifetimeExtended(); });
1333       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1334       return Success;
1335     }
1336   };
1337   typedef ScopeRAII<false> BlockScopeRAII;
1338   typedef ScopeRAII<true> FullExpressionRAII;
1339 }
1340 
1341 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1342                                          CheckSubobjectKind CSK) {
1343   if (Invalid)
1344     return false;
1345   if (isOnePastTheEnd()) {
1346     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1347       << CSK;
1348     setInvalid();
1349     return false;
1350   }
1351   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1352   // must actually be at least one array element; even a VLA cannot have a
1353   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1354   return true;
1355 }
1356 
1357 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1358                                                                 const Expr *E) {
1359   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1360   // Do not set the designator as invalid: we can represent this situation,
1361   // and correct handling of __builtin_object_size requires us to do so.
1362 }
1363 
1364 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1365                                                     const Expr *E,
1366                                                     const APSInt &N) {
1367   // If we're complaining, we must be able to statically determine the size of
1368   // the most derived array.
1369   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1370     Info.CCEDiag(E, diag::note_constexpr_array_index)
1371       << N << /*array*/ 0
1372       << static_cast<unsigned>(getMostDerivedArraySize());
1373   else
1374     Info.CCEDiag(E, diag::note_constexpr_array_index)
1375       << N << /*non-array*/ 1;
1376   setInvalid();
1377 }
1378 
1379 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1380                                const FunctionDecl *Callee, const LValue *This,
1381                                APValue *Arguments)
1382     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1383       Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1384   Info.CurrentCall = this;
1385   ++Info.CallStackDepth;
1386 }
1387 
1388 CallStackFrame::~CallStackFrame() {
1389   assert(Info.CurrentCall == this && "calls retired out of order");
1390   --Info.CallStackDepth;
1391   Info.CurrentCall = Caller;
1392 }
1393 
1394 static bool isRead(AccessKinds AK) {
1395   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1396 }
1397 
1398 static bool isModification(AccessKinds AK) {
1399   switch (AK) {
1400   case AK_Read:
1401   case AK_ReadObjectRepresentation:
1402   case AK_MemberCall:
1403   case AK_DynamicCast:
1404   case AK_TypeId:
1405     return false;
1406   case AK_Assign:
1407   case AK_Increment:
1408   case AK_Decrement:
1409   case AK_Construct:
1410   case AK_Destroy:
1411     return true;
1412   }
1413   llvm_unreachable("unknown access kind");
1414 }
1415 
1416 static bool isAnyAccess(AccessKinds AK) {
1417   return isRead(AK) || isModification(AK);
1418 }
1419 
1420 /// Is this an access per the C++ definition?
1421 static bool isFormalAccess(AccessKinds AK) {
1422   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1423 }
1424 
1425 /// Is this kind of axcess valid on an indeterminate object value?
1426 static bool isValidIndeterminateAccess(AccessKinds AK) {
1427   switch (AK) {
1428   case AK_Read:
1429   case AK_Increment:
1430   case AK_Decrement:
1431     // These need the object's value.
1432     return false;
1433 
1434   case AK_ReadObjectRepresentation:
1435   case AK_Assign:
1436   case AK_Construct:
1437   case AK_Destroy:
1438     // Construction and destruction don't need the value.
1439     return true;
1440 
1441   case AK_MemberCall:
1442   case AK_DynamicCast:
1443   case AK_TypeId:
1444     // These aren't really meaningful on scalars.
1445     return true;
1446   }
1447   llvm_unreachable("unknown access kind");
1448 }
1449 
1450 namespace {
1451   struct ComplexValue {
1452   private:
1453     bool IsInt;
1454 
1455   public:
1456     APSInt IntReal, IntImag;
1457     APFloat FloatReal, FloatImag;
1458 
1459     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1460 
1461     void makeComplexFloat() { IsInt = false; }
1462     bool isComplexFloat() const { return !IsInt; }
1463     APFloat &getComplexFloatReal() { return FloatReal; }
1464     APFloat &getComplexFloatImag() { return FloatImag; }
1465 
1466     void makeComplexInt() { IsInt = true; }
1467     bool isComplexInt() const { return IsInt; }
1468     APSInt &getComplexIntReal() { return IntReal; }
1469     APSInt &getComplexIntImag() { return IntImag; }
1470 
1471     void moveInto(APValue &v) const {
1472       if (isComplexFloat())
1473         v = APValue(FloatReal, FloatImag);
1474       else
1475         v = APValue(IntReal, IntImag);
1476     }
1477     void setFrom(const APValue &v) {
1478       assert(v.isComplexFloat() || v.isComplexInt());
1479       if (v.isComplexFloat()) {
1480         makeComplexFloat();
1481         FloatReal = v.getComplexFloatReal();
1482         FloatImag = v.getComplexFloatImag();
1483       } else {
1484         makeComplexInt();
1485         IntReal = v.getComplexIntReal();
1486         IntImag = v.getComplexIntImag();
1487       }
1488     }
1489   };
1490 
1491   struct LValue {
1492     APValue::LValueBase Base;
1493     CharUnits Offset;
1494     SubobjectDesignator Designator;
1495     bool IsNullPtr : 1;
1496     bool InvalidBase : 1;
1497 
1498     const APValue::LValueBase getLValueBase() const { return Base; }
1499     CharUnits &getLValueOffset() { return Offset; }
1500     const CharUnits &getLValueOffset() const { return Offset; }
1501     SubobjectDesignator &getLValueDesignator() { return Designator; }
1502     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1503     bool isNullPointer() const { return IsNullPtr;}
1504 
1505     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1506     unsigned getLValueVersion() const { return Base.getVersion(); }
1507 
1508     void moveInto(APValue &V) const {
1509       if (Designator.Invalid)
1510         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1511       else {
1512         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1513         V = APValue(Base, Offset, Designator.Entries,
1514                     Designator.IsOnePastTheEnd, IsNullPtr);
1515       }
1516     }
1517     void setFrom(ASTContext &Ctx, const APValue &V) {
1518       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1519       Base = V.getLValueBase();
1520       Offset = V.getLValueOffset();
1521       InvalidBase = false;
1522       Designator = SubobjectDesignator(Ctx, V);
1523       IsNullPtr = V.isNullPointer();
1524     }
1525 
1526     void set(APValue::LValueBase B, bool BInvalid = false) {
1527 #ifndef NDEBUG
1528       // We only allow a few types of invalid bases. Enforce that here.
1529       if (BInvalid) {
1530         const auto *E = B.get<const Expr *>();
1531         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1532                "Unexpected type of invalid base");
1533       }
1534 #endif
1535 
1536       Base = B;
1537       Offset = CharUnits::fromQuantity(0);
1538       InvalidBase = BInvalid;
1539       Designator = SubobjectDesignator(getType(B));
1540       IsNullPtr = false;
1541     }
1542 
1543     void setNull(ASTContext &Ctx, QualType PointerTy) {
1544       Base = (Expr *)nullptr;
1545       Offset =
1546           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1547       InvalidBase = false;
1548       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1549       IsNullPtr = true;
1550     }
1551 
1552     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1553       set(B, true);
1554     }
1555 
1556     std::string toString(ASTContext &Ctx, QualType T) const {
1557       APValue Printable;
1558       moveInto(Printable);
1559       return Printable.getAsString(Ctx, T);
1560     }
1561 
1562   private:
1563     // Check that this LValue is not based on a null pointer. If it is, produce
1564     // a diagnostic and mark the designator as invalid.
1565     template <typename GenDiagType>
1566     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1567       if (Designator.Invalid)
1568         return false;
1569       if (IsNullPtr) {
1570         GenDiag();
1571         Designator.setInvalid();
1572         return false;
1573       }
1574       return true;
1575     }
1576 
1577   public:
1578     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1579                           CheckSubobjectKind CSK) {
1580       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1581         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1582       });
1583     }
1584 
1585     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1586                                        AccessKinds AK) {
1587       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1588         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1589       });
1590     }
1591 
1592     // Check this LValue refers to an object. If not, set the designator to be
1593     // invalid and emit a diagnostic.
1594     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1595       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1596              Designator.checkSubobject(Info, E, CSK);
1597     }
1598 
1599     void addDecl(EvalInfo &Info, const Expr *E,
1600                  const Decl *D, bool Virtual = false) {
1601       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1602         Designator.addDeclUnchecked(D, Virtual);
1603     }
1604     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1605       if (!Designator.Entries.empty()) {
1606         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1607         Designator.setInvalid();
1608         return;
1609       }
1610       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1611         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1612         Designator.FirstEntryIsAnUnsizedArray = true;
1613         Designator.addUnsizedArrayUnchecked(ElemTy);
1614       }
1615     }
1616     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1617       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1618         Designator.addArrayUnchecked(CAT);
1619     }
1620     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1621       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1622         Designator.addComplexUnchecked(EltTy, Imag);
1623     }
1624     void clearIsNullPointer() {
1625       IsNullPtr = false;
1626     }
1627     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1628                               const APSInt &Index, CharUnits ElementSize) {
1629       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1630       // but we're not required to diagnose it and it's valid in C++.)
1631       if (!Index)
1632         return;
1633 
1634       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1635       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1636       // offsets.
1637       uint64_t Offset64 = Offset.getQuantity();
1638       uint64_t ElemSize64 = ElementSize.getQuantity();
1639       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1640       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1641 
1642       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1643         Designator.adjustIndex(Info, E, Index);
1644       clearIsNullPointer();
1645     }
1646     void adjustOffset(CharUnits N) {
1647       Offset += N;
1648       if (N.getQuantity())
1649         clearIsNullPointer();
1650     }
1651   };
1652 
1653   struct MemberPtr {
1654     MemberPtr() {}
1655     explicit MemberPtr(const ValueDecl *Decl) :
1656       DeclAndIsDerivedMember(Decl, false), Path() {}
1657 
1658     /// The member or (direct or indirect) field referred to by this member
1659     /// pointer, or 0 if this is a null member pointer.
1660     const ValueDecl *getDecl() const {
1661       return DeclAndIsDerivedMember.getPointer();
1662     }
1663     /// Is this actually a member of some type derived from the relevant class?
1664     bool isDerivedMember() const {
1665       return DeclAndIsDerivedMember.getInt();
1666     }
1667     /// Get the class which the declaration actually lives in.
1668     const CXXRecordDecl *getContainingRecord() const {
1669       return cast<CXXRecordDecl>(
1670           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1671     }
1672 
1673     void moveInto(APValue &V) const {
1674       V = APValue(getDecl(), isDerivedMember(), Path);
1675     }
1676     void setFrom(const APValue &V) {
1677       assert(V.isMemberPointer());
1678       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1679       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1680       Path.clear();
1681       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1682       Path.insert(Path.end(), P.begin(), P.end());
1683     }
1684 
1685     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1686     /// whether the member is a member of some class derived from the class type
1687     /// of the member pointer.
1688     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1689     /// Path - The path of base/derived classes from the member declaration's
1690     /// class (exclusive) to the class type of the member pointer (inclusive).
1691     SmallVector<const CXXRecordDecl*, 4> Path;
1692 
1693     /// Perform a cast towards the class of the Decl (either up or down the
1694     /// hierarchy).
1695     bool castBack(const CXXRecordDecl *Class) {
1696       assert(!Path.empty());
1697       const CXXRecordDecl *Expected;
1698       if (Path.size() >= 2)
1699         Expected = Path[Path.size() - 2];
1700       else
1701         Expected = getContainingRecord();
1702       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1703         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1704         // if B does not contain the original member and is not a base or
1705         // derived class of the class containing the original member, the result
1706         // of the cast is undefined.
1707         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1708         // (D::*). We consider that to be a language defect.
1709         return false;
1710       }
1711       Path.pop_back();
1712       return true;
1713     }
1714     /// Perform a base-to-derived member pointer cast.
1715     bool castToDerived(const CXXRecordDecl *Derived) {
1716       if (!getDecl())
1717         return true;
1718       if (!isDerivedMember()) {
1719         Path.push_back(Derived);
1720         return true;
1721       }
1722       if (!castBack(Derived))
1723         return false;
1724       if (Path.empty())
1725         DeclAndIsDerivedMember.setInt(false);
1726       return true;
1727     }
1728     /// Perform a derived-to-base member pointer cast.
1729     bool castToBase(const CXXRecordDecl *Base) {
1730       if (!getDecl())
1731         return true;
1732       if (Path.empty())
1733         DeclAndIsDerivedMember.setInt(true);
1734       if (isDerivedMember()) {
1735         Path.push_back(Base);
1736         return true;
1737       }
1738       return castBack(Base);
1739     }
1740   };
1741 
1742   /// Compare two member pointers, which are assumed to be of the same type.
1743   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1744     if (!LHS.getDecl() || !RHS.getDecl())
1745       return !LHS.getDecl() && !RHS.getDecl();
1746     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1747       return false;
1748     return LHS.Path == RHS.Path;
1749   }
1750 }
1751 
1752 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1753 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1754                             const LValue &This, const Expr *E,
1755                             bool AllowNonLiteralTypes = false);
1756 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1757                            bool InvalidBaseOK = false);
1758 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1759                             bool InvalidBaseOK = false);
1760 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1761                                   EvalInfo &Info);
1762 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1763 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1764 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1765                                     EvalInfo &Info);
1766 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1767 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1768 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1769                            EvalInfo &Info);
1770 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1771 
1772 /// Evaluate an integer or fixed point expression into an APResult.
1773 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1774                                         EvalInfo &Info);
1775 
1776 /// Evaluate only a fixed point expression into an APResult.
1777 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1778                                EvalInfo &Info);
1779 
1780 //===----------------------------------------------------------------------===//
1781 // Misc utilities
1782 //===----------------------------------------------------------------------===//
1783 
1784 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1785 /// preserving its value (by extending by up to one bit as needed).
1786 static void negateAsSigned(APSInt &Int) {
1787   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1788     Int = Int.extend(Int.getBitWidth() + 1);
1789     Int.setIsSigned(true);
1790   }
1791   Int = -Int;
1792 }
1793 
1794 template<typename KeyT>
1795 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1796                                          bool IsLifetimeExtended, LValue &LV) {
1797   unsigned Version = getTempVersion();
1798   APValue::LValueBase Base(Key, Index, Version);
1799   LV.set(Base);
1800   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1801   assert(Result.isAbsent() && "temporary created multiple times");
1802 
1803   // If we're creating a temporary immediately in the operand of a speculative
1804   // evaluation, don't register a cleanup to be run outside the speculative
1805   // evaluation context, since we won't actually be able to initialize this
1806   // object.
1807   if (Index <= Info.SpeculativeEvaluationDepth) {
1808     if (T.isDestructedType())
1809       Info.noteSideEffect();
1810   } else {
1811     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, IsLifetimeExtended));
1812   }
1813   return Result;
1814 }
1815 
1816 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1817   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1818     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1819     return nullptr;
1820   }
1821 
1822   DynamicAllocLValue DA(NumHeapAllocs++);
1823   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1824   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1825                                    std::forward_as_tuple(DA), std::tuple<>());
1826   assert(Result.second && "reused a heap alloc index?");
1827   Result.first->second.AllocExpr = E;
1828   return &Result.first->second.Value;
1829 }
1830 
1831 /// Produce a string describing the given constexpr call.
1832 void CallStackFrame::describe(raw_ostream &Out) {
1833   unsigned ArgIndex = 0;
1834   bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1835                       !isa<CXXConstructorDecl>(Callee) &&
1836                       cast<CXXMethodDecl>(Callee)->isInstance();
1837 
1838   if (!IsMemberCall)
1839     Out << *Callee << '(';
1840 
1841   if (This && IsMemberCall) {
1842     APValue Val;
1843     This->moveInto(Val);
1844     Val.printPretty(Out, Info.Ctx,
1845                     This->Designator.MostDerivedType);
1846     // FIXME: Add parens around Val if needed.
1847     Out << "->" << *Callee << '(';
1848     IsMemberCall = false;
1849   }
1850 
1851   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1852        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1853     if (ArgIndex > (unsigned)IsMemberCall)
1854       Out << ", ";
1855 
1856     const ParmVarDecl *Param = *I;
1857     const APValue &Arg = Arguments[ArgIndex];
1858     Arg.printPretty(Out, Info.Ctx, Param->getType());
1859 
1860     if (ArgIndex == 0 && IsMemberCall)
1861       Out << "->" << *Callee << '(';
1862   }
1863 
1864   Out << ')';
1865 }
1866 
1867 /// Evaluate an expression to see if it had side-effects, and discard its
1868 /// result.
1869 /// \return \c true if the caller should keep evaluating.
1870 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1871   APValue Scratch;
1872   if (!Evaluate(Scratch, Info, E))
1873     // We don't need the value, but we might have skipped a side effect here.
1874     return Info.noteSideEffect();
1875   return true;
1876 }
1877 
1878 /// Should this call expression be treated as a string literal?
1879 static bool IsStringLiteralCall(const CallExpr *E) {
1880   unsigned Builtin = E->getBuiltinCallee();
1881   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1882           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1883 }
1884 
1885 static bool IsGlobalLValue(APValue::LValueBase B) {
1886   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1887   // constant expression of pointer type that evaluates to...
1888 
1889   // ... a null pointer value, or a prvalue core constant expression of type
1890   // std::nullptr_t.
1891   if (!B) return true;
1892 
1893   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1894     // ... the address of an object with static storage duration,
1895     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1896       return VD->hasGlobalStorage();
1897     // ... the address of a function,
1898     // ... the address of a GUID [MS extension],
1899     return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D);
1900   }
1901 
1902   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1903     return true;
1904 
1905   const Expr *E = B.get<const Expr*>();
1906   switch (E->getStmtClass()) {
1907   default:
1908     return false;
1909   case Expr::CompoundLiteralExprClass: {
1910     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1911     return CLE->isFileScope() && CLE->isLValue();
1912   }
1913   case Expr::MaterializeTemporaryExprClass:
1914     // A materialized temporary might have been lifetime-extended to static
1915     // storage duration.
1916     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1917   // A string literal has static storage duration.
1918   case Expr::StringLiteralClass:
1919   case Expr::PredefinedExprClass:
1920   case Expr::ObjCStringLiteralClass:
1921   case Expr::ObjCEncodeExprClass:
1922     return true;
1923   case Expr::ObjCBoxedExprClass:
1924     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
1925   case Expr::CallExprClass:
1926     return IsStringLiteralCall(cast<CallExpr>(E));
1927   // For GCC compatibility, &&label has static storage duration.
1928   case Expr::AddrLabelExprClass:
1929     return true;
1930   // A Block literal expression may be used as the initialization value for
1931   // Block variables at global or local static scope.
1932   case Expr::BlockExprClass:
1933     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1934   case Expr::ImplicitValueInitExprClass:
1935     // FIXME:
1936     // We can never form an lvalue with an implicit value initialization as its
1937     // base through expression evaluation, so these only appear in one case: the
1938     // implicit variable declaration we invent when checking whether a constexpr
1939     // constructor can produce a constant expression. We must assume that such
1940     // an expression might be a global lvalue.
1941     return true;
1942   }
1943 }
1944 
1945 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1946   return LVal.Base.dyn_cast<const ValueDecl*>();
1947 }
1948 
1949 static bool IsLiteralLValue(const LValue &Value) {
1950   if (Value.getLValueCallIndex())
1951     return false;
1952   const Expr *E = Value.Base.dyn_cast<const Expr*>();
1953   return E && !isa<MaterializeTemporaryExpr>(E);
1954 }
1955 
1956 static bool IsWeakLValue(const LValue &Value) {
1957   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1958   return Decl && Decl->isWeak();
1959 }
1960 
1961 static bool isZeroSized(const LValue &Value) {
1962   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1963   if (Decl && isa<VarDecl>(Decl)) {
1964     QualType Ty = Decl->getType();
1965     if (Ty->isArrayType())
1966       return Ty->isIncompleteType() ||
1967              Decl->getASTContext().getTypeSize(Ty) == 0;
1968   }
1969   return false;
1970 }
1971 
1972 static bool HasSameBase(const LValue &A, const LValue &B) {
1973   if (!A.getLValueBase())
1974     return !B.getLValueBase();
1975   if (!B.getLValueBase())
1976     return false;
1977 
1978   if (A.getLValueBase().getOpaqueValue() !=
1979       B.getLValueBase().getOpaqueValue()) {
1980     const Decl *ADecl = GetLValueBaseDecl(A);
1981     if (!ADecl)
1982       return false;
1983     const Decl *BDecl = GetLValueBaseDecl(B);
1984     if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1985       return false;
1986   }
1987 
1988   return IsGlobalLValue(A.getLValueBase()) ||
1989          (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1990           A.getLValueVersion() == B.getLValueVersion());
1991 }
1992 
1993 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1994   assert(Base && "no location for a null lvalue");
1995   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1996   if (VD)
1997     Info.Note(VD->getLocation(), diag::note_declared_at);
1998   else if (const Expr *E = Base.dyn_cast<const Expr*>())
1999     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2000   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2001     // FIXME: Produce a note for dangling pointers too.
2002     if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
2003       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2004                 diag::note_constexpr_dynamic_alloc_here);
2005   }
2006   // We have no information to show for a typeid(T) object.
2007 }
2008 
2009 enum class CheckEvaluationResultKind {
2010   ConstantExpression,
2011   FullyInitialized,
2012 };
2013 
2014 /// Materialized temporaries that we've already checked to determine if they're
2015 /// initializsed by a constant expression.
2016 using CheckedTemporaries =
2017     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2018 
2019 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2020                                   EvalInfo &Info, SourceLocation DiagLoc,
2021                                   QualType Type, const APValue &Value,
2022                                   Expr::ConstExprUsage Usage,
2023                                   SourceLocation SubobjectLoc,
2024                                   CheckedTemporaries &CheckedTemps);
2025 
2026 /// Check that this reference or pointer core constant expression is a valid
2027 /// value for an address or reference constant expression. Return true if we
2028 /// can fold this expression, whether or not it's a constant expression.
2029 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2030                                           QualType Type, const LValue &LVal,
2031                                           Expr::ConstExprUsage Usage,
2032                                           CheckedTemporaries &CheckedTemps) {
2033   bool IsReferenceType = Type->isReferenceType();
2034 
2035   APValue::LValueBase Base = LVal.getLValueBase();
2036   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2037 
2038   if (auto *VD = LVal.getLValueBase().dyn_cast<const ValueDecl *>()) {
2039     if (auto *FD = dyn_cast<FunctionDecl>(VD)) {
2040       if (FD->isConsteval()) {
2041         Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2042             << !Type->isAnyPointerType();
2043         Info.Note(FD->getLocation(), diag::note_declared_at);
2044         return false;
2045       }
2046     }
2047   }
2048 
2049   // Check that the object is a global. Note that the fake 'this' object we
2050   // manufacture when checking potential constant expressions is conservatively
2051   // assumed to be global here.
2052   if (!IsGlobalLValue(Base)) {
2053     if (Info.getLangOpts().CPlusPlus11) {
2054       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2055       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2056         << IsReferenceType << !Designator.Entries.empty()
2057         << !!VD << VD;
2058       NoteLValueLocation(Info, Base);
2059     } else {
2060       Info.FFDiag(Loc);
2061     }
2062     // Don't allow references to temporaries to escape.
2063     return false;
2064   }
2065   assert((Info.checkingPotentialConstantExpression() ||
2066           LVal.getLValueCallIndex() == 0) &&
2067          "have call index for global lvalue");
2068 
2069   if (Base.is<DynamicAllocLValue>()) {
2070     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2071         << IsReferenceType << !Designator.Entries.empty();
2072     NoteLValueLocation(Info, Base);
2073     return false;
2074   }
2075 
2076   if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
2077     if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
2078       // Check if this is a thread-local variable.
2079       if (Var->getTLSKind())
2080         // FIXME: Diagnostic!
2081         return false;
2082 
2083       // A dllimport variable never acts like a constant.
2084       if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
2085         // FIXME: Diagnostic!
2086         return false;
2087     }
2088     if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
2089       // __declspec(dllimport) must be handled very carefully:
2090       // We must never initialize an expression with the thunk in C++.
2091       // Doing otherwise would allow the same id-expression to yield
2092       // different addresses for the same function in different translation
2093       // units.  However, this means that we must dynamically initialize the
2094       // expression with the contents of the import address table at runtime.
2095       //
2096       // The C language has no notion of ODR; furthermore, it has no notion of
2097       // dynamic initialization.  This means that we are permitted to
2098       // perform initialization with the address of the thunk.
2099       if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
2100           FD->hasAttr<DLLImportAttr>())
2101         // FIXME: Diagnostic!
2102         return false;
2103     }
2104   } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(
2105                  Base.dyn_cast<const Expr *>())) {
2106     if (CheckedTemps.insert(MTE).second) {
2107       QualType TempType = getType(Base);
2108       if (TempType.isDestructedType()) {
2109         Info.FFDiag(MTE->getExprLoc(),
2110                     diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor)
2111             << TempType;
2112         return false;
2113       }
2114 
2115       APValue *V = MTE->getOrCreateValue(false);
2116       assert(V && "evasluation result refers to uninitialised temporary");
2117       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2118                                  Info, MTE->getExprLoc(), TempType, *V,
2119                                  Usage, SourceLocation(), CheckedTemps))
2120         return false;
2121     }
2122   }
2123 
2124   // Allow address constant expressions to be past-the-end pointers. This is
2125   // an extension: the standard requires them to point to an object.
2126   if (!IsReferenceType)
2127     return true;
2128 
2129   // A reference constant expression must refer to an object.
2130   if (!Base) {
2131     // FIXME: diagnostic
2132     Info.CCEDiag(Loc);
2133     return true;
2134   }
2135 
2136   // Does this refer one past the end of some object?
2137   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2138     const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2139     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2140       << !Designator.Entries.empty() << !!VD << VD;
2141     NoteLValueLocation(Info, Base);
2142   }
2143 
2144   return true;
2145 }
2146 
2147 /// Member pointers are constant expressions unless they point to a
2148 /// non-virtual dllimport member function.
2149 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2150                                                  SourceLocation Loc,
2151                                                  QualType Type,
2152                                                  const APValue &Value,
2153                                                  Expr::ConstExprUsage Usage) {
2154   const ValueDecl *Member = Value.getMemberPointerDecl();
2155   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2156   if (!FD)
2157     return true;
2158   if (FD->isConsteval()) {
2159     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2160     Info.Note(FD->getLocation(), diag::note_declared_at);
2161     return false;
2162   }
2163   return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
2164          !FD->hasAttr<DLLImportAttr>();
2165 }
2166 
2167 /// Check that this core constant expression is of literal type, and if not,
2168 /// produce an appropriate diagnostic.
2169 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2170                              const LValue *This = nullptr) {
2171   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
2172     return true;
2173 
2174   // C++1y: A constant initializer for an object o [...] may also invoke
2175   // constexpr constructors for o and its subobjects even if those objects
2176   // are of non-literal class types.
2177   //
2178   // C++11 missed this detail for aggregates, so classes like this:
2179   //   struct foo_t { union { int i; volatile int j; } u; };
2180   // are not (obviously) initializable like so:
2181   //   __attribute__((__require_constant_initialization__))
2182   //   static const foo_t x = {{0}};
2183   // because "i" is a subobject with non-literal initialization (due to the
2184   // volatile member of the union). See:
2185   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2186   // Therefore, we use the C++1y behavior.
2187   if (This && Info.EvaluatingDecl == This->getLValueBase())
2188     return true;
2189 
2190   // Prvalue constant expressions must be of literal types.
2191   if (Info.getLangOpts().CPlusPlus11)
2192     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2193       << E->getType();
2194   else
2195     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2196   return false;
2197 }
2198 
2199 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2200                                   EvalInfo &Info, SourceLocation DiagLoc,
2201                                   QualType Type, const APValue &Value,
2202                                   Expr::ConstExprUsage Usage,
2203                                   SourceLocation SubobjectLoc,
2204                                   CheckedTemporaries &CheckedTemps) {
2205   if (!Value.hasValue()) {
2206     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2207       << true << Type;
2208     if (SubobjectLoc.isValid())
2209       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2210     return false;
2211   }
2212 
2213   // We allow _Atomic(T) to be initialized from anything that T can be
2214   // initialized from.
2215   if (const AtomicType *AT = Type->getAs<AtomicType>())
2216     Type = AT->getValueType();
2217 
2218   // Core issue 1454: For a literal constant expression of array or class type,
2219   // each subobject of its value shall have been initialized by a constant
2220   // expression.
2221   if (Value.isArray()) {
2222     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2223     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2224       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2225                                  Value.getArrayInitializedElt(I), Usage,
2226                                  SubobjectLoc, CheckedTemps))
2227         return false;
2228     }
2229     if (!Value.hasArrayFiller())
2230       return true;
2231     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2232                                  Value.getArrayFiller(), Usage, SubobjectLoc,
2233                                  CheckedTemps);
2234   }
2235   if (Value.isUnion() && Value.getUnionField()) {
2236     return CheckEvaluationResult(
2237         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2238         Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(),
2239         CheckedTemps);
2240   }
2241   if (Value.isStruct()) {
2242     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2243     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2244       unsigned BaseIndex = 0;
2245       for (const CXXBaseSpecifier &BS : CD->bases()) {
2246         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2247                                    Value.getStructBase(BaseIndex), Usage,
2248                                    BS.getBeginLoc(), CheckedTemps))
2249           return false;
2250         ++BaseIndex;
2251       }
2252     }
2253     for (const auto *I : RD->fields()) {
2254       if (I->isUnnamedBitfield())
2255         continue;
2256 
2257       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2258                                  Value.getStructField(I->getFieldIndex()),
2259                                  Usage, I->getLocation(), CheckedTemps))
2260         return false;
2261     }
2262   }
2263 
2264   if (Value.isLValue() &&
2265       CERK == CheckEvaluationResultKind::ConstantExpression) {
2266     LValue LVal;
2267     LVal.setFrom(Info.Ctx, Value);
2268     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage,
2269                                          CheckedTemps);
2270   }
2271 
2272   if (Value.isMemberPointer() &&
2273       CERK == CheckEvaluationResultKind::ConstantExpression)
2274     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
2275 
2276   // Everything else is fine.
2277   return true;
2278 }
2279 
2280 /// Check that this core constant expression value is a valid value for a
2281 /// constant expression. If not, report an appropriate diagnostic. Does not
2282 /// check that the expression is of literal type.
2283 static bool
2284 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2285                         const APValue &Value,
2286                         Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
2287   CheckedTemporaries CheckedTemps;
2288   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2289                                Info, DiagLoc, Type, Value, Usage,
2290                                SourceLocation(), CheckedTemps);
2291 }
2292 
2293 /// Check that this evaluated value is fully-initialized and can be loaded by
2294 /// an lvalue-to-rvalue conversion.
2295 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2296                                   QualType Type, const APValue &Value) {
2297   CheckedTemporaries CheckedTemps;
2298   return CheckEvaluationResult(
2299       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2300       Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps);
2301 }
2302 
2303 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2304 /// "the allocated storage is deallocated within the evaluation".
2305 static bool CheckMemoryLeaks(EvalInfo &Info) {
2306   if (!Info.HeapAllocs.empty()) {
2307     // We can still fold to a constant despite a compile-time memory leak,
2308     // so long as the heap allocation isn't referenced in the result (we check
2309     // that in CheckConstantExpression).
2310     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2311                  diag::note_constexpr_memory_leak)
2312         << unsigned(Info.HeapAllocs.size() - 1);
2313   }
2314   return true;
2315 }
2316 
2317 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2318   // A null base expression indicates a null pointer.  These are always
2319   // evaluatable, and they are false unless the offset is zero.
2320   if (!Value.getLValueBase()) {
2321     Result = !Value.getLValueOffset().isZero();
2322     return true;
2323   }
2324 
2325   // We have a non-null base.  These are generally known to be true, but if it's
2326   // a weak declaration it can be null at runtime.
2327   Result = true;
2328   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2329   return !Decl || !Decl->isWeak();
2330 }
2331 
2332 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2333   switch (Val.getKind()) {
2334   case APValue::None:
2335   case APValue::Indeterminate:
2336     return false;
2337   case APValue::Int:
2338     Result = Val.getInt().getBoolValue();
2339     return true;
2340   case APValue::FixedPoint:
2341     Result = Val.getFixedPoint().getBoolValue();
2342     return true;
2343   case APValue::Float:
2344     Result = !Val.getFloat().isZero();
2345     return true;
2346   case APValue::ComplexInt:
2347     Result = Val.getComplexIntReal().getBoolValue() ||
2348              Val.getComplexIntImag().getBoolValue();
2349     return true;
2350   case APValue::ComplexFloat:
2351     Result = !Val.getComplexFloatReal().isZero() ||
2352              !Val.getComplexFloatImag().isZero();
2353     return true;
2354   case APValue::LValue:
2355     return EvalPointerValueAsBool(Val, Result);
2356   case APValue::MemberPointer:
2357     Result = Val.getMemberPointerDecl();
2358     return true;
2359   case APValue::Vector:
2360   case APValue::Array:
2361   case APValue::Struct:
2362   case APValue::Union:
2363   case APValue::AddrLabelDiff:
2364     return false;
2365   }
2366 
2367   llvm_unreachable("unknown APValue kind");
2368 }
2369 
2370 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2371                                        EvalInfo &Info) {
2372   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2373   APValue Val;
2374   if (!Evaluate(Val, Info, E))
2375     return false;
2376   return HandleConversionToBool(Val, Result);
2377 }
2378 
2379 template<typename T>
2380 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2381                            const T &SrcValue, QualType DestType) {
2382   Info.CCEDiag(E, diag::note_constexpr_overflow)
2383     << SrcValue << DestType;
2384   return Info.noteUndefinedBehavior();
2385 }
2386 
2387 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2388                                  QualType SrcType, const APFloat &Value,
2389                                  QualType DestType, APSInt &Result) {
2390   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2391   // Determine whether we are converting to unsigned or signed.
2392   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2393 
2394   Result = APSInt(DestWidth, !DestSigned);
2395   bool ignored;
2396   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2397       & APFloat::opInvalidOp)
2398     return HandleOverflow(Info, E, Value, DestType);
2399   return true;
2400 }
2401 
2402 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2403                                    QualType SrcType, QualType DestType,
2404                                    APFloat &Result) {
2405   APFloat Value = Result;
2406   bool ignored;
2407   Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2408                  APFloat::rmNearestTiesToEven, &ignored);
2409   return true;
2410 }
2411 
2412 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2413                                  QualType DestType, QualType SrcType,
2414                                  const APSInt &Value) {
2415   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2416   // Figure out if this is a truncate, extend or noop cast.
2417   // If the input is signed, do a sign extend, noop, or truncate.
2418   APSInt Result = Value.extOrTrunc(DestWidth);
2419   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2420   if (DestType->isBooleanType())
2421     Result = Value.getBoolValue();
2422   return Result;
2423 }
2424 
2425 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2426                                  QualType SrcType, const APSInt &Value,
2427                                  QualType DestType, APFloat &Result) {
2428   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2429   Result.convertFromAPInt(Value, Value.isSigned(),
2430                           APFloat::rmNearestTiesToEven);
2431   return true;
2432 }
2433 
2434 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2435                                   APValue &Value, const FieldDecl *FD) {
2436   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2437 
2438   if (!Value.isInt()) {
2439     // Trying to store a pointer-cast-to-integer into a bitfield.
2440     // FIXME: In this case, we should provide the diagnostic for casting
2441     // a pointer to an integer.
2442     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2443     Info.FFDiag(E);
2444     return false;
2445   }
2446 
2447   APSInt &Int = Value.getInt();
2448   unsigned OldBitWidth = Int.getBitWidth();
2449   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2450   if (NewBitWidth < OldBitWidth)
2451     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2452   return true;
2453 }
2454 
2455 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2456                                   llvm::APInt &Res) {
2457   APValue SVal;
2458   if (!Evaluate(SVal, Info, E))
2459     return false;
2460   if (SVal.isInt()) {
2461     Res = SVal.getInt();
2462     return true;
2463   }
2464   if (SVal.isFloat()) {
2465     Res = SVal.getFloat().bitcastToAPInt();
2466     return true;
2467   }
2468   if (SVal.isVector()) {
2469     QualType VecTy = E->getType();
2470     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2471     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2472     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2473     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2474     Res = llvm::APInt::getNullValue(VecSize);
2475     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2476       APValue &Elt = SVal.getVectorElt(i);
2477       llvm::APInt EltAsInt;
2478       if (Elt.isInt()) {
2479         EltAsInt = Elt.getInt();
2480       } else if (Elt.isFloat()) {
2481         EltAsInt = Elt.getFloat().bitcastToAPInt();
2482       } else {
2483         // Don't try to handle vectors of anything other than int or float
2484         // (not sure if it's possible to hit this case).
2485         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2486         return false;
2487       }
2488       unsigned BaseEltSize = EltAsInt.getBitWidth();
2489       if (BigEndian)
2490         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2491       else
2492         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2493     }
2494     return true;
2495   }
2496   // Give up if the input isn't an int, float, or vector.  For example, we
2497   // reject "(v4i16)(intptr_t)&a".
2498   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2499   return false;
2500 }
2501 
2502 /// Perform the given integer operation, which is known to need at most BitWidth
2503 /// bits, and check for overflow in the original type (if that type was not an
2504 /// unsigned type).
2505 template<typename Operation>
2506 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2507                                  const APSInt &LHS, const APSInt &RHS,
2508                                  unsigned BitWidth, Operation Op,
2509                                  APSInt &Result) {
2510   if (LHS.isUnsigned()) {
2511     Result = Op(LHS, RHS);
2512     return true;
2513   }
2514 
2515   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2516   Result = Value.trunc(LHS.getBitWidth());
2517   if (Result.extend(BitWidth) != Value) {
2518     if (Info.checkingForUndefinedBehavior())
2519       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2520                                        diag::warn_integer_constant_overflow)
2521           << Result.toString(10) << E->getType();
2522     else
2523       return HandleOverflow(Info, E, Value, E->getType());
2524   }
2525   return true;
2526 }
2527 
2528 /// Perform the given binary integer operation.
2529 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2530                               BinaryOperatorKind Opcode, APSInt RHS,
2531                               APSInt &Result) {
2532   switch (Opcode) {
2533   default:
2534     Info.FFDiag(E);
2535     return false;
2536   case BO_Mul:
2537     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2538                                 std::multiplies<APSInt>(), Result);
2539   case BO_Add:
2540     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2541                                 std::plus<APSInt>(), Result);
2542   case BO_Sub:
2543     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2544                                 std::minus<APSInt>(), Result);
2545   case BO_And: Result = LHS & RHS; return true;
2546   case BO_Xor: Result = LHS ^ RHS; return true;
2547   case BO_Or:  Result = LHS | RHS; return true;
2548   case BO_Div:
2549   case BO_Rem:
2550     if (RHS == 0) {
2551       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2552       return false;
2553     }
2554     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2555     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2556     // this operation and gives the two's complement result.
2557     if (RHS.isNegative() && RHS.isAllOnesValue() &&
2558         LHS.isSigned() && LHS.isMinSignedValue())
2559       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2560                             E->getType());
2561     return true;
2562   case BO_Shl: {
2563     if (Info.getLangOpts().OpenCL)
2564       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2565       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2566                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2567                     RHS.isUnsigned());
2568     else if (RHS.isSigned() && RHS.isNegative()) {
2569       // During constant-folding, a negative shift is an opposite shift. Such
2570       // a shift is not a constant expression.
2571       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2572       RHS = -RHS;
2573       goto shift_right;
2574     }
2575   shift_left:
2576     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2577     // the shifted type.
2578     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2579     if (SA != RHS) {
2580       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2581         << RHS << E->getType() << LHS.getBitWidth();
2582     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2583       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2584       // operand, and must not overflow the corresponding unsigned type.
2585       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2586       // E1 x 2^E2 module 2^N.
2587       if (LHS.isNegative())
2588         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2589       else if (LHS.countLeadingZeros() < SA)
2590         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2591     }
2592     Result = LHS << SA;
2593     return true;
2594   }
2595   case BO_Shr: {
2596     if (Info.getLangOpts().OpenCL)
2597       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2598       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2599                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2600                     RHS.isUnsigned());
2601     else if (RHS.isSigned() && RHS.isNegative()) {
2602       // During constant-folding, a negative shift is an opposite shift. Such a
2603       // shift is not a constant expression.
2604       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2605       RHS = -RHS;
2606       goto shift_left;
2607     }
2608   shift_right:
2609     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2610     // shifted type.
2611     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2612     if (SA != RHS)
2613       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2614         << RHS << E->getType() << LHS.getBitWidth();
2615     Result = LHS >> SA;
2616     return true;
2617   }
2618 
2619   case BO_LT: Result = LHS < RHS; return true;
2620   case BO_GT: Result = LHS > RHS; return true;
2621   case BO_LE: Result = LHS <= RHS; return true;
2622   case BO_GE: Result = LHS >= RHS; return true;
2623   case BO_EQ: Result = LHS == RHS; return true;
2624   case BO_NE: Result = LHS != RHS; return true;
2625   case BO_Cmp:
2626     llvm_unreachable("BO_Cmp should be handled elsewhere");
2627   }
2628 }
2629 
2630 /// Perform the given binary floating-point operation, in-place, on LHS.
2631 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2632                                   APFloat &LHS, BinaryOperatorKind Opcode,
2633                                   const APFloat &RHS) {
2634   switch (Opcode) {
2635   default:
2636     Info.FFDiag(E);
2637     return false;
2638   case BO_Mul:
2639     LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2640     break;
2641   case BO_Add:
2642     LHS.add(RHS, APFloat::rmNearestTiesToEven);
2643     break;
2644   case BO_Sub:
2645     LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2646     break;
2647   case BO_Div:
2648     // [expr.mul]p4:
2649     //   If the second operand of / or % is zero the behavior is undefined.
2650     if (RHS.isZero())
2651       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2652     LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2653     break;
2654   }
2655 
2656   // [expr.pre]p4:
2657   //   If during the evaluation of an expression, the result is not
2658   //   mathematically defined [...], the behavior is undefined.
2659   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2660   if (LHS.isNaN()) {
2661     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2662     return Info.noteUndefinedBehavior();
2663   }
2664   return true;
2665 }
2666 
2667 static bool handleLogicalOpForVector(const APInt &LHSValue,
2668                                      BinaryOperatorKind Opcode,
2669                                      const APInt &RHSValue, APInt &Result) {
2670   bool LHS = (LHSValue != 0);
2671   bool RHS = (RHSValue != 0);
2672 
2673   if (Opcode == BO_LAnd)
2674     Result = LHS && RHS;
2675   else
2676     Result = LHS || RHS;
2677   return true;
2678 }
2679 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2680                                      BinaryOperatorKind Opcode,
2681                                      const APFloat &RHSValue, APInt &Result) {
2682   bool LHS = !LHSValue.isZero();
2683   bool RHS = !RHSValue.isZero();
2684 
2685   if (Opcode == BO_LAnd)
2686     Result = LHS && RHS;
2687   else
2688     Result = LHS || RHS;
2689   return true;
2690 }
2691 
2692 static bool handleLogicalOpForVector(const APValue &LHSValue,
2693                                      BinaryOperatorKind Opcode,
2694                                      const APValue &RHSValue, APInt &Result) {
2695   // The result is always an int type, however operands match the first.
2696   if (LHSValue.getKind() == APValue::Int)
2697     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2698                                     RHSValue.getInt(), Result);
2699   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2700   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2701                                   RHSValue.getFloat(), Result);
2702 }
2703 
2704 template <typename APTy>
2705 static bool
2706 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2707                                const APTy &RHSValue, APInt &Result) {
2708   switch (Opcode) {
2709   default:
2710     llvm_unreachable("unsupported binary operator");
2711   case BO_EQ:
2712     Result = (LHSValue == RHSValue);
2713     break;
2714   case BO_NE:
2715     Result = (LHSValue != RHSValue);
2716     break;
2717   case BO_LT:
2718     Result = (LHSValue < RHSValue);
2719     break;
2720   case BO_GT:
2721     Result = (LHSValue > RHSValue);
2722     break;
2723   case BO_LE:
2724     Result = (LHSValue <= RHSValue);
2725     break;
2726   case BO_GE:
2727     Result = (LHSValue >= RHSValue);
2728     break;
2729   }
2730 
2731   return true;
2732 }
2733 
2734 static bool handleCompareOpForVector(const APValue &LHSValue,
2735                                      BinaryOperatorKind Opcode,
2736                                      const APValue &RHSValue, APInt &Result) {
2737   // The result is always an int type, however operands match the first.
2738   if (LHSValue.getKind() == APValue::Int)
2739     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2740                                           RHSValue.getInt(), Result);
2741   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2742   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2743                                         RHSValue.getFloat(), Result);
2744 }
2745 
2746 // Perform binary operations for vector types, in place on the LHS.
2747 static bool handleVectorVectorBinOp(EvalInfo &Info, const Expr *E,
2748                                     BinaryOperatorKind Opcode,
2749                                     APValue &LHSValue,
2750                                     const APValue &RHSValue) {
2751   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2752          "Operation not supported on vector types");
2753 
2754   const auto *VT = E->getType()->castAs<VectorType>();
2755   unsigned NumElements = VT->getNumElements();
2756   QualType EltTy = VT->getElementType();
2757 
2758   // In the cases (typically C as I've observed) where we aren't evaluating
2759   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2760   // just give up.
2761   if (!LHSValue.isVector()) {
2762     assert(LHSValue.isLValue() &&
2763            "A vector result that isn't a vector OR uncalculated LValue");
2764     Info.FFDiag(E);
2765     return false;
2766   }
2767 
2768   assert(LHSValue.getVectorLength() == NumElements &&
2769          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2770 
2771   SmallVector<APValue, 4> ResultElements;
2772 
2773   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
2774     APValue LHSElt = LHSValue.getVectorElt(EltNum);
2775     APValue RHSElt = RHSValue.getVectorElt(EltNum);
2776 
2777     if (EltTy->isIntegerType()) {
2778       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
2779                        EltTy->isUnsignedIntegerType()};
2780       bool Success = true;
2781 
2782       if (BinaryOperator::isLogicalOp(Opcode))
2783         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2784       else if (BinaryOperator::isComparisonOp(Opcode))
2785         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2786       else
2787         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
2788                                     RHSElt.getInt(), EltResult);
2789 
2790       if (!Success) {
2791         Info.FFDiag(E);
2792         return false;
2793       }
2794       ResultElements.emplace_back(EltResult);
2795 
2796     } else if (EltTy->isFloatingType()) {
2797       assert(LHSElt.getKind() == APValue::Float &&
2798              RHSElt.getKind() == APValue::Float &&
2799              "Mismatched LHS/RHS/Result Type");
2800       APFloat LHSFloat = LHSElt.getFloat();
2801 
2802       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
2803                                  RHSElt.getFloat())) {
2804         Info.FFDiag(E);
2805         return false;
2806       }
2807 
2808       ResultElements.emplace_back(LHSFloat);
2809     }
2810   }
2811 
2812   LHSValue = APValue(ResultElements.data(), ResultElements.size());
2813   return true;
2814 }
2815 
2816 /// Cast an lvalue referring to a base subobject to a derived class, by
2817 /// truncating the lvalue's path to the given length.
2818 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2819                                const RecordDecl *TruncatedType,
2820                                unsigned TruncatedElements) {
2821   SubobjectDesignator &D = Result.Designator;
2822 
2823   // Check we actually point to a derived class object.
2824   if (TruncatedElements == D.Entries.size())
2825     return true;
2826   assert(TruncatedElements >= D.MostDerivedPathLength &&
2827          "not casting to a derived class");
2828   if (!Result.checkSubobject(Info, E, CSK_Derived))
2829     return false;
2830 
2831   // Truncate the path to the subobject, and remove any derived-to-base offsets.
2832   const RecordDecl *RD = TruncatedType;
2833   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2834     if (RD->isInvalidDecl()) return false;
2835     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2836     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2837     if (isVirtualBaseClass(D.Entries[I]))
2838       Result.Offset -= Layout.getVBaseClassOffset(Base);
2839     else
2840       Result.Offset -= Layout.getBaseClassOffset(Base);
2841     RD = Base;
2842   }
2843   D.Entries.resize(TruncatedElements);
2844   return true;
2845 }
2846 
2847 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2848                                    const CXXRecordDecl *Derived,
2849                                    const CXXRecordDecl *Base,
2850                                    const ASTRecordLayout *RL = nullptr) {
2851   if (!RL) {
2852     if (Derived->isInvalidDecl()) return false;
2853     RL = &Info.Ctx.getASTRecordLayout(Derived);
2854   }
2855 
2856   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2857   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2858   return true;
2859 }
2860 
2861 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2862                              const CXXRecordDecl *DerivedDecl,
2863                              const CXXBaseSpecifier *Base) {
2864   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2865 
2866   if (!Base->isVirtual())
2867     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2868 
2869   SubobjectDesignator &D = Obj.Designator;
2870   if (D.Invalid)
2871     return false;
2872 
2873   // Extract most-derived object and corresponding type.
2874   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2875   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2876     return false;
2877 
2878   // Find the virtual base class.
2879   if (DerivedDecl->isInvalidDecl()) return false;
2880   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2881   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2882   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2883   return true;
2884 }
2885 
2886 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2887                                  QualType Type, LValue &Result) {
2888   for (CastExpr::path_const_iterator PathI = E->path_begin(),
2889                                      PathE = E->path_end();
2890        PathI != PathE; ++PathI) {
2891     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2892                           *PathI))
2893       return false;
2894     Type = (*PathI)->getType();
2895   }
2896   return true;
2897 }
2898 
2899 /// Cast an lvalue referring to a derived class to a known base subobject.
2900 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2901                             const CXXRecordDecl *DerivedRD,
2902                             const CXXRecordDecl *BaseRD) {
2903   CXXBasePaths Paths(/*FindAmbiguities=*/false,
2904                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
2905   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2906     llvm_unreachable("Class must be derived from the passed in base class!");
2907 
2908   for (CXXBasePathElement &Elem : Paths.front())
2909     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2910       return false;
2911   return true;
2912 }
2913 
2914 /// Update LVal to refer to the given field, which must be a member of the type
2915 /// currently described by LVal.
2916 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2917                                const FieldDecl *FD,
2918                                const ASTRecordLayout *RL = nullptr) {
2919   if (!RL) {
2920     if (FD->getParent()->isInvalidDecl()) return false;
2921     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2922   }
2923 
2924   unsigned I = FD->getFieldIndex();
2925   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2926   LVal.addDecl(Info, E, FD);
2927   return true;
2928 }
2929 
2930 /// Update LVal to refer to the given indirect field.
2931 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2932                                        LValue &LVal,
2933                                        const IndirectFieldDecl *IFD) {
2934   for (const auto *C : IFD->chain())
2935     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2936       return false;
2937   return true;
2938 }
2939 
2940 /// Get the size of the given type in char units.
2941 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2942                          QualType Type, CharUnits &Size) {
2943   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2944   // extension.
2945   if (Type->isVoidType() || Type->isFunctionType()) {
2946     Size = CharUnits::One();
2947     return true;
2948   }
2949 
2950   if (Type->isDependentType()) {
2951     Info.FFDiag(Loc);
2952     return false;
2953   }
2954 
2955   if (!Type->isConstantSizeType()) {
2956     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2957     // FIXME: Better diagnostic.
2958     Info.FFDiag(Loc);
2959     return false;
2960   }
2961 
2962   Size = Info.Ctx.getTypeSizeInChars(Type);
2963   return true;
2964 }
2965 
2966 /// Update a pointer value to model pointer arithmetic.
2967 /// \param Info - Information about the ongoing evaluation.
2968 /// \param E - The expression being evaluated, for diagnostic purposes.
2969 /// \param LVal - The pointer value to be updated.
2970 /// \param EltTy - The pointee type represented by LVal.
2971 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2972 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2973                                         LValue &LVal, QualType EltTy,
2974                                         APSInt Adjustment) {
2975   CharUnits SizeOfPointee;
2976   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2977     return false;
2978 
2979   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2980   return true;
2981 }
2982 
2983 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2984                                         LValue &LVal, QualType EltTy,
2985                                         int64_t Adjustment) {
2986   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2987                                      APSInt::get(Adjustment));
2988 }
2989 
2990 /// Update an lvalue to refer to a component of a complex number.
2991 /// \param Info - Information about the ongoing evaluation.
2992 /// \param LVal - The lvalue to be updated.
2993 /// \param EltTy - The complex number's component type.
2994 /// \param Imag - False for the real component, true for the imaginary.
2995 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2996                                        LValue &LVal, QualType EltTy,
2997                                        bool Imag) {
2998   if (Imag) {
2999     CharUnits SizeOfComponent;
3000     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3001       return false;
3002     LVal.Offset += SizeOfComponent;
3003   }
3004   LVal.addComplex(Info, E, EltTy, Imag);
3005   return true;
3006 }
3007 
3008 /// Try to evaluate the initializer for a variable declaration.
3009 ///
3010 /// \param Info   Information about the ongoing evaluation.
3011 /// \param E      An expression to be used when printing diagnostics.
3012 /// \param VD     The variable whose initializer should be obtained.
3013 /// \param Frame  The frame in which the variable was created. Must be null
3014 ///               if this variable is not local to the evaluation.
3015 /// \param Result Filled in with a pointer to the value of the variable.
3016 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3017                                 const VarDecl *VD, CallStackFrame *Frame,
3018                                 APValue *&Result, const LValue *LVal) {
3019 
3020   // If this is a parameter to an active constexpr function call, perform
3021   // argument substitution.
3022   if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
3023     // Assume arguments of a potential constant expression are unknown
3024     // constant expressions.
3025     if (Info.checkingPotentialConstantExpression())
3026       return false;
3027     if (!Frame || !Frame->Arguments) {
3028       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3029       return false;
3030     }
3031     Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
3032     return true;
3033   }
3034 
3035   // If this is a local variable, dig out its value.
3036   if (Frame) {
3037     Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
3038                   : Frame->getCurrentTemporary(VD);
3039     if (!Result) {
3040       // Assume variables referenced within a lambda's call operator that were
3041       // not declared within the call operator are captures and during checking
3042       // of a potential constant expression, assume they are unknown constant
3043       // expressions.
3044       assert(isLambdaCallOperator(Frame->Callee) &&
3045              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3046              "missing value for local variable");
3047       if (Info.checkingPotentialConstantExpression())
3048         return false;
3049       // FIXME: implement capture evaluation during constant expr evaluation.
3050       Info.FFDiag(E->getBeginLoc(),
3051                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3052           << "captures not currently allowed";
3053       return false;
3054     }
3055     return true;
3056   }
3057 
3058   // Dig out the initializer, and use the declaration which it's attached to.
3059   const Expr *Init = VD->getAnyInitializer(VD);
3060   if (!Init || Init->isValueDependent()) {
3061     // If we're checking a potential constant expression, the variable could be
3062     // initialized later.
3063     if (!Info.checkingPotentialConstantExpression())
3064       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3065     return false;
3066   }
3067 
3068   // If we're currently evaluating the initializer of this declaration, use that
3069   // in-flight value.
3070   if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
3071     Result = Info.EvaluatingDeclValue;
3072     return true;
3073   }
3074 
3075   // Never evaluate the initializer of a weak variable. We can't be sure that
3076   // this is the definition which will be used.
3077   if (VD->isWeak()) {
3078     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3079     return false;
3080   }
3081 
3082   // Check that we can fold the initializer. In C++, we will have already done
3083   // this in the cases where it matters for conformance.
3084   SmallVector<PartialDiagnosticAt, 8> Notes;
3085   if (!VD->evaluateValue(Notes)) {
3086     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
3087               Notes.size() + 1) << VD;
3088     Info.Note(VD->getLocation(), diag::note_declared_at);
3089     Info.addNotes(Notes);
3090     return false;
3091   } else if (!VD->checkInitIsICE()) {
3092     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
3093                  Notes.size() + 1) << VD;
3094     Info.Note(VD->getLocation(), diag::note_declared_at);
3095     Info.addNotes(Notes);
3096   }
3097 
3098   Result = VD->getEvaluatedValue();
3099   return true;
3100 }
3101 
3102 static bool IsConstNonVolatile(QualType T) {
3103   Qualifiers Quals = T.getQualifiers();
3104   return Quals.hasConst() && !Quals.hasVolatile();
3105 }
3106 
3107 /// Get the base index of the given base class within an APValue representing
3108 /// the given derived class.
3109 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3110                              const CXXRecordDecl *Base) {
3111   Base = Base->getCanonicalDecl();
3112   unsigned Index = 0;
3113   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3114          E = Derived->bases_end(); I != E; ++I, ++Index) {
3115     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3116       return Index;
3117   }
3118 
3119   llvm_unreachable("base class missing from derived class's bases list");
3120 }
3121 
3122 /// Extract the value of a character from a string literal.
3123 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3124                                             uint64_t Index) {
3125   assert(!isa<SourceLocExpr>(Lit) &&
3126          "SourceLocExpr should have already been converted to a StringLiteral");
3127 
3128   // FIXME: Support MakeStringConstant
3129   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3130     std::string Str;
3131     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3132     assert(Index <= Str.size() && "Index too large");
3133     return APSInt::getUnsigned(Str.c_str()[Index]);
3134   }
3135 
3136   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3137     Lit = PE->getFunctionName();
3138   const StringLiteral *S = cast<StringLiteral>(Lit);
3139   const ConstantArrayType *CAT =
3140       Info.Ctx.getAsConstantArrayType(S->getType());
3141   assert(CAT && "string literal isn't an array");
3142   QualType CharType = CAT->getElementType();
3143   assert(CharType->isIntegerType() && "unexpected character type");
3144 
3145   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3146                CharType->isUnsignedIntegerType());
3147   if (Index < S->getLength())
3148     Value = S->getCodeUnit(Index);
3149   return Value;
3150 }
3151 
3152 // Expand a string literal into an array of characters.
3153 //
3154 // FIXME: This is inefficient; we should probably introduce something similar
3155 // to the LLVM ConstantDataArray to make this cheaper.
3156 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3157                                 APValue &Result,
3158                                 QualType AllocType = QualType()) {
3159   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3160       AllocType.isNull() ? S->getType() : AllocType);
3161   assert(CAT && "string literal isn't an array");
3162   QualType CharType = CAT->getElementType();
3163   assert(CharType->isIntegerType() && "unexpected character type");
3164 
3165   unsigned Elts = CAT->getSize().getZExtValue();
3166   Result = APValue(APValue::UninitArray(),
3167                    std::min(S->getLength(), Elts), Elts);
3168   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3169                CharType->isUnsignedIntegerType());
3170   if (Result.hasArrayFiller())
3171     Result.getArrayFiller() = APValue(Value);
3172   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3173     Value = S->getCodeUnit(I);
3174     Result.getArrayInitializedElt(I) = APValue(Value);
3175   }
3176 }
3177 
3178 // Expand an array so that it has more than Index filled elements.
3179 static void expandArray(APValue &Array, unsigned Index) {
3180   unsigned Size = Array.getArraySize();
3181   assert(Index < Size);
3182 
3183   // Always at least double the number of elements for which we store a value.
3184   unsigned OldElts = Array.getArrayInitializedElts();
3185   unsigned NewElts = std::max(Index+1, OldElts * 2);
3186   NewElts = std::min(Size, std::max(NewElts, 8u));
3187 
3188   // Copy the data across.
3189   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3190   for (unsigned I = 0; I != OldElts; ++I)
3191     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3192   for (unsigned I = OldElts; I != NewElts; ++I)
3193     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3194   if (NewValue.hasArrayFiller())
3195     NewValue.getArrayFiller() = Array.getArrayFiller();
3196   Array.swap(NewValue);
3197 }
3198 
3199 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3200 /// conversion. If it's of class type, we may assume that the copy operation
3201 /// is trivial. Note that this is never true for a union type with fields
3202 /// (because the copy always "reads" the active member) and always true for
3203 /// a non-class type.
3204 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3205 static bool isReadByLvalueToRvalueConversion(QualType T) {
3206   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3207   return !RD || isReadByLvalueToRvalueConversion(RD);
3208 }
3209 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3210   // FIXME: A trivial copy of a union copies the object representation, even if
3211   // the union is empty.
3212   if (RD->isUnion())
3213     return !RD->field_empty();
3214   if (RD->isEmpty())
3215     return false;
3216 
3217   for (auto *Field : RD->fields())
3218     if (!Field->isUnnamedBitfield() &&
3219         isReadByLvalueToRvalueConversion(Field->getType()))
3220       return true;
3221 
3222   for (auto &BaseSpec : RD->bases())
3223     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3224       return true;
3225 
3226   return false;
3227 }
3228 
3229 /// Diagnose an attempt to read from any unreadable field within the specified
3230 /// type, which might be a class type.
3231 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3232                                   QualType T) {
3233   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3234   if (!RD)
3235     return false;
3236 
3237   if (!RD->hasMutableFields())
3238     return false;
3239 
3240   for (auto *Field : RD->fields()) {
3241     // If we're actually going to read this field in some way, then it can't
3242     // be mutable. If we're in a union, then assigning to a mutable field
3243     // (even an empty one) can change the active member, so that's not OK.
3244     // FIXME: Add core issue number for the union case.
3245     if (Field->isMutable() &&
3246         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3247       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3248       Info.Note(Field->getLocation(), diag::note_declared_at);
3249       return true;
3250     }
3251 
3252     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3253       return true;
3254   }
3255 
3256   for (auto &BaseSpec : RD->bases())
3257     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3258       return true;
3259 
3260   // All mutable fields were empty, and thus not actually read.
3261   return false;
3262 }
3263 
3264 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3265                                         APValue::LValueBase Base,
3266                                         bool MutableSubobject = false) {
3267   // A temporary we created.
3268   if (Base.getCallIndex())
3269     return true;
3270 
3271   auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3272   if (!Evaluating)
3273     return false;
3274 
3275   auto *BaseD = Base.dyn_cast<const ValueDecl*>();
3276 
3277   switch (Info.IsEvaluatingDecl) {
3278   case EvalInfo::EvaluatingDeclKind::None:
3279     return false;
3280 
3281   case EvalInfo::EvaluatingDeclKind::Ctor:
3282     // The variable whose initializer we're evaluating.
3283     if (BaseD)
3284       return declaresSameEntity(Evaluating, BaseD);
3285 
3286     // A temporary lifetime-extended by the variable whose initializer we're
3287     // evaluating.
3288     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3289       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3290         return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating);
3291     return false;
3292 
3293   case EvalInfo::EvaluatingDeclKind::Dtor:
3294     // C++2a [expr.const]p6:
3295     //   [during constant destruction] the lifetime of a and its non-mutable
3296     //   subobjects (but not its mutable subobjects) [are] considered to start
3297     //   within e.
3298     //
3299     // FIXME: We can meaningfully extend this to cover non-const objects, but
3300     // we will need special handling: we should be able to access only
3301     // subobjects of such objects that are themselves declared const.
3302     if (!BaseD ||
3303         !(BaseD->getType().isConstQualified() ||
3304           BaseD->getType()->isReferenceType()) ||
3305         MutableSubobject)
3306       return false;
3307     return declaresSameEntity(Evaluating, BaseD);
3308   }
3309 
3310   llvm_unreachable("unknown evaluating decl kind");
3311 }
3312 
3313 namespace {
3314 /// A handle to a complete object (an object that is not a subobject of
3315 /// another object).
3316 struct CompleteObject {
3317   /// The identity of the object.
3318   APValue::LValueBase Base;
3319   /// The value of the complete object.
3320   APValue *Value;
3321   /// The type of the complete object.
3322   QualType Type;
3323 
3324   CompleteObject() : Value(nullptr) {}
3325   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3326       : Base(Base), Value(Value), Type(Type) {}
3327 
3328   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3329     // If this isn't a "real" access (eg, if it's just accessing the type
3330     // info), allow it. We assume the type doesn't change dynamically for
3331     // subobjects of constexpr objects (even though we'd hit UB here if it
3332     // did). FIXME: Is this right?
3333     if (!isAnyAccess(AK))
3334       return true;
3335 
3336     // In C++14 onwards, it is permitted to read a mutable member whose
3337     // lifetime began within the evaluation.
3338     // FIXME: Should we also allow this in C++11?
3339     if (!Info.getLangOpts().CPlusPlus14)
3340       return false;
3341     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3342   }
3343 
3344   explicit operator bool() const { return !Type.isNull(); }
3345 };
3346 } // end anonymous namespace
3347 
3348 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3349                                  bool IsMutable = false) {
3350   // C++ [basic.type.qualifier]p1:
3351   // - A const object is an object of type const T or a non-mutable subobject
3352   //   of a const object.
3353   if (ObjType.isConstQualified() && !IsMutable)
3354     SubobjType.addConst();
3355   // - A volatile object is an object of type const T or a subobject of a
3356   //   volatile object.
3357   if (ObjType.isVolatileQualified())
3358     SubobjType.addVolatile();
3359   return SubobjType;
3360 }
3361 
3362 /// Find the designated sub-object of an rvalue.
3363 template<typename SubobjectHandler>
3364 typename SubobjectHandler::result_type
3365 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3366               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3367   if (Sub.Invalid)
3368     // A diagnostic will have already been produced.
3369     return handler.failed();
3370   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3371     if (Info.getLangOpts().CPlusPlus11)
3372       Info.FFDiag(E, Sub.isOnePastTheEnd()
3373                          ? diag::note_constexpr_access_past_end
3374                          : diag::note_constexpr_access_unsized_array)
3375           << handler.AccessKind;
3376     else
3377       Info.FFDiag(E);
3378     return handler.failed();
3379   }
3380 
3381   APValue *O = Obj.Value;
3382   QualType ObjType = Obj.Type;
3383   const FieldDecl *LastField = nullptr;
3384   const FieldDecl *VolatileField = nullptr;
3385 
3386   // Walk the designator's path to find the subobject.
3387   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3388     // Reading an indeterminate value is undefined, but assigning over one is OK.
3389     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3390         (O->isIndeterminate() &&
3391          !isValidIndeterminateAccess(handler.AccessKind))) {
3392       if (!Info.checkingPotentialConstantExpression())
3393         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3394             << handler.AccessKind << O->isIndeterminate();
3395       return handler.failed();
3396     }
3397 
3398     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3399     //    const and volatile semantics are not applied on an object under
3400     //    {con,de}struction.
3401     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3402         ObjType->isRecordType() &&
3403         Info.isEvaluatingCtorDtor(
3404             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3405                                          Sub.Entries.begin() + I)) !=
3406                           ConstructionPhase::None) {
3407       ObjType = Info.Ctx.getCanonicalType(ObjType);
3408       ObjType.removeLocalConst();
3409       ObjType.removeLocalVolatile();
3410     }
3411 
3412     // If this is our last pass, check that the final object type is OK.
3413     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3414       // Accesses to volatile objects are prohibited.
3415       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3416         if (Info.getLangOpts().CPlusPlus) {
3417           int DiagKind;
3418           SourceLocation Loc;
3419           const NamedDecl *Decl = nullptr;
3420           if (VolatileField) {
3421             DiagKind = 2;
3422             Loc = VolatileField->getLocation();
3423             Decl = VolatileField;
3424           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3425             DiagKind = 1;
3426             Loc = VD->getLocation();
3427             Decl = VD;
3428           } else {
3429             DiagKind = 0;
3430             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3431               Loc = E->getExprLoc();
3432           }
3433           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3434               << handler.AccessKind << DiagKind << Decl;
3435           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3436         } else {
3437           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3438         }
3439         return handler.failed();
3440       }
3441 
3442       // If we are reading an object of class type, there may still be more
3443       // things we need to check: if there are any mutable subobjects, we
3444       // cannot perform this read. (This only happens when performing a trivial
3445       // copy or assignment.)
3446       if (ObjType->isRecordType() &&
3447           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3448           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3449         return handler.failed();
3450     }
3451 
3452     if (I == N) {
3453       if (!handler.found(*O, ObjType))
3454         return false;
3455 
3456       // If we modified a bit-field, truncate it to the right width.
3457       if (isModification(handler.AccessKind) &&
3458           LastField && LastField->isBitField() &&
3459           !truncateBitfieldValue(Info, E, *O, LastField))
3460         return false;
3461 
3462       return true;
3463     }
3464 
3465     LastField = nullptr;
3466     if (ObjType->isArrayType()) {
3467       // Next subobject is an array element.
3468       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3469       assert(CAT && "vla in literal type?");
3470       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3471       if (CAT->getSize().ule(Index)) {
3472         // Note, it should not be possible to form a pointer with a valid
3473         // designator which points more than one past the end of the array.
3474         if (Info.getLangOpts().CPlusPlus11)
3475           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3476             << handler.AccessKind;
3477         else
3478           Info.FFDiag(E);
3479         return handler.failed();
3480       }
3481 
3482       ObjType = CAT->getElementType();
3483 
3484       if (O->getArrayInitializedElts() > Index)
3485         O = &O->getArrayInitializedElt(Index);
3486       else if (!isRead(handler.AccessKind)) {
3487         expandArray(*O, Index);
3488         O = &O->getArrayInitializedElt(Index);
3489       } else
3490         O = &O->getArrayFiller();
3491     } else if (ObjType->isAnyComplexType()) {
3492       // Next subobject is a complex number.
3493       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3494       if (Index > 1) {
3495         if (Info.getLangOpts().CPlusPlus11)
3496           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3497             << handler.AccessKind;
3498         else
3499           Info.FFDiag(E);
3500         return handler.failed();
3501       }
3502 
3503       ObjType = getSubobjectType(
3504           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3505 
3506       assert(I == N - 1 && "extracting subobject of scalar?");
3507       if (O->isComplexInt()) {
3508         return handler.found(Index ? O->getComplexIntImag()
3509                                    : O->getComplexIntReal(), ObjType);
3510       } else {
3511         assert(O->isComplexFloat());
3512         return handler.found(Index ? O->getComplexFloatImag()
3513                                    : O->getComplexFloatReal(), ObjType);
3514       }
3515     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3516       if (Field->isMutable() &&
3517           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3518         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3519           << handler.AccessKind << Field;
3520         Info.Note(Field->getLocation(), diag::note_declared_at);
3521         return handler.failed();
3522       }
3523 
3524       // Next subobject is a class, struct or union field.
3525       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3526       if (RD->isUnion()) {
3527         const FieldDecl *UnionField = O->getUnionField();
3528         if (!UnionField ||
3529             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3530           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3531             // Placement new onto an inactive union member makes it active.
3532             O->setUnion(Field, APValue());
3533           } else {
3534             // FIXME: If O->getUnionValue() is absent, report that there's no
3535             // active union member rather than reporting the prior active union
3536             // member. We'll need to fix nullptr_t to not use APValue() as its
3537             // representation first.
3538             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3539                 << handler.AccessKind << Field << !UnionField << UnionField;
3540             return handler.failed();
3541           }
3542         }
3543         O = &O->getUnionValue();
3544       } else
3545         O = &O->getStructField(Field->getFieldIndex());
3546 
3547       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3548       LastField = Field;
3549       if (Field->getType().isVolatileQualified())
3550         VolatileField = Field;
3551     } else {
3552       // Next subobject is a base class.
3553       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3554       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3555       O = &O->getStructBase(getBaseIndex(Derived, Base));
3556 
3557       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3558     }
3559   }
3560 }
3561 
3562 namespace {
3563 struct ExtractSubobjectHandler {
3564   EvalInfo &Info;
3565   const Expr *E;
3566   APValue &Result;
3567   const AccessKinds AccessKind;
3568 
3569   typedef bool result_type;
3570   bool failed() { return false; }
3571   bool found(APValue &Subobj, QualType SubobjType) {
3572     Result = Subobj;
3573     if (AccessKind == AK_ReadObjectRepresentation)
3574       return true;
3575     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3576   }
3577   bool found(APSInt &Value, QualType SubobjType) {
3578     Result = APValue(Value);
3579     return true;
3580   }
3581   bool found(APFloat &Value, QualType SubobjType) {
3582     Result = APValue(Value);
3583     return true;
3584   }
3585 };
3586 } // end anonymous namespace
3587 
3588 /// Extract the designated sub-object of an rvalue.
3589 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3590                              const CompleteObject &Obj,
3591                              const SubobjectDesignator &Sub, APValue &Result,
3592                              AccessKinds AK = AK_Read) {
3593   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3594   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3595   return findSubobject(Info, E, Obj, Sub, Handler);
3596 }
3597 
3598 namespace {
3599 struct ModifySubobjectHandler {
3600   EvalInfo &Info;
3601   APValue &NewVal;
3602   const Expr *E;
3603 
3604   typedef bool result_type;
3605   static const AccessKinds AccessKind = AK_Assign;
3606 
3607   bool checkConst(QualType QT) {
3608     // Assigning to a const object has undefined behavior.
3609     if (QT.isConstQualified()) {
3610       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3611       return false;
3612     }
3613     return true;
3614   }
3615 
3616   bool failed() { return false; }
3617   bool found(APValue &Subobj, QualType SubobjType) {
3618     if (!checkConst(SubobjType))
3619       return false;
3620     // We've been given ownership of NewVal, so just swap it in.
3621     Subobj.swap(NewVal);
3622     return true;
3623   }
3624   bool found(APSInt &Value, QualType SubobjType) {
3625     if (!checkConst(SubobjType))
3626       return false;
3627     if (!NewVal.isInt()) {
3628       // Maybe trying to write a cast pointer value into a complex?
3629       Info.FFDiag(E);
3630       return false;
3631     }
3632     Value = NewVal.getInt();
3633     return true;
3634   }
3635   bool found(APFloat &Value, QualType SubobjType) {
3636     if (!checkConst(SubobjType))
3637       return false;
3638     Value = NewVal.getFloat();
3639     return true;
3640   }
3641 };
3642 } // end anonymous namespace
3643 
3644 const AccessKinds ModifySubobjectHandler::AccessKind;
3645 
3646 /// Update the designated sub-object of an rvalue to the given value.
3647 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3648                             const CompleteObject &Obj,
3649                             const SubobjectDesignator &Sub,
3650                             APValue &NewVal) {
3651   ModifySubobjectHandler Handler = { Info, NewVal, E };
3652   return findSubobject(Info, E, Obj, Sub, Handler);
3653 }
3654 
3655 /// Find the position where two subobject designators diverge, or equivalently
3656 /// the length of the common initial subsequence.
3657 static unsigned FindDesignatorMismatch(QualType ObjType,
3658                                        const SubobjectDesignator &A,
3659                                        const SubobjectDesignator &B,
3660                                        bool &WasArrayIndex) {
3661   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3662   for (/**/; I != N; ++I) {
3663     if (!ObjType.isNull() &&
3664         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3665       // Next subobject is an array element.
3666       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3667         WasArrayIndex = true;
3668         return I;
3669       }
3670       if (ObjType->isAnyComplexType())
3671         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3672       else
3673         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3674     } else {
3675       if (A.Entries[I].getAsBaseOrMember() !=
3676           B.Entries[I].getAsBaseOrMember()) {
3677         WasArrayIndex = false;
3678         return I;
3679       }
3680       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3681         // Next subobject is a field.
3682         ObjType = FD->getType();
3683       else
3684         // Next subobject is a base class.
3685         ObjType = QualType();
3686     }
3687   }
3688   WasArrayIndex = false;
3689   return I;
3690 }
3691 
3692 /// Determine whether the given subobject designators refer to elements of the
3693 /// same array object.
3694 static bool AreElementsOfSameArray(QualType ObjType,
3695                                    const SubobjectDesignator &A,
3696                                    const SubobjectDesignator &B) {
3697   if (A.Entries.size() != B.Entries.size())
3698     return false;
3699 
3700   bool IsArray = A.MostDerivedIsArrayElement;
3701   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3702     // A is a subobject of the array element.
3703     return false;
3704 
3705   // If A (and B) designates an array element, the last entry will be the array
3706   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3707   // of length 1' case, and the entire path must match.
3708   bool WasArrayIndex;
3709   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3710   return CommonLength >= A.Entries.size() - IsArray;
3711 }
3712 
3713 /// Find the complete object to which an LValue refers.
3714 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3715                                          AccessKinds AK, const LValue &LVal,
3716                                          QualType LValType) {
3717   if (LVal.InvalidBase) {
3718     Info.FFDiag(E);
3719     return CompleteObject();
3720   }
3721 
3722   if (!LVal.Base) {
3723     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3724     return CompleteObject();
3725   }
3726 
3727   CallStackFrame *Frame = nullptr;
3728   unsigned Depth = 0;
3729   if (LVal.getLValueCallIndex()) {
3730     std::tie(Frame, Depth) =
3731         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3732     if (!Frame) {
3733       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3734         << AK << LVal.Base.is<const ValueDecl*>();
3735       NoteLValueLocation(Info, LVal.Base);
3736       return CompleteObject();
3737     }
3738   }
3739 
3740   bool IsAccess = isAnyAccess(AK);
3741 
3742   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3743   // is not a constant expression (even if the object is non-volatile). We also
3744   // apply this rule to C++98, in order to conform to the expected 'volatile'
3745   // semantics.
3746   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3747     if (Info.getLangOpts().CPlusPlus)
3748       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3749         << AK << LValType;
3750     else
3751       Info.FFDiag(E);
3752     return CompleteObject();
3753   }
3754 
3755   // Compute value storage location and type of base object.
3756   APValue *BaseVal = nullptr;
3757   QualType BaseType = getType(LVal.Base);
3758 
3759   if (const ConstantExpr *CE =
3760           dyn_cast_or_null<ConstantExpr>(LVal.Base.dyn_cast<const Expr *>())) {
3761     /// Nested immediate invocation have been previously removed so if we found
3762     /// a ConstantExpr it can only be the EvaluatingDecl.
3763     assert(CE->isImmediateInvocation() && CE == Info.EvaluatingDecl);
3764     (void)CE;
3765     BaseVal = Info.EvaluatingDeclValue;
3766   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
3767     // Allow reading from a GUID declaration.
3768     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
3769       if (isModification(AK)) {
3770         // All the remaining cases do not permit modification of the object.
3771         Info.FFDiag(E, diag::note_constexpr_modify_global);
3772         return CompleteObject();
3773       }
3774       APValue &V = GD->getAsAPValue();
3775       if (V.isAbsent()) {
3776         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
3777             << GD->getType();
3778         return CompleteObject();
3779       }
3780       return CompleteObject(LVal.Base, &V, GD->getType());
3781     }
3782 
3783     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3784     // In C++11, constexpr, non-volatile variables initialized with constant
3785     // expressions are constant expressions too. Inside constexpr functions,
3786     // parameters are constant expressions even if they're non-const.
3787     // In C++1y, objects local to a constant expression (those with a Frame) are
3788     // both readable and writable inside constant expressions.
3789     // In C, such things can also be folded, although they are not ICEs.
3790     const VarDecl *VD = dyn_cast<VarDecl>(D);
3791     if (VD) {
3792       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3793         VD = VDef;
3794     }
3795     if (!VD || VD->isInvalidDecl()) {
3796       Info.FFDiag(E);
3797       return CompleteObject();
3798     }
3799 
3800     // Unless we're looking at a local variable or argument in a constexpr call,
3801     // the variable we're reading must be const.
3802     if (!Frame) {
3803       if (Info.getLangOpts().CPlusPlus14 &&
3804           lifetimeStartedInEvaluation(Info, LVal.Base)) {
3805         // OK, we can read and modify an object if we're in the process of
3806         // evaluating its initializer, because its lifetime began in this
3807         // evaluation.
3808       } else if (isModification(AK)) {
3809         // All the remaining cases do not permit modification of the object.
3810         Info.FFDiag(E, diag::note_constexpr_modify_global);
3811         return CompleteObject();
3812       } else if (VD->isConstexpr()) {
3813         // OK, we can read this variable.
3814       } else if (BaseType->isIntegralOrEnumerationType()) {
3815         // In OpenCL if a variable is in constant address space it is a const
3816         // value.
3817         if (!(BaseType.isConstQualified() ||
3818               (Info.getLangOpts().OpenCL &&
3819                BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3820           if (!IsAccess)
3821             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3822           if (Info.getLangOpts().CPlusPlus) {
3823             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3824             Info.Note(VD->getLocation(), diag::note_declared_at);
3825           } else {
3826             Info.FFDiag(E);
3827           }
3828           return CompleteObject();
3829         }
3830       } else if (!IsAccess) {
3831         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3832       } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3833         // We support folding of const floating-point types, in order to make
3834         // static const data members of such types (supported as an extension)
3835         // more useful.
3836         if (Info.getLangOpts().CPlusPlus11) {
3837           Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3838           Info.Note(VD->getLocation(), diag::note_declared_at);
3839         } else {
3840           Info.CCEDiag(E);
3841         }
3842       } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3843         Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3844         // Keep evaluating to see what we can do.
3845       } else {
3846         // FIXME: Allow folding of values of any literal type in all languages.
3847         if (Info.checkingPotentialConstantExpression() &&
3848             VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3849           // The definition of this variable could be constexpr. We can't
3850           // access it right now, but may be able to in future.
3851         } else if (Info.getLangOpts().CPlusPlus11) {
3852           Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3853           Info.Note(VD->getLocation(), diag::note_declared_at);
3854         } else {
3855           Info.FFDiag(E);
3856         }
3857         return CompleteObject();
3858       }
3859     }
3860 
3861     if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
3862       return CompleteObject();
3863   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
3864     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
3865     if (!Alloc) {
3866       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
3867       return CompleteObject();
3868     }
3869     return CompleteObject(LVal.Base, &(*Alloc)->Value,
3870                           LVal.Base.getDynamicAllocType());
3871   } else {
3872     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3873 
3874     if (!Frame) {
3875       if (const MaterializeTemporaryExpr *MTE =
3876               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
3877         assert(MTE->getStorageDuration() == SD_Static &&
3878                "should have a frame for a non-global materialized temporary");
3879 
3880         // Per C++1y [expr.const]p2:
3881         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3882         //   - a [...] glvalue of integral or enumeration type that refers to
3883         //     a non-volatile const object [...]
3884         //   [...]
3885         //   - a [...] glvalue of literal type that refers to a non-volatile
3886         //     object whose lifetime began within the evaluation of e.
3887         //
3888         // C++11 misses the 'began within the evaluation of e' check and
3889         // instead allows all temporaries, including things like:
3890         //   int &&r = 1;
3891         //   int x = ++r;
3892         //   constexpr int k = r;
3893         // Therefore we use the C++14 rules in C++11 too.
3894         //
3895         // Note that temporaries whose lifetimes began while evaluating a
3896         // variable's constructor are not usable while evaluating the
3897         // corresponding destructor, not even if they're of const-qualified
3898         // types.
3899         if (!(BaseType.isConstQualified() &&
3900               BaseType->isIntegralOrEnumerationType()) &&
3901             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
3902           if (!IsAccess)
3903             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3904           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3905           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3906           return CompleteObject();
3907         }
3908 
3909         BaseVal = MTE->getOrCreateValue(false);
3910         assert(BaseVal && "got reference to unevaluated temporary");
3911       } else {
3912         if (!IsAccess)
3913           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3914         APValue Val;
3915         LVal.moveInto(Val);
3916         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3917             << AK
3918             << Val.getAsString(Info.Ctx,
3919                                Info.Ctx.getLValueReferenceType(LValType));
3920         NoteLValueLocation(Info, LVal.Base);
3921         return CompleteObject();
3922       }
3923     } else {
3924       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
3925       assert(BaseVal && "missing value for temporary");
3926     }
3927   }
3928 
3929   // In C++14, we can't safely access any mutable state when we might be
3930   // evaluating after an unmodeled side effect.
3931   //
3932   // FIXME: Not all local state is mutable. Allow local constant subobjects
3933   // to be read here (but take care with 'mutable' fields).
3934   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3935        Info.EvalStatus.HasSideEffects) ||
3936       (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
3937     return CompleteObject();
3938 
3939   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
3940 }
3941 
3942 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
3943 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3944 /// glvalue referred to by an entity of reference type.
3945 ///
3946 /// \param Info - Information about the ongoing evaluation.
3947 /// \param Conv - The expression for which we are performing the conversion.
3948 ///               Used for diagnostics.
3949 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3950 ///               case of a non-class type).
3951 /// \param LVal - The glvalue on which we are attempting to perform this action.
3952 /// \param RVal - The produced value will be placed here.
3953 /// \param WantObjectRepresentation - If true, we're looking for the object
3954 ///               representation rather than the value, and in particular,
3955 ///               there is no requirement that the result be fully initialized.
3956 static bool
3957 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
3958                                const LValue &LVal, APValue &RVal,
3959                                bool WantObjectRepresentation = false) {
3960   if (LVal.Designator.Invalid)
3961     return false;
3962 
3963   // Check for special cases where there is no existing APValue to look at.
3964   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3965 
3966   AccessKinds AK =
3967       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
3968 
3969   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
3970     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3971       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3972       // initializer until now for such expressions. Such an expression can't be
3973       // an ICE in C, so this only matters for fold.
3974       if (Type.isVolatileQualified()) {
3975         Info.FFDiag(Conv);
3976         return false;
3977       }
3978       APValue Lit;
3979       if (!Evaluate(Lit, Info, CLE->getInitializer()))
3980         return false;
3981       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
3982       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
3983     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3984       // Special-case character extraction so we don't have to construct an
3985       // APValue for the whole string.
3986       assert(LVal.Designator.Entries.size() <= 1 &&
3987              "Can only read characters from string literals");
3988       if (LVal.Designator.Entries.empty()) {
3989         // Fail for now for LValue to RValue conversion of an array.
3990         // (This shouldn't show up in C/C++, but it could be triggered by a
3991         // weird EvaluateAsRValue call from a tool.)
3992         Info.FFDiag(Conv);
3993         return false;
3994       }
3995       if (LVal.Designator.isOnePastTheEnd()) {
3996         if (Info.getLangOpts().CPlusPlus11)
3997           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
3998         else
3999           Info.FFDiag(Conv);
4000         return false;
4001       }
4002       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4003       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4004       return true;
4005     }
4006   }
4007 
4008   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4009   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4010 }
4011 
4012 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4013 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4014                              QualType LValType, APValue &Val) {
4015   if (LVal.Designator.Invalid)
4016     return false;
4017 
4018   if (!Info.getLangOpts().CPlusPlus14) {
4019     Info.FFDiag(E);
4020     return false;
4021   }
4022 
4023   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4024   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4025 }
4026 
4027 namespace {
4028 struct CompoundAssignSubobjectHandler {
4029   EvalInfo &Info;
4030   const Expr *E;
4031   QualType PromotedLHSType;
4032   BinaryOperatorKind Opcode;
4033   const APValue &RHS;
4034 
4035   static const AccessKinds AccessKind = AK_Assign;
4036 
4037   typedef bool result_type;
4038 
4039   bool checkConst(QualType QT) {
4040     // Assigning to a const object has undefined behavior.
4041     if (QT.isConstQualified()) {
4042       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4043       return false;
4044     }
4045     return true;
4046   }
4047 
4048   bool failed() { return false; }
4049   bool found(APValue &Subobj, QualType SubobjType) {
4050     switch (Subobj.getKind()) {
4051     case APValue::Int:
4052       return found(Subobj.getInt(), SubobjType);
4053     case APValue::Float:
4054       return found(Subobj.getFloat(), SubobjType);
4055     case APValue::ComplexInt:
4056     case APValue::ComplexFloat:
4057       // FIXME: Implement complex compound assignment.
4058       Info.FFDiag(E);
4059       return false;
4060     case APValue::LValue:
4061       return foundPointer(Subobj, SubobjType);
4062     case APValue::Vector:
4063       return foundVector(Subobj, SubobjType);
4064     default:
4065       // FIXME: can this happen?
4066       Info.FFDiag(E);
4067       return false;
4068     }
4069   }
4070 
4071   bool foundVector(APValue &Value, QualType SubobjType) {
4072     if (!checkConst(SubobjType))
4073       return false;
4074 
4075     if (!SubobjType->isVectorType()) {
4076       Info.FFDiag(E);
4077       return false;
4078     }
4079     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4080   }
4081 
4082   bool found(APSInt &Value, QualType SubobjType) {
4083     if (!checkConst(SubobjType))
4084       return false;
4085 
4086     if (!SubobjType->isIntegerType()) {
4087       // We don't support compound assignment on integer-cast-to-pointer
4088       // values.
4089       Info.FFDiag(E);
4090       return false;
4091     }
4092 
4093     if (RHS.isInt()) {
4094       APSInt LHS =
4095           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4096       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4097         return false;
4098       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4099       return true;
4100     } else if (RHS.isFloat()) {
4101       APFloat FValue(0.0);
4102       return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
4103                                   FValue) &&
4104              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4105              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4106                                   Value);
4107     }
4108 
4109     Info.FFDiag(E);
4110     return false;
4111   }
4112   bool found(APFloat &Value, QualType SubobjType) {
4113     return checkConst(SubobjType) &&
4114            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4115                                   Value) &&
4116            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4117            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4118   }
4119   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4120     if (!checkConst(SubobjType))
4121       return false;
4122 
4123     QualType PointeeType;
4124     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4125       PointeeType = PT->getPointeeType();
4126 
4127     if (PointeeType.isNull() || !RHS.isInt() ||
4128         (Opcode != BO_Add && Opcode != BO_Sub)) {
4129       Info.FFDiag(E);
4130       return false;
4131     }
4132 
4133     APSInt Offset = RHS.getInt();
4134     if (Opcode == BO_Sub)
4135       negateAsSigned(Offset);
4136 
4137     LValue LVal;
4138     LVal.setFrom(Info.Ctx, Subobj);
4139     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4140       return false;
4141     LVal.moveInto(Subobj);
4142     return true;
4143   }
4144 };
4145 } // end anonymous namespace
4146 
4147 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4148 
4149 /// Perform a compound assignment of LVal <op>= RVal.
4150 static bool handleCompoundAssignment(
4151     EvalInfo &Info, const Expr *E,
4152     const LValue &LVal, QualType LValType, QualType PromotedLValType,
4153     BinaryOperatorKind Opcode, const APValue &RVal) {
4154   if (LVal.Designator.Invalid)
4155     return false;
4156 
4157   if (!Info.getLangOpts().CPlusPlus14) {
4158     Info.FFDiag(E);
4159     return false;
4160   }
4161 
4162   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4163   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4164                                              RVal };
4165   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4166 }
4167 
4168 namespace {
4169 struct IncDecSubobjectHandler {
4170   EvalInfo &Info;
4171   const UnaryOperator *E;
4172   AccessKinds AccessKind;
4173   APValue *Old;
4174 
4175   typedef bool result_type;
4176 
4177   bool checkConst(QualType QT) {
4178     // Assigning to a const object has undefined behavior.
4179     if (QT.isConstQualified()) {
4180       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4181       return false;
4182     }
4183     return true;
4184   }
4185 
4186   bool failed() { return false; }
4187   bool found(APValue &Subobj, QualType SubobjType) {
4188     // Stash the old value. Also clear Old, so we don't clobber it later
4189     // if we're post-incrementing a complex.
4190     if (Old) {
4191       *Old = Subobj;
4192       Old = nullptr;
4193     }
4194 
4195     switch (Subobj.getKind()) {
4196     case APValue::Int:
4197       return found(Subobj.getInt(), SubobjType);
4198     case APValue::Float:
4199       return found(Subobj.getFloat(), SubobjType);
4200     case APValue::ComplexInt:
4201       return found(Subobj.getComplexIntReal(),
4202                    SubobjType->castAs<ComplexType>()->getElementType()
4203                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4204     case APValue::ComplexFloat:
4205       return found(Subobj.getComplexFloatReal(),
4206                    SubobjType->castAs<ComplexType>()->getElementType()
4207                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4208     case APValue::LValue:
4209       return foundPointer(Subobj, SubobjType);
4210     default:
4211       // FIXME: can this happen?
4212       Info.FFDiag(E);
4213       return false;
4214     }
4215   }
4216   bool found(APSInt &Value, QualType SubobjType) {
4217     if (!checkConst(SubobjType))
4218       return false;
4219 
4220     if (!SubobjType->isIntegerType()) {
4221       // We don't support increment / decrement on integer-cast-to-pointer
4222       // values.
4223       Info.FFDiag(E);
4224       return false;
4225     }
4226 
4227     if (Old) *Old = APValue(Value);
4228 
4229     // bool arithmetic promotes to int, and the conversion back to bool
4230     // doesn't reduce mod 2^n, so special-case it.
4231     if (SubobjType->isBooleanType()) {
4232       if (AccessKind == AK_Increment)
4233         Value = 1;
4234       else
4235         Value = !Value;
4236       return true;
4237     }
4238 
4239     bool WasNegative = Value.isNegative();
4240     if (AccessKind == AK_Increment) {
4241       ++Value;
4242 
4243       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4244         APSInt ActualValue(Value, /*IsUnsigned*/true);
4245         return HandleOverflow(Info, E, ActualValue, SubobjType);
4246       }
4247     } else {
4248       --Value;
4249 
4250       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4251         unsigned BitWidth = Value.getBitWidth();
4252         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4253         ActualValue.setBit(BitWidth);
4254         return HandleOverflow(Info, E, ActualValue, SubobjType);
4255       }
4256     }
4257     return true;
4258   }
4259   bool found(APFloat &Value, QualType SubobjType) {
4260     if (!checkConst(SubobjType))
4261       return false;
4262 
4263     if (Old) *Old = APValue(Value);
4264 
4265     APFloat One(Value.getSemantics(), 1);
4266     if (AccessKind == AK_Increment)
4267       Value.add(One, APFloat::rmNearestTiesToEven);
4268     else
4269       Value.subtract(One, APFloat::rmNearestTiesToEven);
4270     return true;
4271   }
4272   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4273     if (!checkConst(SubobjType))
4274       return false;
4275 
4276     QualType PointeeType;
4277     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4278       PointeeType = PT->getPointeeType();
4279     else {
4280       Info.FFDiag(E);
4281       return false;
4282     }
4283 
4284     LValue LVal;
4285     LVal.setFrom(Info.Ctx, Subobj);
4286     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4287                                      AccessKind == AK_Increment ? 1 : -1))
4288       return false;
4289     LVal.moveInto(Subobj);
4290     return true;
4291   }
4292 };
4293 } // end anonymous namespace
4294 
4295 /// Perform an increment or decrement on LVal.
4296 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4297                          QualType LValType, bool IsIncrement, APValue *Old) {
4298   if (LVal.Designator.Invalid)
4299     return false;
4300 
4301   if (!Info.getLangOpts().CPlusPlus14) {
4302     Info.FFDiag(E);
4303     return false;
4304   }
4305 
4306   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4307   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4308   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4309   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4310 }
4311 
4312 /// Build an lvalue for the object argument of a member function call.
4313 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4314                                    LValue &This) {
4315   if (Object->getType()->isPointerType() && Object->isRValue())
4316     return EvaluatePointer(Object, This, Info);
4317 
4318   if (Object->isGLValue())
4319     return EvaluateLValue(Object, This, Info);
4320 
4321   if (Object->getType()->isLiteralType(Info.Ctx))
4322     return EvaluateTemporary(Object, This, Info);
4323 
4324   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4325   return false;
4326 }
4327 
4328 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4329 /// lvalue referring to the result.
4330 ///
4331 /// \param Info - Information about the ongoing evaluation.
4332 /// \param LV - An lvalue referring to the base of the member pointer.
4333 /// \param RHS - The member pointer expression.
4334 /// \param IncludeMember - Specifies whether the member itself is included in
4335 ///        the resulting LValue subobject designator. This is not possible when
4336 ///        creating a bound member function.
4337 /// \return The field or method declaration to which the member pointer refers,
4338 ///         or 0 if evaluation fails.
4339 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4340                                                   QualType LVType,
4341                                                   LValue &LV,
4342                                                   const Expr *RHS,
4343                                                   bool IncludeMember = true) {
4344   MemberPtr MemPtr;
4345   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4346     return nullptr;
4347 
4348   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4349   // member value, the behavior is undefined.
4350   if (!MemPtr.getDecl()) {
4351     // FIXME: Specific diagnostic.
4352     Info.FFDiag(RHS);
4353     return nullptr;
4354   }
4355 
4356   if (MemPtr.isDerivedMember()) {
4357     // This is a member of some derived class. Truncate LV appropriately.
4358     // The end of the derived-to-base path for the base object must match the
4359     // derived-to-base path for the member pointer.
4360     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4361         LV.Designator.Entries.size()) {
4362       Info.FFDiag(RHS);
4363       return nullptr;
4364     }
4365     unsigned PathLengthToMember =
4366         LV.Designator.Entries.size() - MemPtr.Path.size();
4367     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4368       const CXXRecordDecl *LVDecl = getAsBaseClass(
4369           LV.Designator.Entries[PathLengthToMember + I]);
4370       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4371       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4372         Info.FFDiag(RHS);
4373         return nullptr;
4374       }
4375     }
4376 
4377     // Truncate the lvalue to the appropriate derived class.
4378     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4379                             PathLengthToMember))
4380       return nullptr;
4381   } else if (!MemPtr.Path.empty()) {
4382     // Extend the LValue path with the member pointer's path.
4383     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4384                                   MemPtr.Path.size() + IncludeMember);
4385 
4386     // Walk down to the appropriate base class.
4387     if (const PointerType *PT = LVType->getAs<PointerType>())
4388       LVType = PT->getPointeeType();
4389     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4390     assert(RD && "member pointer access on non-class-type expression");
4391     // The first class in the path is that of the lvalue.
4392     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4393       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4394       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4395         return nullptr;
4396       RD = Base;
4397     }
4398     // Finally cast to the class containing the member.
4399     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4400                                 MemPtr.getContainingRecord()))
4401       return nullptr;
4402   }
4403 
4404   // Add the member. Note that we cannot build bound member functions here.
4405   if (IncludeMember) {
4406     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4407       if (!HandleLValueMember(Info, RHS, LV, FD))
4408         return nullptr;
4409     } else if (const IndirectFieldDecl *IFD =
4410                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4411       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4412         return nullptr;
4413     } else {
4414       llvm_unreachable("can't construct reference to bound member function");
4415     }
4416   }
4417 
4418   return MemPtr.getDecl();
4419 }
4420 
4421 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4422                                                   const BinaryOperator *BO,
4423                                                   LValue &LV,
4424                                                   bool IncludeMember = true) {
4425   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4426 
4427   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4428     if (Info.noteFailure()) {
4429       MemberPtr MemPtr;
4430       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4431     }
4432     return nullptr;
4433   }
4434 
4435   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4436                                    BO->getRHS(), IncludeMember);
4437 }
4438 
4439 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4440 /// the provided lvalue, which currently refers to the base object.
4441 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4442                                     LValue &Result) {
4443   SubobjectDesignator &D = Result.Designator;
4444   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4445     return false;
4446 
4447   QualType TargetQT = E->getType();
4448   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4449     TargetQT = PT->getPointeeType();
4450 
4451   // Check this cast lands within the final derived-to-base subobject path.
4452   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4453     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4454       << D.MostDerivedType << TargetQT;
4455     return false;
4456   }
4457 
4458   // Check the type of the final cast. We don't need to check the path,
4459   // since a cast can only be formed if the path is unique.
4460   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4461   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4462   const CXXRecordDecl *FinalType;
4463   if (NewEntriesSize == D.MostDerivedPathLength)
4464     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4465   else
4466     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4467   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4468     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4469       << D.MostDerivedType << TargetQT;
4470     return false;
4471   }
4472 
4473   // Truncate the lvalue to the appropriate derived class.
4474   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4475 }
4476 
4477 /// Get the value to use for a default-initialized object of type T.
4478 /// Return false if it encounters something invalid.
4479 static bool getDefaultInitValue(QualType T, APValue &Result) {
4480   bool Success = true;
4481   if (auto *RD = T->getAsCXXRecordDecl()) {
4482     if (RD->isInvalidDecl()) {
4483       Result = APValue();
4484       return false;
4485     }
4486     if (RD->isUnion()) {
4487       Result = APValue((const FieldDecl *)nullptr);
4488       return true;
4489     }
4490     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4491                      std::distance(RD->field_begin(), RD->field_end()));
4492 
4493     unsigned Index = 0;
4494     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4495                                                   End = RD->bases_end();
4496          I != End; ++I, ++Index)
4497       Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4498 
4499     for (const auto *I : RD->fields()) {
4500       if (I->isUnnamedBitfield())
4501         continue;
4502       Success &= getDefaultInitValue(I->getType(),
4503                                      Result.getStructField(I->getFieldIndex()));
4504     }
4505     return Success;
4506   }
4507 
4508   if (auto *AT =
4509           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4510     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4511     if (Result.hasArrayFiller())
4512       Success &=
4513           getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4514 
4515     return Success;
4516   }
4517 
4518   Result = APValue::IndeterminateValue();
4519   return true;
4520 }
4521 
4522 namespace {
4523 enum EvalStmtResult {
4524   /// Evaluation failed.
4525   ESR_Failed,
4526   /// Hit a 'return' statement.
4527   ESR_Returned,
4528   /// Evaluation succeeded.
4529   ESR_Succeeded,
4530   /// Hit a 'continue' statement.
4531   ESR_Continue,
4532   /// Hit a 'break' statement.
4533   ESR_Break,
4534   /// Still scanning for 'case' or 'default' statement.
4535   ESR_CaseNotFound
4536 };
4537 }
4538 
4539 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4540   // We don't need to evaluate the initializer for a static local.
4541   if (!VD->hasLocalStorage())
4542     return true;
4543 
4544   LValue Result;
4545   APValue &Val =
4546       Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result);
4547 
4548   const Expr *InitE = VD->getInit();
4549   if (!InitE)
4550     return getDefaultInitValue(VD->getType(), Val);
4551 
4552   if (InitE->isValueDependent())
4553     return false;
4554 
4555   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4556     // Wipe out any partially-computed value, to allow tracking that this
4557     // evaluation failed.
4558     Val = APValue();
4559     return false;
4560   }
4561 
4562   return true;
4563 }
4564 
4565 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4566   bool OK = true;
4567 
4568   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4569     OK &= EvaluateVarDecl(Info, VD);
4570 
4571   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4572     for (auto *BD : DD->bindings())
4573       if (auto *VD = BD->getHoldingVar())
4574         OK &= EvaluateDecl(Info, VD);
4575 
4576   return OK;
4577 }
4578 
4579 
4580 /// Evaluate a condition (either a variable declaration or an expression).
4581 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4582                          const Expr *Cond, bool &Result) {
4583   FullExpressionRAII Scope(Info);
4584   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4585     return false;
4586   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4587     return false;
4588   return Scope.destroy();
4589 }
4590 
4591 namespace {
4592 /// A location where the result (returned value) of evaluating a
4593 /// statement should be stored.
4594 struct StmtResult {
4595   /// The APValue that should be filled in with the returned value.
4596   APValue &Value;
4597   /// The location containing the result, if any (used to support RVO).
4598   const LValue *Slot;
4599 };
4600 
4601 struct TempVersionRAII {
4602   CallStackFrame &Frame;
4603 
4604   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4605     Frame.pushTempVersion();
4606   }
4607 
4608   ~TempVersionRAII() {
4609     Frame.popTempVersion();
4610   }
4611 };
4612 
4613 }
4614 
4615 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4616                                    const Stmt *S,
4617                                    const SwitchCase *SC = nullptr);
4618 
4619 /// Evaluate the body of a loop, and translate the result as appropriate.
4620 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4621                                        const Stmt *Body,
4622                                        const SwitchCase *Case = nullptr) {
4623   BlockScopeRAII Scope(Info);
4624 
4625   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4626   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4627     ESR = ESR_Failed;
4628 
4629   switch (ESR) {
4630   case ESR_Break:
4631     return ESR_Succeeded;
4632   case ESR_Succeeded:
4633   case ESR_Continue:
4634     return ESR_Continue;
4635   case ESR_Failed:
4636   case ESR_Returned:
4637   case ESR_CaseNotFound:
4638     return ESR;
4639   }
4640   llvm_unreachable("Invalid EvalStmtResult!");
4641 }
4642 
4643 /// Evaluate a switch statement.
4644 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4645                                      const SwitchStmt *SS) {
4646   BlockScopeRAII Scope(Info);
4647 
4648   // Evaluate the switch condition.
4649   APSInt Value;
4650   {
4651     if (const Stmt *Init = SS->getInit()) {
4652       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4653       if (ESR != ESR_Succeeded) {
4654         if (ESR != ESR_Failed && !Scope.destroy())
4655           ESR = ESR_Failed;
4656         return ESR;
4657       }
4658     }
4659 
4660     FullExpressionRAII CondScope(Info);
4661     if (SS->getConditionVariable() &&
4662         !EvaluateDecl(Info, SS->getConditionVariable()))
4663       return ESR_Failed;
4664     if (!EvaluateInteger(SS->getCond(), Value, Info))
4665       return ESR_Failed;
4666     if (!CondScope.destroy())
4667       return ESR_Failed;
4668   }
4669 
4670   // Find the switch case corresponding to the value of the condition.
4671   // FIXME: Cache this lookup.
4672   const SwitchCase *Found = nullptr;
4673   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4674        SC = SC->getNextSwitchCase()) {
4675     if (isa<DefaultStmt>(SC)) {
4676       Found = SC;
4677       continue;
4678     }
4679 
4680     const CaseStmt *CS = cast<CaseStmt>(SC);
4681     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4682     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4683                               : LHS;
4684     if (LHS <= Value && Value <= RHS) {
4685       Found = SC;
4686       break;
4687     }
4688   }
4689 
4690   if (!Found)
4691     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4692 
4693   // Search the switch body for the switch case and evaluate it from there.
4694   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4695   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4696     return ESR_Failed;
4697 
4698   switch (ESR) {
4699   case ESR_Break:
4700     return ESR_Succeeded;
4701   case ESR_Succeeded:
4702   case ESR_Continue:
4703   case ESR_Failed:
4704   case ESR_Returned:
4705     return ESR;
4706   case ESR_CaseNotFound:
4707     // This can only happen if the switch case is nested within a statement
4708     // expression. We have no intention of supporting that.
4709     Info.FFDiag(Found->getBeginLoc(),
4710                 diag::note_constexpr_stmt_expr_unsupported);
4711     return ESR_Failed;
4712   }
4713   llvm_unreachable("Invalid EvalStmtResult!");
4714 }
4715 
4716 // Evaluate a statement.
4717 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4718                                    const Stmt *S, const SwitchCase *Case) {
4719   if (!Info.nextStep(S))
4720     return ESR_Failed;
4721 
4722   // If we're hunting down a 'case' or 'default' label, recurse through
4723   // substatements until we hit the label.
4724   if (Case) {
4725     switch (S->getStmtClass()) {
4726     case Stmt::CompoundStmtClass:
4727       // FIXME: Precompute which substatement of a compound statement we
4728       // would jump to, and go straight there rather than performing a
4729       // linear scan each time.
4730     case Stmt::LabelStmtClass:
4731     case Stmt::AttributedStmtClass:
4732     case Stmt::DoStmtClass:
4733       break;
4734 
4735     case Stmt::CaseStmtClass:
4736     case Stmt::DefaultStmtClass:
4737       if (Case == S)
4738         Case = nullptr;
4739       break;
4740 
4741     case Stmt::IfStmtClass: {
4742       // FIXME: Precompute which side of an 'if' we would jump to, and go
4743       // straight there rather than scanning both sides.
4744       const IfStmt *IS = cast<IfStmt>(S);
4745 
4746       // Wrap the evaluation in a block scope, in case it's a DeclStmt
4747       // preceded by our switch label.
4748       BlockScopeRAII Scope(Info);
4749 
4750       // Step into the init statement in case it brings an (uninitialized)
4751       // variable into scope.
4752       if (const Stmt *Init = IS->getInit()) {
4753         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4754         if (ESR != ESR_CaseNotFound) {
4755           assert(ESR != ESR_Succeeded);
4756           return ESR;
4757         }
4758       }
4759 
4760       // Condition variable must be initialized if it exists.
4761       // FIXME: We can skip evaluating the body if there's a condition
4762       // variable, as there can't be any case labels within it.
4763       // (The same is true for 'for' statements.)
4764 
4765       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4766       if (ESR == ESR_Failed)
4767         return ESR;
4768       if (ESR != ESR_CaseNotFound)
4769         return Scope.destroy() ? ESR : ESR_Failed;
4770       if (!IS->getElse())
4771         return ESR_CaseNotFound;
4772 
4773       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
4774       if (ESR == ESR_Failed)
4775         return ESR;
4776       if (ESR != ESR_CaseNotFound)
4777         return Scope.destroy() ? ESR : ESR_Failed;
4778       return ESR_CaseNotFound;
4779     }
4780 
4781     case Stmt::WhileStmtClass: {
4782       EvalStmtResult ESR =
4783           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4784       if (ESR != ESR_Continue)
4785         return ESR;
4786       break;
4787     }
4788 
4789     case Stmt::ForStmtClass: {
4790       const ForStmt *FS = cast<ForStmt>(S);
4791       BlockScopeRAII Scope(Info);
4792 
4793       // Step into the init statement in case it brings an (uninitialized)
4794       // variable into scope.
4795       if (const Stmt *Init = FS->getInit()) {
4796         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4797         if (ESR != ESR_CaseNotFound) {
4798           assert(ESR != ESR_Succeeded);
4799           return ESR;
4800         }
4801       }
4802 
4803       EvalStmtResult ESR =
4804           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4805       if (ESR != ESR_Continue)
4806         return ESR;
4807       if (FS->getInc()) {
4808         FullExpressionRAII IncScope(Info);
4809         if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
4810           return ESR_Failed;
4811       }
4812       break;
4813     }
4814 
4815     case Stmt::DeclStmtClass: {
4816       // Start the lifetime of any uninitialized variables we encounter. They
4817       // might be used by the selected branch of the switch.
4818       const DeclStmt *DS = cast<DeclStmt>(S);
4819       for (const auto *D : DS->decls()) {
4820         if (const auto *VD = dyn_cast<VarDecl>(D)) {
4821           if (VD->hasLocalStorage() && !VD->getInit())
4822             if (!EvaluateVarDecl(Info, VD))
4823               return ESR_Failed;
4824           // FIXME: If the variable has initialization that can't be jumped
4825           // over, bail out of any immediately-surrounding compound-statement
4826           // too. There can't be any case labels here.
4827         }
4828       }
4829       return ESR_CaseNotFound;
4830     }
4831 
4832     default:
4833       return ESR_CaseNotFound;
4834     }
4835   }
4836 
4837   switch (S->getStmtClass()) {
4838   default:
4839     if (const Expr *E = dyn_cast<Expr>(S)) {
4840       // Don't bother evaluating beyond an expression-statement which couldn't
4841       // be evaluated.
4842       // FIXME: Do we need the FullExpressionRAII object here?
4843       // VisitExprWithCleanups should create one when necessary.
4844       FullExpressionRAII Scope(Info);
4845       if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
4846         return ESR_Failed;
4847       return ESR_Succeeded;
4848     }
4849 
4850     Info.FFDiag(S->getBeginLoc());
4851     return ESR_Failed;
4852 
4853   case Stmt::NullStmtClass:
4854     return ESR_Succeeded;
4855 
4856   case Stmt::DeclStmtClass: {
4857     const DeclStmt *DS = cast<DeclStmt>(S);
4858     for (const auto *D : DS->decls()) {
4859       // Each declaration initialization is its own full-expression.
4860       FullExpressionRAII Scope(Info);
4861       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
4862         return ESR_Failed;
4863       if (!Scope.destroy())
4864         return ESR_Failed;
4865     }
4866     return ESR_Succeeded;
4867   }
4868 
4869   case Stmt::ReturnStmtClass: {
4870     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
4871     FullExpressionRAII Scope(Info);
4872     if (RetExpr &&
4873         !(Result.Slot
4874               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4875               : Evaluate(Result.Value, Info, RetExpr)))
4876       return ESR_Failed;
4877     return Scope.destroy() ? ESR_Returned : ESR_Failed;
4878   }
4879 
4880   case Stmt::CompoundStmtClass: {
4881     BlockScopeRAII Scope(Info);
4882 
4883     const CompoundStmt *CS = cast<CompoundStmt>(S);
4884     for (const auto *BI : CS->body()) {
4885       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
4886       if (ESR == ESR_Succeeded)
4887         Case = nullptr;
4888       else if (ESR != ESR_CaseNotFound) {
4889         if (ESR != ESR_Failed && !Scope.destroy())
4890           return ESR_Failed;
4891         return ESR;
4892       }
4893     }
4894     if (Case)
4895       return ESR_CaseNotFound;
4896     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4897   }
4898 
4899   case Stmt::IfStmtClass: {
4900     const IfStmt *IS = cast<IfStmt>(S);
4901 
4902     // Evaluate the condition, as either a var decl or as an expression.
4903     BlockScopeRAII Scope(Info);
4904     if (const Stmt *Init = IS->getInit()) {
4905       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4906       if (ESR != ESR_Succeeded) {
4907         if (ESR != ESR_Failed && !Scope.destroy())
4908           return ESR_Failed;
4909         return ESR;
4910       }
4911     }
4912     bool Cond;
4913     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4914       return ESR_Failed;
4915 
4916     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4917       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4918       if (ESR != ESR_Succeeded) {
4919         if (ESR != ESR_Failed && !Scope.destroy())
4920           return ESR_Failed;
4921         return ESR;
4922       }
4923     }
4924     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4925   }
4926 
4927   case Stmt::WhileStmtClass: {
4928     const WhileStmt *WS = cast<WhileStmt>(S);
4929     while (true) {
4930       BlockScopeRAII Scope(Info);
4931       bool Continue;
4932       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4933                         Continue))
4934         return ESR_Failed;
4935       if (!Continue)
4936         break;
4937 
4938       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4939       if (ESR != ESR_Continue) {
4940         if (ESR != ESR_Failed && !Scope.destroy())
4941           return ESR_Failed;
4942         return ESR;
4943       }
4944       if (!Scope.destroy())
4945         return ESR_Failed;
4946     }
4947     return ESR_Succeeded;
4948   }
4949 
4950   case Stmt::DoStmtClass: {
4951     const DoStmt *DS = cast<DoStmt>(S);
4952     bool Continue;
4953     do {
4954       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4955       if (ESR != ESR_Continue)
4956         return ESR;
4957       Case = nullptr;
4958 
4959       FullExpressionRAII CondScope(Info);
4960       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
4961           !CondScope.destroy())
4962         return ESR_Failed;
4963     } while (Continue);
4964     return ESR_Succeeded;
4965   }
4966 
4967   case Stmt::ForStmtClass: {
4968     const ForStmt *FS = cast<ForStmt>(S);
4969     BlockScopeRAII ForScope(Info);
4970     if (FS->getInit()) {
4971       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4972       if (ESR != ESR_Succeeded) {
4973         if (ESR != ESR_Failed && !ForScope.destroy())
4974           return ESR_Failed;
4975         return ESR;
4976       }
4977     }
4978     while (true) {
4979       BlockScopeRAII IterScope(Info);
4980       bool Continue = true;
4981       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4982                                          FS->getCond(), Continue))
4983         return ESR_Failed;
4984       if (!Continue)
4985         break;
4986 
4987       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4988       if (ESR != ESR_Continue) {
4989         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
4990           return ESR_Failed;
4991         return ESR;
4992       }
4993 
4994       if (FS->getInc()) {
4995         FullExpressionRAII IncScope(Info);
4996         if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
4997           return ESR_Failed;
4998       }
4999 
5000       if (!IterScope.destroy())
5001         return ESR_Failed;
5002     }
5003     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5004   }
5005 
5006   case Stmt::CXXForRangeStmtClass: {
5007     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5008     BlockScopeRAII Scope(Info);
5009 
5010     // Evaluate the init-statement if present.
5011     if (FS->getInit()) {
5012       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5013       if (ESR != ESR_Succeeded) {
5014         if (ESR != ESR_Failed && !Scope.destroy())
5015           return ESR_Failed;
5016         return ESR;
5017       }
5018     }
5019 
5020     // Initialize the __range variable.
5021     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5022     if (ESR != ESR_Succeeded) {
5023       if (ESR != ESR_Failed && !Scope.destroy())
5024         return ESR_Failed;
5025       return ESR;
5026     }
5027 
5028     // Create the __begin and __end iterators.
5029     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5030     if (ESR != ESR_Succeeded) {
5031       if (ESR != ESR_Failed && !Scope.destroy())
5032         return ESR_Failed;
5033       return ESR;
5034     }
5035     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5036     if (ESR != ESR_Succeeded) {
5037       if (ESR != ESR_Failed && !Scope.destroy())
5038         return ESR_Failed;
5039       return ESR;
5040     }
5041 
5042     while (true) {
5043       // Condition: __begin != __end.
5044       {
5045         bool Continue = true;
5046         FullExpressionRAII CondExpr(Info);
5047         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5048           return ESR_Failed;
5049         if (!Continue)
5050           break;
5051       }
5052 
5053       // User's variable declaration, initialized by *__begin.
5054       BlockScopeRAII InnerScope(Info);
5055       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5056       if (ESR != ESR_Succeeded) {
5057         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5058           return ESR_Failed;
5059         return ESR;
5060       }
5061 
5062       // Loop body.
5063       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5064       if (ESR != ESR_Continue) {
5065         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5066           return ESR_Failed;
5067         return ESR;
5068       }
5069 
5070       // Increment: ++__begin
5071       if (!EvaluateIgnoredValue(Info, FS->getInc()))
5072         return ESR_Failed;
5073 
5074       if (!InnerScope.destroy())
5075         return ESR_Failed;
5076     }
5077 
5078     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5079   }
5080 
5081   case Stmt::SwitchStmtClass:
5082     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5083 
5084   case Stmt::ContinueStmtClass:
5085     return ESR_Continue;
5086 
5087   case Stmt::BreakStmtClass:
5088     return ESR_Break;
5089 
5090   case Stmt::LabelStmtClass:
5091     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5092 
5093   case Stmt::AttributedStmtClass:
5094     // As a general principle, C++11 attributes can be ignored without
5095     // any semantic impact.
5096     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5097                         Case);
5098 
5099   case Stmt::CaseStmtClass:
5100   case Stmt::DefaultStmtClass:
5101     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5102   case Stmt::CXXTryStmtClass:
5103     // Evaluate try blocks by evaluating all sub statements.
5104     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5105   }
5106 }
5107 
5108 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5109 /// default constructor. If so, we'll fold it whether or not it's marked as
5110 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5111 /// so we need special handling.
5112 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5113                                            const CXXConstructorDecl *CD,
5114                                            bool IsValueInitialization) {
5115   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5116     return false;
5117 
5118   // Value-initialization does not call a trivial default constructor, so such a
5119   // call is a core constant expression whether or not the constructor is
5120   // constexpr.
5121   if (!CD->isConstexpr() && !IsValueInitialization) {
5122     if (Info.getLangOpts().CPlusPlus11) {
5123       // FIXME: If DiagDecl is an implicitly-declared special member function,
5124       // we should be much more explicit about why it's not constexpr.
5125       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5126         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5127       Info.Note(CD->getLocation(), diag::note_declared_at);
5128     } else {
5129       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5130     }
5131   }
5132   return true;
5133 }
5134 
5135 /// CheckConstexprFunction - Check that a function can be called in a constant
5136 /// expression.
5137 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5138                                    const FunctionDecl *Declaration,
5139                                    const FunctionDecl *Definition,
5140                                    const Stmt *Body) {
5141   // Potential constant expressions can contain calls to declared, but not yet
5142   // defined, constexpr functions.
5143   if (Info.checkingPotentialConstantExpression() && !Definition &&
5144       Declaration->isConstexpr())
5145     return false;
5146 
5147   // Bail out if the function declaration itself is invalid.  We will
5148   // have produced a relevant diagnostic while parsing it, so just
5149   // note the problematic sub-expression.
5150   if (Declaration->isInvalidDecl()) {
5151     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5152     return false;
5153   }
5154 
5155   // DR1872: An instantiated virtual constexpr function can't be called in a
5156   // constant expression (prior to C++20). We can still constant-fold such a
5157   // call.
5158   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5159       cast<CXXMethodDecl>(Declaration)->isVirtual())
5160     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5161 
5162   if (Definition && Definition->isInvalidDecl()) {
5163     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5164     return false;
5165   }
5166 
5167   if (const auto *CtorDecl = dyn_cast_or_null<CXXConstructorDecl>(Definition)) {
5168     for (const auto *InitExpr : CtorDecl->inits()) {
5169       if (InitExpr->getInit() && InitExpr->getInit()->containsErrors())
5170         return false;
5171     }
5172   }
5173 
5174   // Can we evaluate this function call?
5175   if (Definition && Definition->isConstexpr() && Body)
5176     return true;
5177 
5178   if (Info.getLangOpts().CPlusPlus11) {
5179     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5180 
5181     // If this function is not constexpr because it is an inherited
5182     // non-constexpr constructor, diagnose that directly.
5183     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5184     if (CD && CD->isInheritingConstructor()) {
5185       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5186       if (!Inherited->isConstexpr())
5187         DiagDecl = CD = Inherited;
5188     }
5189 
5190     // FIXME: If DiagDecl is an implicitly-declared special member function
5191     // or an inheriting constructor, we should be much more explicit about why
5192     // it's not constexpr.
5193     if (CD && CD->isInheritingConstructor())
5194       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5195         << CD->getInheritedConstructor().getConstructor()->getParent();
5196     else
5197       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5198         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5199     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5200   } else {
5201     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5202   }
5203   return false;
5204 }
5205 
5206 namespace {
5207 struct CheckDynamicTypeHandler {
5208   AccessKinds AccessKind;
5209   typedef bool result_type;
5210   bool failed() { return false; }
5211   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5212   bool found(APSInt &Value, QualType SubobjType) { return true; }
5213   bool found(APFloat &Value, QualType SubobjType) { return true; }
5214 };
5215 } // end anonymous namespace
5216 
5217 /// Check that we can access the notional vptr of an object / determine its
5218 /// dynamic type.
5219 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5220                              AccessKinds AK, bool Polymorphic) {
5221   if (This.Designator.Invalid)
5222     return false;
5223 
5224   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5225 
5226   if (!Obj)
5227     return false;
5228 
5229   if (!Obj.Value) {
5230     // The object is not usable in constant expressions, so we can't inspect
5231     // its value to see if it's in-lifetime or what the active union members
5232     // are. We can still check for a one-past-the-end lvalue.
5233     if (This.Designator.isOnePastTheEnd() ||
5234         This.Designator.isMostDerivedAnUnsizedArray()) {
5235       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5236                          ? diag::note_constexpr_access_past_end
5237                          : diag::note_constexpr_access_unsized_array)
5238           << AK;
5239       return false;
5240     } else if (Polymorphic) {
5241       // Conservatively refuse to perform a polymorphic operation if we would
5242       // not be able to read a notional 'vptr' value.
5243       APValue Val;
5244       This.moveInto(Val);
5245       QualType StarThisType =
5246           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5247       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5248           << AK << Val.getAsString(Info.Ctx, StarThisType);
5249       return false;
5250     }
5251     return true;
5252   }
5253 
5254   CheckDynamicTypeHandler Handler{AK};
5255   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5256 }
5257 
5258 /// Check that the pointee of the 'this' pointer in a member function call is
5259 /// either within its lifetime or in its period of construction or destruction.
5260 static bool
5261 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5262                                      const LValue &This,
5263                                      const CXXMethodDecl *NamedMember) {
5264   return checkDynamicType(
5265       Info, E, This,
5266       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5267 }
5268 
5269 struct DynamicType {
5270   /// The dynamic class type of the object.
5271   const CXXRecordDecl *Type;
5272   /// The corresponding path length in the lvalue.
5273   unsigned PathLength;
5274 };
5275 
5276 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5277                                              unsigned PathLength) {
5278   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5279       Designator.Entries.size() && "invalid path length");
5280   return (PathLength == Designator.MostDerivedPathLength)
5281              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5282              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5283 }
5284 
5285 /// Determine the dynamic type of an object.
5286 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5287                                                 LValue &This, AccessKinds AK) {
5288   // If we don't have an lvalue denoting an object of class type, there is no
5289   // meaningful dynamic type. (We consider objects of non-class type to have no
5290   // dynamic type.)
5291   if (!checkDynamicType(Info, E, This, AK, true))
5292     return None;
5293 
5294   // Refuse to compute a dynamic type in the presence of virtual bases. This
5295   // shouldn't happen other than in constant-folding situations, since literal
5296   // types can't have virtual bases.
5297   //
5298   // Note that consumers of DynamicType assume that the type has no virtual
5299   // bases, and will need modifications if this restriction is relaxed.
5300   const CXXRecordDecl *Class =
5301       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5302   if (!Class || Class->getNumVBases()) {
5303     Info.FFDiag(E);
5304     return None;
5305   }
5306 
5307   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5308   // binary search here instead. But the overwhelmingly common case is that
5309   // we're not in the middle of a constructor, so it probably doesn't matter
5310   // in practice.
5311   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5312   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5313        PathLength <= Path.size(); ++PathLength) {
5314     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5315                                       Path.slice(0, PathLength))) {
5316     case ConstructionPhase::Bases:
5317     case ConstructionPhase::DestroyingBases:
5318       // We're constructing or destroying a base class. This is not the dynamic
5319       // type.
5320       break;
5321 
5322     case ConstructionPhase::None:
5323     case ConstructionPhase::AfterBases:
5324     case ConstructionPhase::AfterFields:
5325     case ConstructionPhase::Destroying:
5326       // We've finished constructing the base classes and not yet started
5327       // destroying them again, so this is the dynamic type.
5328       return DynamicType{getBaseClassType(This.Designator, PathLength),
5329                          PathLength};
5330     }
5331   }
5332 
5333   // CWG issue 1517: we're constructing a base class of the object described by
5334   // 'This', so that object has not yet begun its period of construction and
5335   // any polymorphic operation on it results in undefined behavior.
5336   Info.FFDiag(E);
5337   return None;
5338 }
5339 
5340 /// Perform virtual dispatch.
5341 static const CXXMethodDecl *HandleVirtualDispatch(
5342     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5343     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5344   Optional<DynamicType> DynType = ComputeDynamicType(
5345       Info, E, This,
5346       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5347   if (!DynType)
5348     return nullptr;
5349 
5350   // Find the final overrider. It must be declared in one of the classes on the
5351   // path from the dynamic type to the static type.
5352   // FIXME: If we ever allow literal types to have virtual base classes, that
5353   // won't be true.
5354   const CXXMethodDecl *Callee = Found;
5355   unsigned PathLength = DynType->PathLength;
5356   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5357     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5358     const CXXMethodDecl *Overrider =
5359         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5360     if (Overrider) {
5361       Callee = Overrider;
5362       break;
5363     }
5364   }
5365 
5366   // C++2a [class.abstract]p6:
5367   //   the effect of making a virtual call to a pure virtual function [...] is
5368   //   undefined
5369   if (Callee->isPure()) {
5370     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5371     Info.Note(Callee->getLocation(), diag::note_declared_at);
5372     return nullptr;
5373   }
5374 
5375   // If necessary, walk the rest of the path to determine the sequence of
5376   // covariant adjustment steps to apply.
5377   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5378                                        Found->getReturnType())) {
5379     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5380     for (unsigned CovariantPathLength = PathLength + 1;
5381          CovariantPathLength != This.Designator.Entries.size();
5382          ++CovariantPathLength) {
5383       const CXXRecordDecl *NextClass =
5384           getBaseClassType(This.Designator, CovariantPathLength);
5385       const CXXMethodDecl *Next =
5386           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5387       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5388                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5389         CovariantAdjustmentPath.push_back(Next->getReturnType());
5390     }
5391     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5392                                          CovariantAdjustmentPath.back()))
5393       CovariantAdjustmentPath.push_back(Found->getReturnType());
5394   }
5395 
5396   // Perform 'this' adjustment.
5397   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5398     return nullptr;
5399 
5400   return Callee;
5401 }
5402 
5403 /// Perform the adjustment from a value returned by a virtual function to
5404 /// a value of the statically expected type, which may be a pointer or
5405 /// reference to a base class of the returned type.
5406 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5407                                             APValue &Result,
5408                                             ArrayRef<QualType> Path) {
5409   assert(Result.isLValue() &&
5410          "unexpected kind of APValue for covariant return");
5411   if (Result.isNullPointer())
5412     return true;
5413 
5414   LValue LVal;
5415   LVal.setFrom(Info.Ctx, Result);
5416 
5417   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5418   for (unsigned I = 1; I != Path.size(); ++I) {
5419     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5420     assert(OldClass && NewClass && "unexpected kind of covariant return");
5421     if (OldClass != NewClass &&
5422         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5423       return false;
5424     OldClass = NewClass;
5425   }
5426 
5427   LVal.moveInto(Result);
5428   return true;
5429 }
5430 
5431 /// Determine whether \p Base, which is known to be a direct base class of
5432 /// \p Derived, is a public base class.
5433 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5434                               const CXXRecordDecl *Base) {
5435   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5436     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5437     if (BaseClass && declaresSameEntity(BaseClass, Base))
5438       return BaseSpec.getAccessSpecifier() == AS_public;
5439   }
5440   llvm_unreachable("Base is not a direct base of Derived");
5441 }
5442 
5443 /// Apply the given dynamic cast operation on the provided lvalue.
5444 ///
5445 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5446 /// to find a suitable target subobject.
5447 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5448                               LValue &Ptr) {
5449   // We can't do anything with a non-symbolic pointer value.
5450   SubobjectDesignator &D = Ptr.Designator;
5451   if (D.Invalid)
5452     return false;
5453 
5454   // C++ [expr.dynamic.cast]p6:
5455   //   If v is a null pointer value, the result is a null pointer value.
5456   if (Ptr.isNullPointer() && !E->isGLValue())
5457     return true;
5458 
5459   // For all the other cases, we need the pointer to point to an object within
5460   // its lifetime / period of construction / destruction, and we need to know
5461   // its dynamic type.
5462   Optional<DynamicType> DynType =
5463       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5464   if (!DynType)
5465     return false;
5466 
5467   // C++ [expr.dynamic.cast]p7:
5468   //   If T is "pointer to cv void", then the result is a pointer to the most
5469   //   derived object
5470   if (E->getType()->isVoidPointerType())
5471     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5472 
5473   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5474   assert(C && "dynamic_cast target is not void pointer nor class");
5475   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5476 
5477   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5478     // C++ [expr.dynamic.cast]p9:
5479     if (!E->isGLValue()) {
5480       //   The value of a failed cast to pointer type is the null pointer value
5481       //   of the required result type.
5482       Ptr.setNull(Info.Ctx, E->getType());
5483       return true;
5484     }
5485 
5486     //   A failed cast to reference type throws [...] std::bad_cast.
5487     unsigned DiagKind;
5488     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5489                    DynType->Type->isDerivedFrom(C)))
5490       DiagKind = 0;
5491     else if (!Paths || Paths->begin() == Paths->end())
5492       DiagKind = 1;
5493     else if (Paths->isAmbiguous(CQT))
5494       DiagKind = 2;
5495     else {
5496       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5497       DiagKind = 3;
5498     }
5499     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5500         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5501         << Info.Ctx.getRecordType(DynType->Type)
5502         << E->getType().getUnqualifiedType();
5503     return false;
5504   };
5505 
5506   // Runtime check, phase 1:
5507   //   Walk from the base subobject towards the derived object looking for the
5508   //   target type.
5509   for (int PathLength = Ptr.Designator.Entries.size();
5510        PathLength >= (int)DynType->PathLength; --PathLength) {
5511     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5512     if (declaresSameEntity(Class, C))
5513       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5514     // We can only walk across public inheritance edges.
5515     if (PathLength > (int)DynType->PathLength &&
5516         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5517                            Class))
5518       return RuntimeCheckFailed(nullptr);
5519   }
5520 
5521   // Runtime check, phase 2:
5522   //   Search the dynamic type for an unambiguous public base of type C.
5523   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5524                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5525   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5526       Paths.front().Access == AS_public) {
5527     // Downcast to the dynamic type...
5528     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5529       return false;
5530     // ... then upcast to the chosen base class subobject.
5531     for (CXXBasePathElement &Elem : Paths.front())
5532       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5533         return false;
5534     return true;
5535   }
5536 
5537   // Otherwise, the runtime check fails.
5538   return RuntimeCheckFailed(&Paths);
5539 }
5540 
5541 namespace {
5542 struct StartLifetimeOfUnionMemberHandler {
5543   EvalInfo &Info;
5544   const Expr *LHSExpr;
5545   const FieldDecl *Field;
5546   bool DuringInit;
5547   bool Failed = false;
5548   static const AccessKinds AccessKind = AK_Assign;
5549 
5550   typedef bool result_type;
5551   bool failed() { return Failed; }
5552   bool found(APValue &Subobj, QualType SubobjType) {
5553     // We are supposed to perform no initialization but begin the lifetime of
5554     // the object. We interpret that as meaning to do what default
5555     // initialization of the object would do if all constructors involved were
5556     // trivial:
5557     //  * All base, non-variant member, and array element subobjects' lifetimes
5558     //    begin
5559     //  * No variant members' lifetimes begin
5560     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5561     assert(SubobjType->isUnionType());
5562     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5563       // This union member is already active. If it's also in-lifetime, there's
5564       // nothing to do.
5565       if (Subobj.getUnionValue().hasValue())
5566         return true;
5567     } else if (DuringInit) {
5568       // We're currently in the process of initializing a different union
5569       // member.  If we carried on, that initialization would attempt to
5570       // store to an inactive union member, resulting in undefined behavior.
5571       Info.FFDiag(LHSExpr,
5572                   diag::note_constexpr_union_member_change_during_init);
5573       return false;
5574     }
5575     APValue Result;
5576     Failed = !getDefaultInitValue(Field->getType(), Result);
5577     Subobj.setUnion(Field, Result);
5578     return true;
5579   }
5580   bool found(APSInt &Value, QualType SubobjType) {
5581     llvm_unreachable("wrong value kind for union object");
5582   }
5583   bool found(APFloat &Value, QualType SubobjType) {
5584     llvm_unreachable("wrong value kind for union object");
5585   }
5586 };
5587 } // end anonymous namespace
5588 
5589 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5590 
5591 /// Handle a builtin simple-assignment or a call to a trivial assignment
5592 /// operator whose left-hand side might involve a union member access. If it
5593 /// does, implicitly start the lifetime of any accessed union elements per
5594 /// C++20 [class.union]5.
5595 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5596                                           const LValue &LHS) {
5597   if (LHS.InvalidBase || LHS.Designator.Invalid)
5598     return false;
5599 
5600   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5601   // C++ [class.union]p5:
5602   //   define the set S(E) of subexpressions of E as follows:
5603   unsigned PathLength = LHS.Designator.Entries.size();
5604   for (const Expr *E = LHSExpr; E != nullptr;) {
5605     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5606     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5607       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5608       // Note that we can't implicitly start the lifetime of a reference,
5609       // so we don't need to proceed any further if we reach one.
5610       if (!FD || FD->getType()->isReferenceType())
5611         break;
5612 
5613       //    ... and also contains A.B if B names a union member ...
5614       if (FD->getParent()->isUnion()) {
5615         //    ... of a non-class, non-array type, or of a class type with a
5616         //    trivial default constructor that is not deleted, or an array of
5617         //    such types.
5618         auto *RD =
5619             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5620         if (!RD || RD->hasTrivialDefaultConstructor())
5621           UnionPathLengths.push_back({PathLength - 1, FD});
5622       }
5623 
5624       E = ME->getBase();
5625       --PathLength;
5626       assert(declaresSameEntity(FD,
5627                                 LHS.Designator.Entries[PathLength]
5628                                     .getAsBaseOrMember().getPointer()));
5629 
5630       //   -- If E is of the form A[B] and is interpreted as a built-in array
5631       //      subscripting operator, S(E) is [S(the array operand, if any)].
5632     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5633       // Step over an ArrayToPointerDecay implicit cast.
5634       auto *Base = ASE->getBase()->IgnoreImplicit();
5635       if (!Base->getType()->isArrayType())
5636         break;
5637 
5638       E = Base;
5639       --PathLength;
5640 
5641     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5642       // Step over a derived-to-base conversion.
5643       E = ICE->getSubExpr();
5644       if (ICE->getCastKind() == CK_NoOp)
5645         continue;
5646       if (ICE->getCastKind() != CK_DerivedToBase &&
5647           ICE->getCastKind() != CK_UncheckedDerivedToBase)
5648         break;
5649       // Walk path backwards as we walk up from the base to the derived class.
5650       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5651         --PathLength;
5652         (void)Elt;
5653         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5654                                   LHS.Designator.Entries[PathLength]
5655                                       .getAsBaseOrMember().getPointer()));
5656       }
5657 
5658     //   -- Otherwise, S(E) is empty.
5659     } else {
5660       break;
5661     }
5662   }
5663 
5664   // Common case: no unions' lifetimes are started.
5665   if (UnionPathLengths.empty())
5666     return true;
5667 
5668   //   if modification of X [would access an inactive union member], an object
5669   //   of the type of X is implicitly created
5670   CompleteObject Obj =
5671       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5672   if (!Obj)
5673     return false;
5674   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5675            llvm::reverse(UnionPathLengths)) {
5676     // Form a designator for the union object.
5677     SubobjectDesignator D = LHS.Designator;
5678     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5679 
5680     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
5681                       ConstructionPhase::AfterBases;
5682     StartLifetimeOfUnionMemberHandler StartLifetime{
5683         Info, LHSExpr, LengthAndField.second, DuringInit};
5684     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5685       return false;
5686   }
5687 
5688   return true;
5689 }
5690 
5691 namespace {
5692 typedef SmallVector<APValue, 8> ArgVector;
5693 }
5694 
5695 /// EvaluateArgs - Evaluate the arguments to a function call.
5696 static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
5697                          EvalInfo &Info, const FunctionDecl *Callee) {
5698   bool Success = true;
5699   llvm::SmallBitVector ForbiddenNullArgs;
5700   if (Callee->hasAttr<NonNullAttr>()) {
5701     ForbiddenNullArgs.resize(Args.size());
5702     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5703       if (!Attr->args_size()) {
5704         ForbiddenNullArgs.set();
5705         break;
5706       } else
5707         for (auto Idx : Attr->args()) {
5708           unsigned ASTIdx = Idx.getASTIndex();
5709           if (ASTIdx >= Args.size())
5710             continue;
5711           ForbiddenNullArgs[ASTIdx] = 1;
5712         }
5713     }
5714   }
5715   // FIXME: This is the wrong evaluation order for an assignment operator
5716   // called via operator syntax.
5717   for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
5718     if (!Evaluate(ArgValues[Idx], Info, Args[Idx])) {
5719       // If we're checking for a potential constant expression, evaluate all
5720       // initializers even if some of them fail.
5721       if (!Info.noteFailure())
5722         return false;
5723       Success = false;
5724     } else if (!ForbiddenNullArgs.empty() &&
5725                ForbiddenNullArgs[Idx] &&
5726                ArgValues[Idx].isLValue() &&
5727                ArgValues[Idx].isNullPointer()) {
5728       Info.CCEDiag(Args[Idx], diag::note_non_null_attribute_failed);
5729       if (!Info.noteFailure())
5730         return false;
5731       Success = false;
5732     }
5733   }
5734   return Success;
5735 }
5736 
5737 /// Evaluate a function call.
5738 static bool HandleFunctionCall(SourceLocation CallLoc,
5739                                const FunctionDecl *Callee, const LValue *This,
5740                                ArrayRef<const Expr*> Args, const Stmt *Body,
5741                                EvalInfo &Info, APValue &Result,
5742                                const LValue *ResultSlot) {
5743   ArgVector ArgValues(Args.size());
5744   if (!EvaluateArgs(Args, ArgValues, Info, Callee))
5745     return false;
5746 
5747   if (!Info.CheckCallLimit(CallLoc))
5748     return false;
5749 
5750   CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
5751 
5752   // For a trivial copy or move assignment, perform an APValue copy. This is
5753   // essential for unions, where the operations performed by the assignment
5754   // operator cannot be represented as statements.
5755   //
5756   // Skip this for non-union classes with no fields; in that case, the defaulted
5757   // copy/move does not actually read the object.
5758   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
5759   if (MD && MD->isDefaulted() &&
5760       (MD->getParent()->isUnion() ||
5761        (MD->isTrivial() &&
5762         isReadByLvalueToRvalueConversion(MD->getParent())))) {
5763     assert(This &&
5764            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
5765     LValue RHS;
5766     RHS.setFrom(Info.Ctx, ArgValues[0]);
5767     APValue RHSValue;
5768     if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS,
5769                                         RHSValue, MD->getParent()->isUnion()))
5770       return false;
5771     if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() &&
5772         !HandleUnionActiveMemberChange(Info, Args[0], *This))
5773       return false;
5774     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
5775                           RHSValue))
5776       return false;
5777     This->moveInto(Result);
5778     return true;
5779   } else if (MD && isLambdaCallOperator(MD)) {
5780     // We're in a lambda; determine the lambda capture field maps unless we're
5781     // just constexpr checking a lambda's call operator. constexpr checking is
5782     // done before the captures have been added to the closure object (unless
5783     // we're inferring constexpr-ness), so we don't have access to them in this
5784     // case. But since we don't need the captures to constexpr check, we can
5785     // just ignore them.
5786     if (!Info.checkingPotentialConstantExpression())
5787       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5788                                         Frame.LambdaThisCaptureField);
5789   }
5790 
5791   StmtResult Ret = {Result, ResultSlot};
5792   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
5793   if (ESR == ESR_Succeeded) {
5794     if (Callee->getReturnType()->isVoidType())
5795       return true;
5796     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
5797   }
5798   return ESR == ESR_Returned;
5799 }
5800 
5801 /// Evaluate a constructor call.
5802 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5803                                   APValue *ArgValues,
5804                                   const CXXConstructorDecl *Definition,
5805                                   EvalInfo &Info, APValue &Result) {
5806   SourceLocation CallLoc = E->getExprLoc();
5807   if (!Info.CheckCallLimit(CallLoc))
5808     return false;
5809 
5810   const CXXRecordDecl *RD = Definition->getParent();
5811   if (RD->getNumVBases()) {
5812     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5813     return false;
5814   }
5815 
5816   EvalInfo::EvaluatingConstructorRAII EvalObj(
5817       Info,
5818       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5819       RD->getNumBases());
5820   CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
5821 
5822   // FIXME: Creating an APValue just to hold a nonexistent return value is
5823   // wasteful.
5824   APValue RetVal;
5825   StmtResult Ret = {RetVal, nullptr};
5826 
5827   // If it's a delegating constructor, delegate.
5828   if (Definition->isDelegatingConstructor()) {
5829     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
5830     {
5831       FullExpressionRAII InitScope(Info);
5832       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
5833           !InitScope.destroy())
5834         return false;
5835     }
5836     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5837   }
5838 
5839   // For a trivial copy or move constructor, perform an APValue copy. This is
5840   // essential for unions (or classes with anonymous union members), where the
5841   // operations performed by the constructor cannot be represented by
5842   // ctor-initializers.
5843   //
5844   // Skip this for empty non-union classes; we should not perform an
5845   // lvalue-to-rvalue conversion on them because their copy constructor does not
5846   // actually read them.
5847   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
5848       (Definition->getParent()->isUnion() ||
5849        (Definition->isTrivial() &&
5850         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
5851     LValue RHS;
5852     RHS.setFrom(Info.Ctx, ArgValues[0]);
5853     return handleLValueToRValueConversion(
5854         Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
5855         RHS, Result, Definition->getParent()->isUnion());
5856   }
5857 
5858   // Reserve space for the struct members.
5859   if (!Result.hasValue()) {
5860     if (!RD->isUnion())
5861       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5862                        std::distance(RD->field_begin(), RD->field_end()));
5863     else
5864       // A union starts with no active member.
5865       Result = APValue((const FieldDecl*)nullptr);
5866   }
5867 
5868   if (RD->isInvalidDecl()) return false;
5869   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5870 
5871   // A scope for temporaries lifetime-extended by reference members.
5872   BlockScopeRAII LifetimeExtendedScope(Info);
5873 
5874   bool Success = true;
5875   unsigned BasesSeen = 0;
5876 #ifndef NDEBUG
5877   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5878 #endif
5879   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
5880   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
5881     // We might be initializing the same field again if this is an indirect
5882     // field initialization.
5883     if (FieldIt == RD->field_end() ||
5884         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
5885       assert(Indirect && "fields out of order?");
5886       return;
5887     }
5888 
5889     // Default-initialize any fields with no explicit initializer.
5890     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
5891       assert(FieldIt != RD->field_end() && "missing field?");
5892       if (!FieldIt->isUnnamedBitfield())
5893         Success &= getDefaultInitValue(
5894             FieldIt->getType(),
5895             Result.getStructField(FieldIt->getFieldIndex()));
5896     }
5897     ++FieldIt;
5898   };
5899   for (const auto *I : Definition->inits()) {
5900     LValue Subobject = This;
5901     LValue SubobjectParent = This;
5902     APValue *Value = &Result;
5903 
5904     // Determine the subobject to initialize.
5905     FieldDecl *FD = nullptr;
5906     if (I->isBaseInitializer()) {
5907       QualType BaseType(I->getBaseClass(), 0);
5908 #ifndef NDEBUG
5909       // Non-virtual base classes are initialized in the order in the class
5910       // definition. We have already checked for virtual base classes.
5911       assert(!BaseIt->isVirtual() && "virtual base for literal type");
5912       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5913              "base class initializers not in expected order");
5914       ++BaseIt;
5915 #endif
5916       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
5917                                   BaseType->getAsCXXRecordDecl(), &Layout))
5918         return false;
5919       Value = &Result.getStructBase(BasesSeen++);
5920     } else if ((FD = I->getMember())) {
5921       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
5922         return false;
5923       if (RD->isUnion()) {
5924         Result = APValue(FD);
5925         Value = &Result.getUnionValue();
5926       } else {
5927         SkipToField(FD, false);
5928         Value = &Result.getStructField(FD->getFieldIndex());
5929       }
5930     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
5931       // Walk the indirect field decl's chain to find the object to initialize,
5932       // and make sure we've initialized every step along it.
5933       auto IndirectFieldChain = IFD->chain();
5934       for (auto *C : IndirectFieldChain) {
5935         FD = cast<FieldDecl>(C);
5936         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5937         // Switch the union field if it differs. This happens if we had
5938         // preceding zero-initialization, and we're now initializing a union
5939         // subobject other than the first.
5940         // FIXME: In this case, the values of the other subobjects are
5941         // specified, since zero-initialization sets all padding bits to zero.
5942         if (!Value->hasValue() ||
5943             (Value->isUnion() && Value->getUnionField() != FD)) {
5944           if (CD->isUnion())
5945             *Value = APValue(FD);
5946           else
5947             // FIXME: This immediately starts the lifetime of all members of
5948             // an anonymous struct. It would be preferable to strictly start
5949             // member lifetime in initialization order.
5950             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
5951         }
5952         // Store Subobject as its parent before updating it for the last element
5953         // in the chain.
5954         if (C == IndirectFieldChain.back())
5955           SubobjectParent = Subobject;
5956         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
5957           return false;
5958         if (CD->isUnion())
5959           Value = &Value->getUnionValue();
5960         else {
5961           if (C == IndirectFieldChain.front() && !RD->isUnion())
5962             SkipToField(FD, true);
5963           Value = &Value->getStructField(FD->getFieldIndex());
5964         }
5965       }
5966     } else {
5967       llvm_unreachable("unknown base initializer kind");
5968     }
5969 
5970     // Need to override This for implicit field initializers as in this case
5971     // This refers to innermost anonymous struct/union containing initializer,
5972     // not to currently constructed class.
5973     const Expr *Init = I->getInit();
5974     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
5975                                   isa<CXXDefaultInitExpr>(Init));
5976     FullExpressionRAII InitScope(Info);
5977     if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
5978         (FD && FD->isBitField() &&
5979          !truncateBitfieldValue(Info, Init, *Value, FD))) {
5980       // If we're checking for a potential constant expression, evaluate all
5981       // initializers even if some of them fail.
5982       if (!Info.noteFailure())
5983         return false;
5984       Success = false;
5985     }
5986 
5987     // This is the point at which the dynamic type of the object becomes this
5988     // class type.
5989     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
5990       EvalObj.finishedConstructingBases();
5991   }
5992 
5993   // Default-initialize any remaining fields.
5994   if (!RD->isUnion()) {
5995     for (; FieldIt != RD->field_end(); ++FieldIt) {
5996       if (!FieldIt->isUnnamedBitfield())
5997         Success &= getDefaultInitValue(
5998             FieldIt->getType(),
5999             Result.getStructField(FieldIt->getFieldIndex()));
6000     }
6001   }
6002 
6003   EvalObj.finishedConstructingFields();
6004 
6005   return Success &&
6006          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6007          LifetimeExtendedScope.destroy();
6008 }
6009 
6010 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6011                                   ArrayRef<const Expr*> Args,
6012                                   const CXXConstructorDecl *Definition,
6013                                   EvalInfo &Info, APValue &Result) {
6014   ArgVector ArgValues(Args.size());
6015   if (!EvaluateArgs(Args, ArgValues, Info, Definition))
6016     return false;
6017 
6018   return HandleConstructorCall(E, This, ArgValues.data(), Definition,
6019                                Info, Result);
6020 }
6021 
6022 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6023                                   const LValue &This, APValue &Value,
6024                                   QualType T) {
6025   // Objects can only be destroyed while they're within their lifetimes.
6026   // FIXME: We have no representation for whether an object of type nullptr_t
6027   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6028   // as indeterminate instead?
6029   if (Value.isAbsent() && !T->isNullPtrType()) {
6030     APValue Printable;
6031     This.moveInto(Printable);
6032     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6033       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6034     return false;
6035   }
6036 
6037   // Invent an expression for location purposes.
6038   // FIXME: We shouldn't need to do this.
6039   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue);
6040 
6041   // For arrays, destroy elements right-to-left.
6042   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6043     uint64_t Size = CAT->getSize().getZExtValue();
6044     QualType ElemT = CAT->getElementType();
6045 
6046     LValue ElemLV = This;
6047     ElemLV.addArray(Info, &LocE, CAT);
6048     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6049       return false;
6050 
6051     // Ensure that we have actual array elements available to destroy; the
6052     // destructors might mutate the value, so we can't run them on the array
6053     // filler.
6054     if (Size && Size > Value.getArrayInitializedElts())
6055       expandArray(Value, Value.getArraySize() - 1);
6056 
6057     for (; Size != 0; --Size) {
6058       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6059       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6060           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6061         return false;
6062     }
6063 
6064     // End the lifetime of this array now.
6065     Value = APValue();
6066     return true;
6067   }
6068 
6069   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6070   if (!RD) {
6071     if (T.isDestructedType()) {
6072       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6073       return false;
6074     }
6075 
6076     Value = APValue();
6077     return true;
6078   }
6079 
6080   if (RD->getNumVBases()) {
6081     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6082     return false;
6083   }
6084 
6085   const CXXDestructorDecl *DD = RD->getDestructor();
6086   if (!DD && !RD->hasTrivialDestructor()) {
6087     Info.FFDiag(CallLoc);
6088     return false;
6089   }
6090 
6091   if (!DD || DD->isTrivial() ||
6092       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6093     // A trivial destructor just ends the lifetime of the object. Check for
6094     // this case before checking for a body, because we might not bother
6095     // building a body for a trivial destructor. Note that it doesn't matter
6096     // whether the destructor is constexpr in this case; all trivial
6097     // destructors are constexpr.
6098     //
6099     // If an anonymous union would be destroyed, some enclosing destructor must
6100     // have been explicitly defined, and the anonymous union destruction should
6101     // have no effect.
6102     Value = APValue();
6103     return true;
6104   }
6105 
6106   if (!Info.CheckCallLimit(CallLoc))
6107     return false;
6108 
6109   const FunctionDecl *Definition = nullptr;
6110   const Stmt *Body = DD->getBody(Definition);
6111 
6112   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6113     return false;
6114 
6115   CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr);
6116 
6117   // We're now in the period of destruction of this object.
6118   unsigned BasesLeft = RD->getNumBases();
6119   EvalInfo::EvaluatingDestructorRAII EvalObj(
6120       Info,
6121       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6122   if (!EvalObj.DidInsert) {
6123     // C++2a [class.dtor]p19:
6124     //   the behavior is undefined if the destructor is invoked for an object
6125     //   whose lifetime has ended
6126     // (Note that formally the lifetime ends when the period of destruction
6127     // begins, even though certain uses of the object remain valid until the
6128     // period of destruction ends.)
6129     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6130     return false;
6131   }
6132 
6133   // FIXME: Creating an APValue just to hold a nonexistent return value is
6134   // wasteful.
6135   APValue RetVal;
6136   StmtResult Ret = {RetVal, nullptr};
6137   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6138     return false;
6139 
6140   // A union destructor does not implicitly destroy its members.
6141   if (RD->isUnion())
6142     return true;
6143 
6144   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6145 
6146   // We don't have a good way to iterate fields in reverse, so collect all the
6147   // fields first and then walk them backwards.
6148   SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
6149   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6150     if (FD->isUnnamedBitfield())
6151       continue;
6152 
6153     LValue Subobject = This;
6154     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6155       return false;
6156 
6157     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6158     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6159                                FD->getType()))
6160       return false;
6161   }
6162 
6163   if (BasesLeft != 0)
6164     EvalObj.startedDestroyingBases();
6165 
6166   // Destroy base classes in reverse order.
6167   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6168     --BasesLeft;
6169 
6170     QualType BaseType = Base.getType();
6171     LValue Subobject = This;
6172     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6173                                 BaseType->getAsCXXRecordDecl(), &Layout))
6174       return false;
6175 
6176     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6177     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6178                                BaseType))
6179       return false;
6180   }
6181   assert(BasesLeft == 0 && "NumBases was wrong?");
6182 
6183   // The period of destruction ends now. The object is gone.
6184   Value = APValue();
6185   return true;
6186 }
6187 
6188 namespace {
6189 struct DestroyObjectHandler {
6190   EvalInfo &Info;
6191   const Expr *E;
6192   const LValue &This;
6193   const AccessKinds AccessKind;
6194 
6195   typedef bool result_type;
6196   bool failed() { return false; }
6197   bool found(APValue &Subobj, QualType SubobjType) {
6198     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6199                                  SubobjType);
6200   }
6201   bool found(APSInt &Value, QualType SubobjType) {
6202     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6203     return false;
6204   }
6205   bool found(APFloat &Value, QualType SubobjType) {
6206     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6207     return false;
6208   }
6209 };
6210 }
6211 
6212 /// Perform a destructor or pseudo-destructor call on the given object, which
6213 /// might in general not be a complete object.
6214 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6215                               const LValue &This, QualType ThisType) {
6216   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6217   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6218   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6219 }
6220 
6221 /// Destroy and end the lifetime of the given complete object.
6222 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6223                               APValue::LValueBase LVBase, APValue &Value,
6224                               QualType T) {
6225   // If we've had an unmodeled side-effect, we can't rely on mutable state
6226   // (such as the object we're about to destroy) being correct.
6227   if (Info.EvalStatus.HasSideEffects)
6228     return false;
6229 
6230   LValue LV;
6231   LV.set({LVBase});
6232   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6233 }
6234 
6235 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6236 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6237                                   LValue &Result) {
6238   if (Info.checkingPotentialConstantExpression() ||
6239       Info.SpeculativeEvaluationDepth)
6240     return false;
6241 
6242   // This is permitted only within a call to std::allocator<T>::allocate.
6243   auto Caller = Info.getStdAllocatorCaller("allocate");
6244   if (!Caller) {
6245     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6246                                      ? diag::note_constexpr_new_untyped
6247                                      : diag::note_constexpr_new);
6248     return false;
6249   }
6250 
6251   QualType ElemType = Caller.ElemType;
6252   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6253     Info.FFDiag(E->getExprLoc(),
6254                 diag::note_constexpr_new_not_complete_object_type)
6255         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6256     return false;
6257   }
6258 
6259   APSInt ByteSize;
6260   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6261     return false;
6262   bool IsNothrow = false;
6263   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6264     EvaluateIgnoredValue(Info, E->getArg(I));
6265     IsNothrow |= E->getType()->isNothrowT();
6266   }
6267 
6268   CharUnits ElemSize;
6269   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6270     return false;
6271   APInt Size, Remainder;
6272   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6273   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6274   if (Remainder != 0) {
6275     // This likely indicates a bug in the implementation of 'std::allocator'.
6276     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6277         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6278     return false;
6279   }
6280 
6281   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6282     if (IsNothrow) {
6283       Result.setNull(Info.Ctx, E->getType());
6284       return true;
6285     }
6286 
6287     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6288     return false;
6289   }
6290 
6291   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6292                                                      ArrayType::Normal, 0);
6293   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6294   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6295   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6296   return true;
6297 }
6298 
6299 static bool hasVirtualDestructor(QualType T) {
6300   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6301     if (CXXDestructorDecl *DD = RD->getDestructor())
6302       return DD->isVirtual();
6303   return false;
6304 }
6305 
6306 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6307   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6308     if (CXXDestructorDecl *DD = RD->getDestructor())
6309       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6310   return nullptr;
6311 }
6312 
6313 /// Check that the given object is a suitable pointer to a heap allocation that
6314 /// still exists and is of the right kind for the purpose of a deletion.
6315 ///
6316 /// On success, returns the heap allocation to deallocate. On failure, produces
6317 /// a diagnostic and returns None.
6318 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6319                                             const LValue &Pointer,
6320                                             DynAlloc::Kind DeallocKind) {
6321   auto PointerAsString = [&] {
6322     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6323   };
6324 
6325   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6326   if (!DA) {
6327     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6328         << PointerAsString();
6329     if (Pointer.Base)
6330       NoteLValueLocation(Info, Pointer.Base);
6331     return None;
6332   }
6333 
6334   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6335   if (!Alloc) {
6336     Info.FFDiag(E, diag::note_constexpr_double_delete);
6337     return None;
6338   }
6339 
6340   QualType AllocType = Pointer.Base.getDynamicAllocType();
6341   if (DeallocKind != (*Alloc)->getKind()) {
6342     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6343         << DeallocKind << (*Alloc)->getKind() << AllocType;
6344     NoteLValueLocation(Info, Pointer.Base);
6345     return None;
6346   }
6347 
6348   bool Subobject = false;
6349   if (DeallocKind == DynAlloc::New) {
6350     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6351                 Pointer.Designator.isOnePastTheEnd();
6352   } else {
6353     Subobject = Pointer.Designator.Entries.size() != 1 ||
6354                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6355   }
6356   if (Subobject) {
6357     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6358         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6359     return None;
6360   }
6361 
6362   return Alloc;
6363 }
6364 
6365 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6366 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6367   if (Info.checkingPotentialConstantExpression() ||
6368       Info.SpeculativeEvaluationDepth)
6369     return false;
6370 
6371   // This is permitted only within a call to std::allocator<T>::deallocate.
6372   if (!Info.getStdAllocatorCaller("deallocate")) {
6373     Info.FFDiag(E->getExprLoc());
6374     return true;
6375   }
6376 
6377   LValue Pointer;
6378   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6379     return false;
6380   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6381     EvaluateIgnoredValue(Info, E->getArg(I));
6382 
6383   if (Pointer.Designator.Invalid)
6384     return false;
6385 
6386   // Deleting a null pointer has no effect.
6387   if (Pointer.isNullPointer())
6388     return true;
6389 
6390   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6391     return false;
6392 
6393   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6394   return true;
6395 }
6396 
6397 //===----------------------------------------------------------------------===//
6398 // Generic Evaluation
6399 //===----------------------------------------------------------------------===//
6400 namespace {
6401 
6402 class BitCastBuffer {
6403   // FIXME: We're going to need bit-level granularity when we support
6404   // bit-fields.
6405   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6406   // we don't support a host or target where that is the case. Still, we should
6407   // use a more generic type in case we ever do.
6408   SmallVector<Optional<unsigned char>, 32> Bytes;
6409 
6410   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6411                 "Need at least 8 bit unsigned char");
6412 
6413   bool TargetIsLittleEndian;
6414 
6415 public:
6416   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6417       : Bytes(Width.getQuantity()),
6418         TargetIsLittleEndian(TargetIsLittleEndian) {}
6419 
6420   LLVM_NODISCARD
6421   bool readObject(CharUnits Offset, CharUnits Width,
6422                   SmallVectorImpl<unsigned char> &Output) const {
6423     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6424       // If a byte of an integer is uninitialized, then the whole integer is
6425       // uninitalized.
6426       if (!Bytes[I.getQuantity()])
6427         return false;
6428       Output.push_back(*Bytes[I.getQuantity()]);
6429     }
6430     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6431       std::reverse(Output.begin(), Output.end());
6432     return true;
6433   }
6434 
6435   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6436     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6437       std::reverse(Input.begin(), Input.end());
6438 
6439     size_t Index = 0;
6440     for (unsigned char Byte : Input) {
6441       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6442       Bytes[Offset.getQuantity() + Index] = Byte;
6443       ++Index;
6444     }
6445   }
6446 
6447   size_t size() { return Bytes.size(); }
6448 };
6449 
6450 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6451 /// target would represent the value at runtime.
6452 class APValueToBufferConverter {
6453   EvalInfo &Info;
6454   BitCastBuffer Buffer;
6455   const CastExpr *BCE;
6456 
6457   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6458                            const CastExpr *BCE)
6459       : Info(Info),
6460         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6461         BCE(BCE) {}
6462 
6463   bool visit(const APValue &Val, QualType Ty) {
6464     return visit(Val, Ty, CharUnits::fromQuantity(0));
6465   }
6466 
6467   // Write out Val with type Ty into Buffer starting at Offset.
6468   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6469     assert((size_t)Offset.getQuantity() <= Buffer.size());
6470 
6471     // As a special case, nullptr_t has an indeterminate value.
6472     if (Ty->isNullPtrType())
6473       return true;
6474 
6475     // Dig through Src to find the byte at SrcOffset.
6476     switch (Val.getKind()) {
6477     case APValue::Indeterminate:
6478     case APValue::None:
6479       return true;
6480 
6481     case APValue::Int:
6482       return visitInt(Val.getInt(), Ty, Offset);
6483     case APValue::Float:
6484       return visitFloat(Val.getFloat(), Ty, Offset);
6485     case APValue::Array:
6486       return visitArray(Val, Ty, Offset);
6487     case APValue::Struct:
6488       return visitRecord(Val, Ty, Offset);
6489 
6490     case APValue::ComplexInt:
6491     case APValue::ComplexFloat:
6492     case APValue::Vector:
6493     case APValue::FixedPoint:
6494       // FIXME: We should support these.
6495 
6496     case APValue::Union:
6497     case APValue::MemberPointer:
6498     case APValue::AddrLabelDiff: {
6499       Info.FFDiag(BCE->getBeginLoc(),
6500                   diag::note_constexpr_bit_cast_unsupported_type)
6501           << Ty;
6502       return false;
6503     }
6504 
6505     case APValue::LValue:
6506       llvm_unreachable("LValue subobject in bit_cast?");
6507     }
6508     llvm_unreachable("Unhandled APValue::ValueKind");
6509   }
6510 
6511   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6512     const RecordDecl *RD = Ty->getAsRecordDecl();
6513     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6514 
6515     // Visit the base classes.
6516     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6517       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6518         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6519         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6520 
6521         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6522                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6523           return false;
6524       }
6525     }
6526 
6527     // Visit the fields.
6528     unsigned FieldIdx = 0;
6529     for (FieldDecl *FD : RD->fields()) {
6530       if (FD->isBitField()) {
6531         Info.FFDiag(BCE->getBeginLoc(),
6532                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6533         return false;
6534       }
6535 
6536       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6537 
6538       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6539              "only bit-fields can have sub-char alignment");
6540       CharUnits FieldOffset =
6541           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6542       QualType FieldTy = FD->getType();
6543       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6544         return false;
6545       ++FieldIdx;
6546     }
6547 
6548     return true;
6549   }
6550 
6551   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6552     const auto *CAT =
6553         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6554     if (!CAT)
6555       return false;
6556 
6557     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6558     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6559     unsigned ArraySize = Val.getArraySize();
6560     // First, initialize the initialized elements.
6561     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6562       const APValue &SubObj = Val.getArrayInitializedElt(I);
6563       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6564         return false;
6565     }
6566 
6567     // Next, initialize the rest of the array using the filler.
6568     if (Val.hasArrayFiller()) {
6569       const APValue &Filler = Val.getArrayFiller();
6570       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6571         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6572           return false;
6573       }
6574     }
6575 
6576     return true;
6577   }
6578 
6579   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6580     CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
6581     SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
6582     llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
6583     Buffer.writeObject(Offset, Bytes);
6584     return true;
6585   }
6586 
6587   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6588     APSInt AsInt(Val.bitcastToAPInt());
6589     return visitInt(AsInt, Ty, Offset);
6590   }
6591 
6592 public:
6593   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6594                                          const CastExpr *BCE) {
6595     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6596     APValueToBufferConverter Converter(Info, DstSize, BCE);
6597     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6598       return None;
6599     return Converter.Buffer;
6600   }
6601 };
6602 
6603 /// Write an BitCastBuffer into an APValue.
6604 class BufferToAPValueConverter {
6605   EvalInfo &Info;
6606   const BitCastBuffer &Buffer;
6607   const CastExpr *BCE;
6608 
6609   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6610                            const CastExpr *BCE)
6611       : Info(Info), Buffer(Buffer), BCE(BCE) {}
6612 
6613   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6614   // with an invalid type, so anything left is a deficiency on our part (FIXME).
6615   // Ideally this will be unreachable.
6616   llvm::NoneType unsupportedType(QualType Ty) {
6617     Info.FFDiag(BCE->getBeginLoc(),
6618                 diag::note_constexpr_bit_cast_unsupported_type)
6619         << Ty;
6620     return None;
6621   }
6622 
6623   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6624                           const EnumType *EnumSugar = nullptr) {
6625     if (T->isNullPtrType()) {
6626       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6627       return APValue((Expr *)nullptr,
6628                      /*Offset=*/CharUnits::fromQuantity(NullValue),
6629                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6630     }
6631 
6632     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6633     SmallVector<uint8_t, 8> Bytes;
6634     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
6635       // If this is std::byte or unsigned char, then its okay to store an
6636       // indeterminate value.
6637       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
6638       bool IsUChar =
6639           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
6640                          T->isSpecificBuiltinType(BuiltinType::Char_U));
6641       if (!IsStdByte && !IsUChar) {
6642         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
6643         Info.FFDiag(BCE->getExprLoc(),
6644                     diag::note_constexpr_bit_cast_indet_dest)
6645             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
6646         return None;
6647       }
6648 
6649       return APValue::IndeterminateValue();
6650     }
6651 
6652     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
6653     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
6654 
6655     if (T->isIntegralOrEnumerationType()) {
6656       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
6657       return APValue(Val);
6658     }
6659 
6660     if (T->isRealFloatingType()) {
6661       const llvm::fltSemantics &Semantics =
6662           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6663       return APValue(APFloat(Semantics, Val));
6664     }
6665 
6666     return unsupportedType(QualType(T, 0));
6667   }
6668 
6669   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
6670     const RecordDecl *RD = RTy->getAsRecordDecl();
6671     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6672 
6673     unsigned NumBases = 0;
6674     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6675       NumBases = CXXRD->getNumBases();
6676 
6677     APValue ResultVal(APValue::UninitStruct(), NumBases,
6678                       std::distance(RD->field_begin(), RD->field_end()));
6679 
6680     // Visit the base classes.
6681     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6682       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6683         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6684         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6685         if (BaseDecl->isEmpty() ||
6686             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
6687           continue;
6688 
6689         Optional<APValue> SubObj = visitType(
6690             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
6691         if (!SubObj)
6692           return None;
6693         ResultVal.getStructBase(I) = *SubObj;
6694       }
6695     }
6696 
6697     // Visit the fields.
6698     unsigned FieldIdx = 0;
6699     for (FieldDecl *FD : RD->fields()) {
6700       // FIXME: We don't currently support bit-fields. A lot of the logic for
6701       // this is in CodeGen, so we need to factor it around.
6702       if (FD->isBitField()) {
6703         Info.FFDiag(BCE->getBeginLoc(),
6704                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6705         return None;
6706       }
6707 
6708       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6709       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
6710 
6711       CharUnits FieldOffset =
6712           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
6713           Offset;
6714       QualType FieldTy = FD->getType();
6715       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
6716       if (!SubObj)
6717         return None;
6718       ResultVal.getStructField(FieldIdx) = *SubObj;
6719       ++FieldIdx;
6720     }
6721 
6722     return ResultVal;
6723   }
6724 
6725   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
6726     QualType RepresentationType = Ty->getDecl()->getIntegerType();
6727     assert(!RepresentationType.isNull() &&
6728            "enum forward decl should be caught by Sema");
6729     const auto *AsBuiltin =
6730         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
6731     // Recurse into the underlying type. Treat std::byte transparently as
6732     // unsigned char.
6733     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
6734   }
6735 
6736   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
6737     size_t Size = Ty->getSize().getLimitedValue();
6738     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
6739 
6740     APValue ArrayValue(APValue::UninitArray(), Size, Size);
6741     for (size_t I = 0; I != Size; ++I) {
6742       Optional<APValue> ElementValue =
6743           visitType(Ty->getElementType(), Offset + I * ElementWidth);
6744       if (!ElementValue)
6745         return None;
6746       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
6747     }
6748 
6749     return ArrayValue;
6750   }
6751 
6752   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
6753     return unsupportedType(QualType(Ty, 0));
6754   }
6755 
6756   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
6757     QualType Can = Ty.getCanonicalType();
6758 
6759     switch (Can->getTypeClass()) {
6760 #define TYPE(Class, Base)                                                      \
6761   case Type::Class:                                                            \
6762     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
6763 #define ABSTRACT_TYPE(Class, Base)
6764 #define NON_CANONICAL_TYPE(Class, Base)                                        \
6765   case Type::Class:                                                            \
6766     llvm_unreachable("non-canonical type should be impossible!");
6767 #define DEPENDENT_TYPE(Class, Base)                                            \
6768   case Type::Class:                                                            \
6769     llvm_unreachable(                                                          \
6770         "dependent types aren't supported in the constant evaluator!");
6771 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
6772   case Type::Class:                                                            \
6773     llvm_unreachable("either dependent or not canonical!");
6774 #include "clang/AST/TypeNodes.inc"
6775     }
6776     llvm_unreachable("Unhandled Type::TypeClass");
6777   }
6778 
6779 public:
6780   // Pull out a full value of type DstType.
6781   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
6782                                    const CastExpr *BCE) {
6783     BufferToAPValueConverter Converter(Info, Buffer, BCE);
6784     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
6785   }
6786 };
6787 
6788 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
6789                                                  QualType Ty, EvalInfo *Info,
6790                                                  const ASTContext &Ctx,
6791                                                  bool CheckingDest) {
6792   Ty = Ty.getCanonicalType();
6793 
6794   auto diag = [&](int Reason) {
6795     if (Info)
6796       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
6797           << CheckingDest << (Reason == 4) << Reason;
6798     return false;
6799   };
6800   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
6801     if (Info)
6802       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
6803           << NoteTy << Construct << Ty;
6804     return false;
6805   };
6806 
6807   if (Ty->isUnionType())
6808     return diag(0);
6809   if (Ty->isPointerType())
6810     return diag(1);
6811   if (Ty->isMemberPointerType())
6812     return diag(2);
6813   if (Ty.isVolatileQualified())
6814     return diag(3);
6815 
6816   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
6817     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
6818       for (CXXBaseSpecifier &BS : CXXRD->bases())
6819         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
6820                                                   CheckingDest))
6821           return note(1, BS.getType(), BS.getBeginLoc());
6822     }
6823     for (FieldDecl *FD : Record->fields()) {
6824       if (FD->getType()->isReferenceType())
6825         return diag(4);
6826       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
6827                                                 CheckingDest))
6828         return note(0, FD->getType(), FD->getBeginLoc());
6829     }
6830   }
6831 
6832   if (Ty->isArrayType() &&
6833       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
6834                                             Info, Ctx, CheckingDest))
6835     return false;
6836 
6837   return true;
6838 }
6839 
6840 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
6841                                              const ASTContext &Ctx,
6842                                              const CastExpr *BCE) {
6843   bool DestOK = checkBitCastConstexprEligibilityType(
6844       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
6845   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
6846                                 BCE->getBeginLoc(),
6847                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
6848   return SourceOK;
6849 }
6850 
6851 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
6852                                         APValue &SourceValue,
6853                                         const CastExpr *BCE) {
6854   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
6855          "no host or target supports non 8-bit chars");
6856   assert(SourceValue.isLValue() &&
6857          "LValueToRValueBitcast requires an lvalue operand!");
6858 
6859   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
6860     return false;
6861 
6862   LValue SourceLValue;
6863   APValue SourceRValue;
6864   SourceLValue.setFrom(Info.Ctx, SourceValue);
6865   if (!handleLValueToRValueConversion(
6866           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
6867           SourceRValue, /*WantObjectRepresentation=*/true))
6868     return false;
6869 
6870   // Read out SourceValue into a char buffer.
6871   Optional<BitCastBuffer> Buffer =
6872       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
6873   if (!Buffer)
6874     return false;
6875 
6876   // Write out the buffer into a new APValue.
6877   Optional<APValue> MaybeDestValue =
6878       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
6879   if (!MaybeDestValue)
6880     return false;
6881 
6882   DestValue = std::move(*MaybeDestValue);
6883   return true;
6884 }
6885 
6886 template <class Derived>
6887 class ExprEvaluatorBase
6888   : public ConstStmtVisitor<Derived, bool> {
6889 private:
6890   Derived &getDerived() { return static_cast<Derived&>(*this); }
6891   bool DerivedSuccess(const APValue &V, const Expr *E) {
6892     return getDerived().Success(V, E);
6893   }
6894   bool DerivedZeroInitialization(const Expr *E) {
6895     return getDerived().ZeroInitialization(E);
6896   }
6897 
6898   // Check whether a conditional operator with a non-constant condition is a
6899   // potential constant expression. If neither arm is a potential constant
6900   // expression, then the conditional operator is not either.
6901   template<typename ConditionalOperator>
6902   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
6903     assert(Info.checkingPotentialConstantExpression());
6904 
6905     // Speculatively evaluate both arms.
6906     SmallVector<PartialDiagnosticAt, 8> Diag;
6907     {
6908       SpeculativeEvaluationRAII Speculate(Info, &Diag);
6909       StmtVisitorTy::Visit(E->getFalseExpr());
6910       if (Diag.empty())
6911         return;
6912     }
6913 
6914     {
6915       SpeculativeEvaluationRAII Speculate(Info, &Diag);
6916       Diag.clear();
6917       StmtVisitorTy::Visit(E->getTrueExpr());
6918       if (Diag.empty())
6919         return;
6920     }
6921 
6922     Error(E, diag::note_constexpr_conditional_never_const);
6923   }
6924 
6925 
6926   template<typename ConditionalOperator>
6927   bool HandleConditionalOperator(const ConditionalOperator *E) {
6928     bool BoolResult;
6929     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
6930       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
6931         CheckPotentialConstantConditional(E);
6932         return false;
6933       }
6934       if (Info.noteFailure()) {
6935         StmtVisitorTy::Visit(E->getTrueExpr());
6936         StmtVisitorTy::Visit(E->getFalseExpr());
6937       }
6938       return false;
6939     }
6940 
6941     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
6942     return StmtVisitorTy::Visit(EvalExpr);
6943   }
6944 
6945 protected:
6946   EvalInfo &Info;
6947   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
6948   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
6949 
6950   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6951     return Info.CCEDiag(E, D);
6952   }
6953 
6954   bool ZeroInitialization(const Expr *E) { return Error(E); }
6955 
6956 public:
6957   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
6958 
6959   EvalInfo &getEvalInfo() { return Info; }
6960 
6961   /// Report an evaluation error. This should only be called when an error is
6962   /// first discovered. When propagating an error, just return false.
6963   bool Error(const Expr *E, diag::kind D) {
6964     Info.FFDiag(E, D);
6965     return false;
6966   }
6967   bool Error(const Expr *E) {
6968     return Error(E, diag::note_invalid_subexpr_in_const_expr);
6969   }
6970 
6971   bool VisitStmt(const Stmt *) {
6972     llvm_unreachable("Expression evaluator should not be called on stmts");
6973   }
6974   bool VisitExpr(const Expr *E) {
6975     return Error(E);
6976   }
6977 
6978   bool VisitConstantExpr(const ConstantExpr *E) {
6979     if (E->hasAPValueResult())
6980       return DerivedSuccess(E->getAPValueResult(), E);
6981 
6982     return StmtVisitorTy::Visit(E->getSubExpr());
6983   }
6984 
6985   bool VisitParenExpr(const ParenExpr *E)
6986     { return StmtVisitorTy::Visit(E->getSubExpr()); }
6987   bool VisitUnaryExtension(const UnaryOperator *E)
6988     { return StmtVisitorTy::Visit(E->getSubExpr()); }
6989   bool VisitUnaryPlus(const UnaryOperator *E)
6990     { return StmtVisitorTy::Visit(E->getSubExpr()); }
6991   bool VisitChooseExpr(const ChooseExpr *E)
6992     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
6993   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
6994     { return StmtVisitorTy::Visit(E->getResultExpr()); }
6995   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
6996     { return StmtVisitorTy::Visit(E->getReplacement()); }
6997   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
6998     TempVersionRAII RAII(*Info.CurrentCall);
6999     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7000     return StmtVisitorTy::Visit(E->getExpr());
7001   }
7002   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7003     TempVersionRAII RAII(*Info.CurrentCall);
7004     // The initializer may not have been parsed yet, or might be erroneous.
7005     if (!E->getExpr())
7006       return Error(E);
7007     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7008     return StmtVisitorTy::Visit(E->getExpr());
7009   }
7010 
7011   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7012     FullExpressionRAII Scope(Info);
7013     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7014   }
7015 
7016   // Temporaries are registered when created, so we don't care about
7017   // CXXBindTemporaryExpr.
7018   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7019     return StmtVisitorTy::Visit(E->getSubExpr());
7020   }
7021 
7022   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7023     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7024     return static_cast<Derived*>(this)->VisitCastExpr(E);
7025   }
7026   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7027     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7028       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7029     return static_cast<Derived*>(this)->VisitCastExpr(E);
7030   }
7031   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7032     return static_cast<Derived*>(this)->VisitCastExpr(E);
7033   }
7034 
7035   bool VisitBinaryOperator(const BinaryOperator *E) {
7036     switch (E->getOpcode()) {
7037     default:
7038       return Error(E);
7039 
7040     case BO_Comma:
7041       VisitIgnoredValue(E->getLHS());
7042       return StmtVisitorTy::Visit(E->getRHS());
7043 
7044     case BO_PtrMemD:
7045     case BO_PtrMemI: {
7046       LValue Obj;
7047       if (!HandleMemberPointerAccess(Info, E, Obj))
7048         return false;
7049       APValue Result;
7050       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7051         return false;
7052       return DerivedSuccess(Result, E);
7053     }
7054     }
7055   }
7056 
7057   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7058     return StmtVisitorTy::Visit(E->getSemanticForm());
7059   }
7060 
7061   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7062     // Evaluate and cache the common expression. We treat it as a temporary,
7063     // even though it's not quite the same thing.
7064     LValue CommonLV;
7065     if (!Evaluate(Info.CurrentCall->createTemporary(
7066                       E->getOpaqueValue(),
7067                       getStorageType(Info.Ctx, E->getOpaqueValue()), false,
7068                       CommonLV),
7069                   Info, E->getCommon()))
7070       return false;
7071 
7072     return HandleConditionalOperator(E);
7073   }
7074 
7075   bool VisitConditionalOperator(const ConditionalOperator *E) {
7076     bool IsBcpCall = false;
7077     // If the condition (ignoring parens) is a __builtin_constant_p call,
7078     // the result is a constant expression if it can be folded without
7079     // side-effects. This is an important GNU extension. See GCC PR38377
7080     // for discussion.
7081     if (const CallExpr *CallCE =
7082           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7083       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7084         IsBcpCall = true;
7085 
7086     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7087     // constant expression; we can't check whether it's potentially foldable.
7088     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7089     // it would return 'false' in this mode.
7090     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7091       return false;
7092 
7093     FoldConstant Fold(Info, IsBcpCall);
7094     if (!HandleConditionalOperator(E)) {
7095       Fold.keepDiagnostics();
7096       return false;
7097     }
7098 
7099     return true;
7100   }
7101 
7102   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7103     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7104       return DerivedSuccess(*Value, E);
7105 
7106     const Expr *Source = E->getSourceExpr();
7107     if (!Source)
7108       return Error(E);
7109     if (Source == E) { // sanity checking.
7110       assert(0 && "OpaqueValueExpr recursively refers to itself");
7111       return Error(E);
7112     }
7113     return StmtVisitorTy::Visit(Source);
7114   }
7115 
7116   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7117     for (const Expr *SemE : E->semantics()) {
7118       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7119         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7120         // result expression: there could be two different LValues that would
7121         // refer to the same object in that case, and we can't model that.
7122         if (SemE == E->getResultExpr())
7123           return Error(E);
7124 
7125         // Unique OVEs get evaluated if and when we encounter them when
7126         // emitting the rest of the semantic form, rather than eagerly.
7127         if (OVE->isUnique())
7128           continue;
7129 
7130         LValue LV;
7131         if (!Evaluate(Info.CurrentCall->createTemporary(
7132                           OVE, getStorageType(Info.Ctx, OVE), false, LV),
7133                       Info, OVE->getSourceExpr()))
7134           return false;
7135       } else if (SemE == E->getResultExpr()) {
7136         if (!StmtVisitorTy::Visit(SemE))
7137           return false;
7138       } else {
7139         if (!EvaluateIgnoredValue(Info, SemE))
7140           return false;
7141       }
7142     }
7143     return true;
7144   }
7145 
7146   bool VisitCallExpr(const CallExpr *E) {
7147     APValue Result;
7148     if (!handleCallExpr(E, Result, nullptr))
7149       return false;
7150     return DerivedSuccess(Result, E);
7151   }
7152 
7153   bool handleCallExpr(const CallExpr *E, APValue &Result,
7154                      const LValue *ResultSlot) {
7155     const Expr *Callee = E->getCallee()->IgnoreParens();
7156     QualType CalleeType = Callee->getType();
7157 
7158     const FunctionDecl *FD = nullptr;
7159     LValue *This = nullptr, ThisVal;
7160     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7161     bool HasQualifier = false;
7162 
7163     // Extract function decl and 'this' pointer from the callee.
7164     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7165       const CXXMethodDecl *Member = nullptr;
7166       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7167         // Explicit bound member calls, such as x.f() or p->g();
7168         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7169           return false;
7170         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7171         if (!Member)
7172           return Error(Callee);
7173         This = &ThisVal;
7174         HasQualifier = ME->hasQualifier();
7175       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7176         // Indirect bound member calls ('.*' or '->*').
7177         const ValueDecl *D =
7178             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7179         if (!D)
7180           return false;
7181         Member = dyn_cast<CXXMethodDecl>(D);
7182         if (!Member)
7183           return Error(Callee);
7184         This = &ThisVal;
7185       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7186         if (!Info.getLangOpts().CPlusPlus20)
7187           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7188         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7189                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7190       } else
7191         return Error(Callee);
7192       FD = Member;
7193     } else if (CalleeType->isFunctionPointerType()) {
7194       LValue Call;
7195       if (!EvaluatePointer(Callee, Call, Info))
7196         return false;
7197 
7198       if (!Call.getLValueOffset().isZero())
7199         return Error(Callee);
7200       FD = dyn_cast_or_null<FunctionDecl>(
7201                              Call.getLValueBase().dyn_cast<const ValueDecl*>());
7202       if (!FD)
7203         return Error(Callee);
7204       // Don't call function pointers which have been cast to some other type.
7205       // Per DR (no number yet), the caller and callee can differ in noexcept.
7206       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7207         CalleeType->getPointeeType(), FD->getType())) {
7208         return Error(E);
7209       }
7210 
7211       // Overloaded operator calls to member functions are represented as normal
7212       // calls with '*this' as the first argument.
7213       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7214       if (MD && !MD->isStatic()) {
7215         // FIXME: When selecting an implicit conversion for an overloaded
7216         // operator delete, we sometimes try to evaluate calls to conversion
7217         // operators without a 'this' parameter!
7218         if (Args.empty())
7219           return Error(E);
7220 
7221         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7222           return false;
7223         This = &ThisVal;
7224         Args = Args.slice(1);
7225       } else if (MD && MD->isLambdaStaticInvoker()) {
7226         // Map the static invoker for the lambda back to the call operator.
7227         // Conveniently, we don't have to slice out the 'this' argument (as is
7228         // being done for the non-static case), since a static member function
7229         // doesn't have an implicit argument passed in.
7230         const CXXRecordDecl *ClosureClass = MD->getParent();
7231         assert(
7232             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7233             "Number of captures must be zero for conversion to function-ptr");
7234 
7235         const CXXMethodDecl *LambdaCallOp =
7236             ClosureClass->getLambdaCallOperator();
7237 
7238         // Set 'FD', the function that will be called below, to the call
7239         // operator.  If the closure object represents a generic lambda, find
7240         // the corresponding specialization of the call operator.
7241 
7242         if (ClosureClass->isGenericLambda()) {
7243           assert(MD->isFunctionTemplateSpecialization() &&
7244                  "A generic lambda's static-invoker function must be a "
7245                  "template specialization");
7246           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7247           FunctionTemplateDecl *CallOpTemplate =
7248               LambdaCallOp->getDescribedFunctionTemplate();
7249           void *InsertPos = nullptr;
7250           FunctionDecl *CorrespondingCallOpSpecialization =
7251               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7252           assert(CorrespondingCallOpSpecialization &&
7253                  "We must always have a function call operator specialization "
7254                  "that corresponds to our static invoker specialization");
7255           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7256         } else
7257           FD = LambdaCallOp;
7258       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7259         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7260             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7261           LValue Ptr;
7262           if (!HandleOperatorNewCall(Info, E, Ptr))
7263             return false;
7264           Ptr.moveInto(Result);
7265           return true;
7266         } else {
7267           return HandleOperatorDeleteCall(Info, E);
7268         }
7269       }
7270     } else
7271       return Error(E);
7272 
7273     SmallVector<QualType, 4> CovariantAdjustmentPath;
7274     if (This) {
7275       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7276       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7277         // Perform virtual dispatch, if necessary.
7278         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7279                                    CovariantAdjustmentPath);
7280         if (!FD)
7281           return false;
7282       } else {
7283         // Check that the 'this' pointer points to an object of the right type.
7284         // FIXME: If this is an assignment operator call, we may need to change
7285         // the active union member before we check this.
7286         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7287           return false;
7288       }
7289     }
7290 
7291     // Destructor calls are different enough that they have their own codepath.
7292     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7293       assert(This && "no 'this' pointer for destructor call");
7294       return HandleDestruction(Info, E, *This,
7295                                Info.Ctx.getRecordType(DD->getParent()));
7296     }
7297 
7298     const FunctionDecl *Definition = nullptr;
7299     Stmt *Body = FD->getBody(Definition);
7300 
7301     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7302         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
7303                             Result, ResultSlot))
7304       return false;
7305 
7306     if (!CovariantAdjustmentPath.empty() &&
7307         !HandleCovariantReturnAdjustment(Info, E, Result,
7308                                          CovariantAdjustmentPath))
7309       return false;
7310 
7311     return true;
7312   }
7313 
7314   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7315     return StmtVisitorTy::Visit(E->getInitializer());
7316   }
7317   bool VisitInitListExpr(const InitListExpr *E) {
7318     if (E->getNumInits() == 0)
7319       return DerivedZeroInitialization(E);
7320     if (E->getNumInits() == 1)
7321       return StmtVisitorTy::Visit(E->getInit(0));
7322     return Error(E);
7323   }
7324   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7325     return DerivedZeroInitialization(E);
7326   }
7327   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7328     return DerivedZeroInitialization(E);
7329   }
7330   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7331     return DerivedZeroInitialization(E);
7332   }
7333 
7334   /// A member expression where the object is a prvalue is itself a prvalue.
7335   bool VisitMemberExpr(const MemberExpr *E) {
7336     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7337            "missing temporary materialization conversion");
7338     assert(!E->isArrow() && "missing call to bound member function?");
7339 
7340     APValue Val;
7341     if (!Evaluate(Val, Info, E->getBase()))
7342       return false;
7343 
7344     QualType BaseTy = E->getBase()->getType();
7345 
7346     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7347     if (!FD) return Error(E);
7348     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7349     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7350            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7351 
7352     // Note: there is no lvalue base here. But this case should only ever
7353     // happen in C or in C++98, where we cannot be evaluating a constexpr
7354     // constructor, which is the only case the base matters.
7355     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7356     SubobjectDesignator Designator(BaseTy);
7357     Designator.addDeclUnchecked(FD);
7358 
7359     APValue Result;
7360     return extractSubobject(Info, E, Obj, Designator, Result) &&
7361            DerivedSuccess(Result, E);
7362   }
7363 
7364   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7365     APValue Val;
7366     if (!Evaluate(Val, Info, E->getBase()))
7367       return false;
7368 
7369     if (Val.isVector()) {
7370       SmallVector<uint32_t, 4> Indices;
7371       E->getEncodedElementAccess(Indices);
7372       if (Indices.size() == 1) {
7373         // Return scalar.
7374         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7375       } else {
7376         // Construct new APValue vector.
7377         SmallVector<APValue, 4> Elts;
7378         for (unsigned I = 0; I < Indices.size(); ++I) {
7379           Elts.push_back(Val.getVectorElt(Indices[I]));
7380         }
7381         APValue VecResult(Elts.data(), Indices.size());
7382         return DerivedSuccess(VecResult, E);
7383       }
7384     }
7385 
7386     return false;
7387   }
7388 
7389   bool VisitCastExpr(const CastExpr *E) {
7390     switch (E->getCastKind()) {
7391     default:
7392       break;
7393 
7394     case CK_AtomicToNonAtomic: {
7395       APValue AtomicVal;
7396       // This does not need to be done in place even for class/array types:
7397       // atomic-to-non-atomic conversion implies copying the object
7398       // representation.
7399       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7400         return false;
7401       return DerivedSuccess(AtomicVal, E);
7402     }
7403 
7404     case CK_NoOp:
7405     case CK_UserDefinedConversion:
7406       return StmtVisitorTy::Visit(E->getSubExpr());
7407 
7408     case CK_LValueToRValue: {
7409       LValue LVal;
7410       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7411         return false;
7412       APValue RVal;
7413       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7414       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7415                                           LVal, RVal))
7416         return false;
7417       return DerivedSuccess(RVal, E);
7418     }
7419     case CK_LValueToRValueBitCast: {
7420       APValue DestValue, SourceValue;
7421       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7422         return false;
7423       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7424         return false;
7425       return DerivedSuccess(DestValue, E);
7426     }
7427 
7428     case CK_AddressSpaceConversion: {
7429       APValue Value;
7430       if (!Evaluate(Value, Info, E->getSubExpr()))
7431         return false;
7432       return DerivedSuccess(Value, E);
7433     }
7434     }
7435 
7436     return Error(E);
7437   }
7438 
7439   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7440     return VisitUnaryPostIncDec(UO);
7441   }
7442   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7443     return VisitUnaryPostIncDec(UO);
7444   }
7445   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7446     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7447       return Error(UO);
7448 
7449     LValue LVal;
7450     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7451       return false;
7452     APValue RVal;
7453     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7454                       UO->isIncrementOp(), &RVal))
7455       return false;
7456     return DerivedSuccess(RVal, UO);
7457   }
7458 
7459   bool VisitStmtExpr(const StmtExpr *E) {
7460     // We will have checked the full-expressions inside the statement expression
7461     // when they were completed, and don't need to check them again now.
7462     if (Info.checkingForUndefinedBehavior())
7463       return Error(E);
7464 
7465     const CompoundStmt *CS = E->getSubStmt();
7466     if (CS->body_empty())
7467       return true;
7468 
7469     BlockScopeRAII Scope(Info);
7470     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7471                                            BE = CS->body_end();
7472          /**/; ++BI) {
7473       if (BI + 1 == BE) {
7474         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7475         if (!FinalExpr) {
7476           Info.FFDiag((*BI)->getBeginLoc(),
7477                       diag::note_constexpr_stmt_expr_unsupported);
7478           return false;
7479         }
7480         return this->Visit(FinalExpr) && Scope.destroy();
7481       }
7482 
7483       APValue ReturnValue;
7484       StmtResult Result = { ReturnValue, nullptr };
7485       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7486       if (ESR != ESR_Succeeded) {
7487         // FIXME: If the statement-expression terminated due to 'return',
7488         // 'break', or 'continue', it would be nice to propagate that to
7489         // the outer statement evaluation rather than bailing out.
7490         if (ESR != ESR_Failed)
7491           Info.FFDiag((*BI)->getBeginLoc(),
7492                       diag::note_constexpr_stmt_expr_unsupported);
7493         return false;
7494       }
7495     }
7496 
7497     llvm_unreachable("Return from function from the loop above.");
7498   }
7499 
7500   /// Visit a value which is evaluated, but whose value is ignored.
7501   void VisitIgnoredValue(const Expr *E) {
7502     EvaluateIgnoredValue(Info, E);
7503   }
7504 
7505   /// Potentially visit a MemberExpr's base expression.
7506   void VisitIgnoredBaseExpression(const Expr *E) {
7507     // While MSVC doesn't evaluate the base expression, it does diagnose the
7508     // presence of side-effecting behavior.
7509     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7510       return;
7511     VisitIgnoredValue(E);
7512   }
7513 };
7514 
7515 } // namespace
7516 
7517 //===----------------------------------------------------------------------===//
7518 // Common base class for lvalue and temporary evaluation.
7519 //===----------------------------------------------------------------------===//
7520 namespace {
7521 template<class Derived>
7522 class LValueExprEvaluatorBase
7523   : public ExprEvaluatorBase<Derived> {
7524 protected:
7525   LValue &Result;
7526   bool InvalidBaseOK;
7527   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7528   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7529 
7530   bool Success(APValue::LValueBase B) {
7531     Result.set(B);
7532     return true;
7533   }
7534 
7535   bool evaluatePointer(const Expr *E, LValue &Result) {
7536     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7537   }
7538 
7539 public:
7540   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7541       : ExprEvaluatorBaseTy(Info), Result(Result),
7542         InvalidBaseOK(InvalidBaseOK) {}
7543 
7544   bool Success(const APValue &V, const Expr *E) {
7545     Result.setFrom(this->Info.Ctx, V);
7546     return true;
7547   }
7548 
7549   bool VisitMemberExpr(const MemberExpr *E) {
7550     // Handle non-static data members.
7551     QualType BaseTy;
7552     bool EvalOK;
7553     if (E->isArrow()) {
7554       EvalOK = evaluatePointer(E->getBase(), Result);
7555       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
7556     } else if (E->getBase()->isRValue()) {
7557       assert(E->getBase()->getType()->isRecordType());
7558       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
7559       BaseTy = E->getBase()->getType();
7560     } else {
7561       EvalOK = this->Visit(E->getBase());
7562       BaseTy = E->getBase()->getType();
7563     }
7564     if (!EvalOK) {
7565       if (!InvalidBaseOK)
7566         return false;
7567       Result.setInvalid(E);
7568       return true;
7569     }
7570 
7571     const ValueDecl *MD = E->getMemberDecl();
7572     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
7573       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7574              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7575       (void)BaseTy;
7576       if (!HandleLValueMember(this->Info, E, Result, FD))
7577         return false;
7578     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
7579       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
7580         return false;
7581     } else
7582       return this->Error(E);
7583 
7584     if (MD->getType()->isReferenceType()) {
7585       APValue RefValue;
7586       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
7587                                           RefValue))
7588         return false;
7589       return Success(RefValue, E);
7590     }
7591     return true;
7592   }
7593 
7594   bool VisitBinaryOperator(const BinaryOperator *E) {
7595     switch (E->getOpcode()) {
7596     default:
7597       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7598 
7599     case BO_PtrMemD:
7600     case BO_PtrMemI:
7601       return HandleMemberPointerAccess(this->Info, E, Result);
7602     }
7603   }
7604 
7605   bool VisitCastExpr(const CastExpr *E) {
7606     switch (E->getCastKind()) {
7607     default:
7608       return ExprEvaluatorBaseTy::VisitCastExpr(E);
7609 
7610     case CK_DerivedToBase:
7611     case CK_UncheckedDerivedToBase:
7612       if (!this->Visit(E->getSubExpr()))
7613         return false;
7614 
7615       // Now figure out the necessary offset to add to the base LV to get from
7616       // the derived class to the base class.
7617       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
7618                                   Result);
7619     }
7620   }
7621 };
7622 }
7623 
7624 //===----------------------------------------------------------------------===//
7625 // LValue Evaluation
7626 //
7627 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
7628 // function designators (in C), decl references to void objects (in C), and
7629 // temporaries (if building with -Wno-address-of-temporary).
7630 //
7631 // LValue evaluation produces values comprising a base expression of one of the
7632 // following types:
7633 // - Declarations
7634 //  * VarDecl
7635 //  * FunctionDecl
7636 // - Literals
7637 //  * CompoundLiteralExpr in C (and in global scope in C++)
7638 //  * StringLiteral
7639 //  * PredefinedExpr
7640 //  * ObjCStringLiteralExpr
7641 //  * ObjCEncodeExpr
7642 //  * AddrLabelExpr
7643 //  * BlockExpr
7644 //  * CallExpr for a MakeStringConstant builtin
7645 // - typeid(T) expressions, as TypeInfoLValues
7646 // - Locals and temporaries
7647 //  * MaterializeTemporaryExpr
7648 //  * Any Expr, with a CallIndex indicating the function in which the temporary
7649 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
7650 //    from the AST (FIXME).
7651 //  * A MaterializeTemporaryExpr that has static storage duration, with no
7652 //    CallIndex, for a lifetime-extended temporary.
7653 //  * The ConstantExpr that is currently being evaluated during evaluation of an
7654 //    immediate invocation.
7655 // plus an offset in bytes.
7656 //===----------------------------------------------------------------------===//
7657 namespace {
7658 class LValueExprEvaluator
7659   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
7660 public:
7661   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
7662     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
7663 
7664   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
7665   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
7666 
7667   bool VisitDeclRefExpr(const DeclRefExpr *E);
7668   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
7669   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
7670   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
7671   bool VisitMemberExpr(const MemberExpr *E);
7672   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
7673   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
7674   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
7675   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
7676   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
7677   bool VisitUnaryDeref(const UnaryOperator *E);
7678   bool VisitUnaryReal(const UnaryOperator *E);
7679   bool VisitUnaryImag(const UnaryOperator *E);
7680   bool VisitUnaryPreInc(const UnaryOperator *UO) {
7681     return VisitUnaryPreIncDec(UO);
7682   }
7683   bool VisitUnaryPreDec(const UnaryOperator *UO) {
7684     return VisitUnaryPreIncDec(UO);
7685   }
7686   bool VisitBinAssign(const BinaryOperator *BO);
7687   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
7688 
7689   bool VisitCastExpr(const CastExpr *E) {
7690     switch (E->getCastKind()) {
7691     default:
7692       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
7693 
7694     case CK_LValueBitCast:
7695       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7696       if (!Visit(E->getSubExpr()))
7697         return false;
7698       Result.Designator.setInvalid();
7699       return true;
7700 
7701     case CK_BaseToDerived:
7702       if (!Visit(E->getSubExpr()))
7703         return false;
7704       return HandleBaseToDerivedCast(Info, E, Result);
7705 
7706     case CK_Dynamic:
7707       if (!Visit(E->getSubExpr()))
7708         return false;
7709       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
7710     }
7711   }
7712 };
7713 } // end anonymous namespace
7714 
7715 /// Evaluate an expression as an lvalue. This can be legitimately called on
7716 /// expressions which are not glvalues, in three cases:
7717 ///  * function designators in C, and
7718 ///  * "extern void" objects
7719 ///  * @selector() expressions in Objective-C
7720 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
7721                            bool InvalidBaseOK) {
7722   assert(E->isGLValue() || E->getType()->isFunctionType() ||
7723          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
7724   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
7725 }
7726 
7727 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
7728   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
7729     return Success(FD);
7730   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
7731     return VisitVarDecl(E, VD);
7732   if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
7733     return Visit(BD->getBinding());
7734   if (const MSGuidDecl *GD = dyn_cast<MSGuidDecl>(E->getDecl()))
7735     return Success(GD);
7736   return Error(E);
7737 }
7738 
7739 
7740 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
7741 
7742   // If we are within a lambda's call operator, check whether the 'VD' referred
7743   // to within 'E' actually represents a lambda-capture that maps to a
7744   // data-member/field within the closure object, and if so, evaluate to the
7745   // field or what the field refers to.
7746   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
7747       isa<DeclRefExpr>(E) &&
7748       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
7749     // We don't always have a complete capture-map when checking or inferring if
7750     // the function call operator meets the requirements of a constexpr function
7751     // - but we don't need to evaluate the captures to determine constexprness
7752     // (dcl.constexpr C++17).
7753     if (Info.checkingPotentialConstantExpression())
7754       return false;
7755 
7756     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
7757       // Start with 'Result' referring to the complete closure object...
7758       Result = *Info.CurrentCall->This;
7759       // ... then update it to refer to the field of the closure object
7760       // that represents the capture.
7761       if (!HandleLValueMember(Info, E, Result, FD))
7762         return false;
7763       // And if the field is of reference type, update 'Result' to refer to what
7764       // the field refers to.
7765       if (FD->getType()->isReferenceType()) {
7766         APValue RVal;
7767         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
7768                                             RVal))
7769           return false;
7770         Result.setFrom(Info.Ctx, RVal);
7771       }
7772       return true;
7773     }
7774   }
7775   CallStackFrame *Frame = nullptr;
7776   if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
7777     // Only if a local variable was declared in the function currently being
7778     // evaluated, do we expect to be able to find its value in the current
7779     // frame. (Otherwise it was likely declared in an enclosing context and
7780     // could either have a valid evaluatable value (for e.g. a constexpr
7781     // variable) or be ill-formed (and trigger an appropriate evaluation
7782     // diagnostic)).
7783     if (Info.CurrentCall->Callee &&
7784         Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
7785       Frame = Info.CurrentCall;
7786     }
7787   }
7788 
7789   if (!VD->getType()->isReferenceType()) {
7790     if (Frame) {
7791       Result.set({VD, Frame->Index,
7792                   Info.CurrentCall->getCurrentTemporaryVersion(VD)});
7793       return true;
7794     }
7795     return Success(VD);
7796   }
7797 
7798   APValue *V;
7799   if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
7800     return false;
7801   if (!V->hasValue()) {
7802     // FIXME: Is it possible for V to be indeterminate here? If so, we should
7803     // adjust the diagnostic to say that.
7804     if (!Info.checkingPotentialConstantExpression())
7805       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
7806     return false;
7807   }
7808   return Success(*V, E);
7809 }
7810 
7811 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
7812     const MaterializeTemporaryExpr *E) {
7813   // Walk through the expression to find the materialized temporary itself.
7814   SmallVector<const Expr *, 2> CommaLHSs;
7815   SmallVector<SubobjectAdjustment, 2> Adjustments;
7816   const Expr *Inner =
7817       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
7818 
7819   // If we passed any comma operators, evaluate their LHSs.
7820   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
7821     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
7822       return false;
7823 
7824   // A materialized temporary with static storage duration can appear within the
7825   // result of a constant expression evaluation, so we need to preserve its
7826   // value for use outside this evaluation.
7827   APValue *Value;
7828   if (E->getStorageDuration() == SD_Static) {
7829     Value = E->getOrCreateValue(true);
7830     *Value = APValue();
7831     Result.set(E);
7832   } else {
7833     Value = &Info.CurrentCall->createTemporary(
7834         E, E->getType(), E->getStorageDuration() == SD_Automatic, Result);
7835   }
7836 
7837   QualType Type = Inner->getType();
7838 
7839   // Materialize the temporary itself.
7840   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
7841     *Value = APValue();
7842     return false;
7843   }
7844 
7845   // Adjust our lvalue to refer to the desired subobject.
7846   for (unsigned I = Adjustments.size(); I != 0; /**/) {
7847     --I;
7848     switch (Adjustments[I].Kind) {
7849     case SubobjectAdjustment::DerivedToBaseAdjustment:
7850       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
7851                                 Type, Result))
7852         return false;
7853       Type = Adjustments[I].DerivedToBase.BasePath->getType();
7854       break;
7855 
7856     case SubobjectAdjustment::FieldAdjustment:
7857       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
7858         return false;
7859       Type = Adjustments[I].Field->getType();
7860       break;
7861 
7862     case SubobjectAdjustment::MemberPointerAdjustment:
7863       if (!HandleMemberPointerAccess(this->Info, Type, Result,
7864                                      Adjustments[I].Ptr.RHS))
7865         return false;
7866       Type = Adjustments[I].Ptr.MPT->getPointeeType();
7867       break;
7868     }
7869   }
7870 
7871   return true;
7872 }
7873 
7874 bool
7875 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7876   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
7877          "lvalue compound literal in c++?");
7878   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
7879   // only see this when folding in C, so there's no standard to follow here.
7880   return Success(E);
7881 }
7882 
7883 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
7884   TypeInfoLValue TypeInfo;
7885 
7886   if (!E->isPotentiallyEvaluated()) {
7887     if (E->isTypeOperand())
7888       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
7889     else
7890       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
7891   } else {
7892     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
7893       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
7894         << E->getExprOperand()->getType()
7895         << E->getExprOperand()->getSourceRange();
7896     }
7897 
7898     if (!Visit(E->getExprOperand()))
7899       return false;
7900 
7901     Optional<DynamicType> DynType =
7902         ComputeDynamicType(Info, E, Result, AK_TypeId);
7903     if (!DynType)
7904       return false;
7905 
7906     TypeInfo =
7907         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
7908   }
7909 
7910   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
7911 }
7912 
7913 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
7914   return Success(E->getGuidDecl());
7915 }
7916 
7917 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
7918   // Handle static data members.
7919   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
7920     VisitIgnoredBaseExpression(E->getBase());
7921     return VisitVarDecl(E, VD);
7922   }
7923 
7924   // Handle static member functions.
7925   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
7926     if (MD->isStatic()) {
7927       VisitIgnoredBaseExpression(E->getBase());
7928       return Success(MD);
7929     }
7930   }
7931 
7932   // Handle non-static data members.
7933   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
7934 }
7935 
7936 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
7937   // FIXME: Deal with vectors as array subscript bases.
7938   if (E->getBase()->getType()->isVectorType())
7939     return Error(E);
7940 
7941   bool Success = true;
7942   if (!evaluatePointer(E->getBase(), Result)) {
7943     if (!Info.noteFailure())
7944       return false;
7945     Success = false;
7946   }
7947 
7948   APSInt Index;
7949   if (!EvaluateInteger(E->getIdx(), Index, Info))
7950     return false;
7951 
7952   return Success &&
7953          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
7954 }
7955 
7956 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
7957   return evaluatePointer(E->getSubExpr(), Result);
7958 }
7959 
7960 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7961   if (!Visit(E->getSubExpr()))
7962     return false;
7963   // __real is a no-op on scalar lvalues.
7964   if (E->getSubExpr()->getType()->isAnyComplexType())
7965     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
7966   return true;
7967 }
7968 
7969 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7970   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
7971          "lvalue __imag__ on scalar?");
7972   if (!Visit(E->getSubExpr()))
7973     return false;
7974   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
7975   return true;
7976 }
7977 
7978 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
7979   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7980     return Error(UO);
7981 
7982   if (!this->Visit(UO->getSubExpr()))
7983     return false;
7984 
7985   return handleIncDec(
7986       this->Info, UO, Result, UO->getSubExpr()->getType(),
7987       UO->isIncrementOp(), nullptr);
7988 }
7989 
7990 bool LValueExprEvaluator::VisitCompoundAssignOperator(
7991     const CompoundAssignOperator *CAO) {
7992   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7993     return Error(CAO);
7994 
7995   APValue RHS;
7996 
7997   // The overall lvalue result is the result of evaluating the LHS.
7998   if (!this->Visit(CAO->getLHS())) {
7999     if (Info.noteFailure())
8000       Evaluate(RHS, this->Info, CAO->getRHS());
8001     return false;
8002   }
8003 
8004   if (!Evaluate(RHS, this->Info, CAO->getRHS()))
8005     return false;
8006 
8007   return handleCompoundAssignment(
8008       this->Info, CAO,
8009       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8010       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8011 }
8012 
8013 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8014   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8015     return Error(E);
8016 
8017   APValue NewVal;
8018 
8019   if (!this->Visit(E->getLHS())) {
8020     if (Info.noteFailure())
8021       Evaluate(NewVal, this->Info, E->getRHS());
8022     return false;
8023   }
8024 
8025   if (!Evaluate(NewVal, this->Info, E->getRHS()))
8026     return false;
8027 
8028   if (Info.getLangOpts().CPlusPlus20 &&
8029       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8030     return false;
8031 
8032   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8033                           NewVal);
8034 }
8035 
8036 //===----------------------------------------------------------------------===//
8037 // Pointer Evaluation
8038 //===----------------------------------------------------------------------===//
8039 
8040 /// Attempts to compute the number of bytes available at the pointer
8041 /// returned by a function with the alloc_size attribute. Returns true if we
8042 /// were successful. Places an unsigned number into `Result`.
8043 ///
8044 /// This expects the given CallExpr to be a call to a function with an
8045 /// alloc_size attribute.
8046 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8047                                             const CallExpr *Call,
8048                                             llvm::APInt &Result) {
8049   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8050 
8051   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8052   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8053   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8054   if (Call->getNumArgs() <= SizeArgNo)
8055     return false;
8056 
8057   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8058     Expr::EvalResult ExprResult;
8059     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8060       return false;
8061     Into = ExprResult.Val.getInt();
8062     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8063       return false;
8064     Into = Into.zextOrSelf(BitsInSizeT);
8065     return true;
8066   };
8067 
8068   APSInt SizeOfElem;
8069   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8070     return false;
8071 
8072   if (!AllocSize->getNumElemsParam().isValid()) {
8073     Result = std::move(SizeOfElem);
8074     return true;
8075   }
8076 
8077   APSInt NumberOfElems;
8078   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8079   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8080     return false;
8081 
8082   bool Overflow;
8083   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8084   if (Overflow)
8085     return false;
8086 
8087   Result = std::move(BytesAvailable);
8088   return true;
8089 }
8090 
8091 /// Convenience function. LVal's base must be a call to an alloc_size
8092 /// function.
8093 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8094                                             const LValue &LVal,
8095                                             llvm::APInt &Result) {
8096   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8097          "Can't get the size of a non alloc_size function");
8098   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8099   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8100   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8101 }
8102 
8103 /// Attempts to evaluate the given LValueBase as the result of a call to
8104 /// a function with the alloc_size attribute. If it was possible to do so, this
8105 /// function will return true, make Result's Base point to said function call,
8106 /// and mark Result's Base as invalid.
8107 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8108                                       LValue &Result) {
8109   if (Base.isNull())
8110     return false;
8111 
8112   // Because we do no form of static analysis, we only support const variables.
8113   //
8114   // Additionally, we can't support parameters, nor can we support static
8115   // variables (in the latter case, use-before-assign isn't UB; in the former,
8116   // we have no clue what they'll be assigned to).
8117   const auto *VD =
8118       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8119   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8120     return false;
8121 
8122   const Expr *Init = VD->getAnyInitializer();
8123   if (!Init)
8124     return false;
8125 
8126   const Expr *E = Init->IgnoreParens();
8127   if (!tryUnwrapAllocSizeCall(E))
8128     return false;
8129 
8130   // Store E instead of E unwrapped so that the type of the LValue's base is
8131   // what the user wanted.
8132   Result.setInvalid(E);
8133 
8134   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8135   Result.addUnsizedArray(Info, E, Pointee);
8136   return true;
8137 }
8138 
8139 namespace {
8140 class PointerExprEvaluator
8141   : public ExprEvaluatorBase<PointerExprEvaluator> {
8142   LValue &Result;
8143   bool InvalidBaseOK;
8144 
8145   bool Success(const Expr *E) {
8146     Result.set(E);
8147     return true;
8148   }
8149 
8150   bool evaluateLValue(const Expr *E, LValue &Result) {
8151     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8152   }
8153 
8154   bool evaluatePointer(const Expr *E, LValue &Result) {
8155     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8156   }
8157 
8158   bool visitNonBuiltinCallExpr(const CallExpr *E);
8159 public:
8160 
8161   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8162       : ExprEvaluatorBaseTy(info), Result(Result),
8163         InvalidBaseOK(InvalidBaseOK) {}
8164 
8165   bool Success(const APValue &V, const Expr *E) {
8166     Result.setFrom(Info.Ctx, V);
8167     return true;
8168   }
8169   bool ZeroInitialization(const Expr *E) {
8170     Result.setNull(Info.Ctx, E->getType());
8171     return true;
8172   }
8173 
8174   bool VisitBinaryOperator(const BinaryOperator *E);
8175   bool VisitCastExpr(const CastExpr* E);
8176   bool VisitUnaryAddrOf(const UnaryOperator *E);
8177   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8178       { return Success(E); }
8179   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8180     if (E->isExpressibleAsConstantInitializer())
8181       return Success(E);
8182     if (Info.noteFailure())
8183       EvaluateIgnoredValue(Info, E->getSubExpr());
8184     return Error(E);
8185   }
8186   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8187       { return Success(E); }
8188   bool VisitCallExpr(const CallExpr *E);
8189   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8190   bool VisitBlockExpr(const BlockExpr *E) {
8191     if (!E->getBlockDecl()->hasCaptures())
8192       return Success(E);
8193     return Error(E);
8194   }
8195   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8196     // Can't look at 'this' when checking a potential constant expression.
8197     if (Info.checkingPotentialConstantExpression())
8198       return false;
8199     if (!Info.CurrentCall->This) {
8200       if (Info.getLangOpts().CPlusPlus11)
8201         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8202       else
8203         Info.FFDiag(E);
8204       return false;
8205     }
8206     Result = *Info.CurrentCall->This;
8207     // If we are inside a lambda's call operator, the 'this' expression refers
8208     // to the enclosing '*this' object (either by value or reference) which is
8209     // either copied into the closure object's field that represents the '*this'
8210     // or refers to '*this'.
8211     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8212       // Ensure we actually have captured 'this'. (an error will have
8213       // been previously reported if not).
8214       if (!Info.CurrentCall->LambdaThisCaptureField)
8215         return false;
8216 
8217       // Update 'Result' to refer to the data member/field of the closure object
8218       // that represents the '*this' capture.
8219       if (!HandleLValueMember(Info, E, Result,
8220                              Info.CurrentCall->LambdaThisCaptureField))
8221         return false;
8222       // If we captured '*this' by reference, replace the field with its referent.
8223       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8224               ->isPointerType()) {
8225         APValue RVal;
8226         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8227                                             RVal))
8228           return false;
8229 
8230         Result.setFrom(Info.Ctx, RVal);
8231       }
8232     }
8233     return true;
8234   }
8235 
8236   bool VisitCXXNewExpr(const CXXNewExpr *E);
8237 
8238   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8239     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
8240     APValue LValResult = E->EvaluateInContext(
8241         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8242     Result.setFrom(Info.Ctx, LValResult);
8243     return true;
8244   }
8245 
8246   // FIXME: Missing: @protocol, @selector
8247 };
8248 } // end anonymous namespace
8249 
8250 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8251                             bool InvalidBaseOK) {
8252   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
8253   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8254 }
8255 
8256 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8257   if (E->getOpcode() != BO_Add &&
8258       E->getOpcode() != BO_Sub)
8259     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8260 
8261   const Expr *PExp = E->getLHS();
8262   const Expr *IExp = E->getRHS();
8263   if (IExp->getType()->isPointerType())
8264     std::swap(PExp, IExp);
8265 
8266   bool EvalPtrOK = evaluatePointer(PExp, Result);
8267   if (!EvalPtrOK && !Info.noteFailure())
8268     return false;
8269 
8270   llvm::APSInt Offset;
8271   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8272     return false;
8273 
8274   if (E->getOpcode() == BO_Sub)
8275     negateAsSigned(Offset);
8276 
8277   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8278   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8279 }
8280 
8281 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8282   return evaluateLValue(E->getSubExpr(), Result);
8283 }
8284 
8285 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8286   const Expr *SubExpr = E->getSubExpr();
8287 
8288   switch (E->getCastKind()) {
8289   default:
8290     break;
8291   case CK_BitCast:
8292   case CK_CPointerToObjCPointerCast:
8293   case CK_BlockPointerToObjCPointerCast:
8294   case CK_AnyPointerToBlockPointerCast:
8295   case CK_AddressSpaceConversion:
8296     if (!Visit(SubExpr))
8297       return false;
8298     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8299     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8300     // also static_casts, but we disallow them as a resolution to DR1312.
8301     if (!E->getType()->isVoidPointerType()) {
8302       if (!Result.InvalidBase && !Result.Designator.Invalid &&
8303           !Result.IsNullPtr &&
8304           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8305                                           E->getType()->getPointeeType()) &&
8306           Info.getStdAllocatorCaller("allocate")) {
8307         // Inside a call to std::allocator::allocate and friends, we permit
8308         // casting from void* back to cv1 T* for a pointer that points to a
8309         // cv2 T.
8310       } else {
8311         Result.Designator.setInvalid();
8312         if (SubExpr->getType()->isVoidPointerType())
8313           CCEDiag(E, diag::note_constexpr_invalid_cast)
8314             << 3 << SubExpr->getType();
8315         else
8316           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8317       }
8318     }
8319     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8320       ZeroInitialization(E);
8321     return true;
8322 
8323   case CK_DerivedToBase:
8324   case CK_UncheckedDerivedToBase:
8325     if (!evaluatePointer(E->getSubExpr(), Result))
8326       return false;
8327     if (!Result.Base && Result.Offset.isZero())
8328       return true;
8329 
8330     // Now figure out the necessary offset to add to the base LV to get from
8331     // the derived class to the base class.
8332     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8333                                   castAs<PointerType>()->getPointeeType(),
8334                                 Result);
8335 
8336   case CK_BaseToDerived:
8337     if (!Visit(E->getSubExpr()))
8338       return false;
8339     if (!Result.Base && Result.Offset.isZero())
8340       return true;
8341     return HandleBaseToDerivedCast(Info, E, Result);
8342 
8343   case CK_Dynamic:
8344     if (!Visit(E->getSubExpr()))
8345       return false;
8346     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8347 
8348   case CK_NullToPointer:
8349     VisitIgnoredValue(E->getSubExpr());
8350     return ZeroInitialization(E);
8351 
8352   case CK_IntegralToPointer: {
8353     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8354 
8355     APValue Value;
8356     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8357       break;
8358 
8359     if (Value.isInt()) {
8360       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8361       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8362       Result.Base = (Expr*)nullptr;
8363       Result.InvalidBase = false;
8364       Result.Offset = CharUnits::fromQuantity(N);
8365       Result.Designator.setInvalid();
8366       Result.IsNullPtr = false;
8367       return true;
8368     } else {
8369       // Cast is of an lvalue, no need to change value.
8370       Result.setFrom(Info.Ctx, Value);
8371       return true;
8372     }
8373   }
8374 
8375   case CK_ArrayToPointerDecay: {
8376     if (SubExpr->isGLValue()) {
8377       if (!evaluateLValue(SubExpr, Result))
8378         return false;
8379     } else {
8380       APValue &Value = Info.CurrentCall->createTemporary(
8381           SubExpr, SubExpr->getType(), false, Result);
8382       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8383         return false;
8384     }
8385     // The result is a pointer to the first element of the array.
8386     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8387     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8388       Result.addArray(Info, E, CAT);
8389     else
8390       Result.addUnsizedArray(Info, E, AT->getElementType());
8391     return true;
8392   }
8393 
8394   case CK_FunctionToPointerDecay:
8395     return evaluateLValue(SubExpr, Result);
8396 
8397   case CK_LValueToRValue: {
8398     LValue LVal;
8399     if (!evaluateLValue(E->getSubExpr(), LVal))
8400       return false;
8401 
8402     APValue RVal;
8403     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8404     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8405                                         LVal, RVal))
8406       return InvalidBaseOK &&
8407              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8408     return Success(RVal, E);
8409   }
8410   }
8411 
8412   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8413 }
8414 
8415 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8416                                 UnaryExprOrTypeTrait ExprKind) {
8417   // C++ [expr.alignof]p3:
8418   //     When alignof is applied to a reference type, the result is the
8419   //     alignment of the referenced type.
8420   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8421     T = Ref->getPointeeType();
8422 
8423   if (T.getQualifiers().hasUnaligned())
8424     return CharUnits::One();
8425 
8426   const bool AlignOfReturnsPreferred =
8427       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8428 
8429   // __alignof is defined to return the preferred alignment.
8430   // Before 8, clang returned the preferred alignment for alignof and _Alignof
8431   // as well.
8432   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8433     return Info.Ctx.toCharUnitsFromBits(
8434       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8435   // alignof and _Alignof are defined to return the ABI alignment.
8436   else if (ExprKind == UETT_AlignOf)
8437     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8438   else
8439     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8440 }
8441 
8442 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8443                                 UnaryExprOrTypeTrait ExprKind) {
8444   E = E->IgnoreParens();
8445 
8446   // The kinds of expressions that we have special-case logic here for
8447   // should be kept up to date with the special checks for those
8448   // expressions in Sema.
8449 
8450   // alignof decl is always accepted, even if it doesn't make sense: we default
8451   // to 1 in those cases.
8452   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8453     return Info.Ctx.getDeclAlign(DRE->getDecl(),
8454                                  /*RefAsPointee*/true);
8455 
8456   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8457     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8458                                  /*RefAsPointee*/true);
8459 
8460   return GetAlignOfType(Info, E->getType(), ExprKind);
8461 }
8462 
8463 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
8464   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
8465     return Info.Ctx.getDeclAlign(VD);
8466   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
8467     return GetAlignOfExpr(Info, E, UETT_AlignOf);
8468   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
8469 }
8470 
8471 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
8472 /// __builtin_is_aligned and __builtin_assume_aligned.
8473 static bool getAlignmentArgument(const Expr *E, QualType ForType,
8474                                  EvalInfo &Info, APSInt &Alignment) {
8475   if (!EvaluateInteger(E, Alignment, Info))
8476     return false;
8477   if (Alignment < 0 || !Alignment.isPowerOf2()) {
8478     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
8479     return false;
8480   }
8481   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
8482   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
8483   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
8484     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
8485         << MaxValue << ForType << Alignment;
8486     return false;
8487   }
8488   // Ensure both alignment and source value have the same bit width so that we
8489   // don't assert when computing the resulting value.
8490   APSInt ExtAlignment =
8491       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
8492   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
8493          "Alignment should not be changed by ext/trunc");
8494   Alignment = ExtAlignment;
8495   assert(Alignment.getBitWidth() == SrcWidth);
8496   return true;
8497 }
8498 
8499 // To be clear: this happily visits unsupported builtins. Better name welcomed.
8500 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8501   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8502     return true;
8503 
8504   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
8505     return false;
8506 
8507   Result.setInvalid(E);
8508   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
8509   Result.addUnsizedArray(Info, E, PointeeTy);
8510   return true;
8511 }
8512 
8513 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
8514   if (IsStringLiteralCall(E))
8515     return Success(E);
8516 
8517   if (unsigned BuiltinOp = E->getBuiltinCallee())
8518     return VisitBuiltinCallExpr(E, BuiltinOp);
8519 
8520   return visitNonBuiltinCallExpr(E);
8521 }
8522 
8523 // Determine if T is a character type for which we guarantee that
8524 // sizeof(T) == 1.
8525 static bool isOneByteCharacterType(QualType T) {
8526   return T->isCharType() || T->isChar8Type();
8527 }
8528 
8529 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8530                                                 unsigned BuiltinOp) {
8531   switch (BuiltinOp) {
8532   case Builtin::BI__builtin_addressof:
8533     return evaluateLValue(E->getArg(0), Result);
8534   case Builtin::BI__builtin_assume_aligned: {
8535     // We need to be very careful here because: if the pointer does not have the
8536     // asserted alignment, then the behavior is undefined, and undefined
8537     // behavior is non-constant.
8538     if (!evaluatePointer(E->getArg(0), Result))
8539       return false;
8540 
8541     LValue OffsetResult(Result);
8542     APSInt Alignment;
8543     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8544                               Alignment))
8545       return false;
8546     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
8547 
8548     if (E->getNumArgs() > 2) {
8549       APSInt Offset;
8550       if (!EvaluateInteger(E->getArg(2), Offset, Info))
8551         return false;
8552 
8553       int64_t AdditionalOffset = -Offset.getZExtValue();
8554       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
8555     }
8556 
8557     // If there is a base object, then it must have the correct alignment.
8558     if (OffsetResult.Base) {
8559       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
8560 
8561       if (BaseAlignment < Align) {
8562         Result.Designator.setInvalid();
8563         // FIXME: Add support to Diagnostic for long / long long.
8564         CCEDiag(E->getArg(0),
8565                 diag::note_constexpr_baa_insufficient_alignment) << 0
8566           << (unsigned)BaseAlignment.getQuantity()
8567           << (unsigned)Align.getQuantity();
8568         return false;
8569       }
8570     }
8571 
8572     // The offset must also have the correct alignment.
8573     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
8574       Result.Designator.setInvalid();
8575 
8576       (OffsetResult.Base
8577            ? CCEDiag(E->getArg(0),
8578                      diag::note_constexpr_baa_insufficient_alignment) << 1
8579            : CCEDiag(E->getArg(0),
8580                      diag::note_constexpr_baa_value_insufficient_alignment))
8581         << (int)OffsetResult.Offset.getQuantity()
8582         << (unsigned)Align.getQuantity();
8583       return false;
8584     }
8585 
8586     return true;
8587   }
8588   case Builtin::BI__builtin_align_up:
8589   case Builtin::BI__builtin_align_down: {
8590     if (!evaluatePointer(E->getArg(0), Result))
8591       return false;
8592     APSInt Alignment;
8593     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8594                               Alignment))
8595       return false;
8596     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
8597     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
8598     // For align_up/align_down, we can return the same value if the alignment
8599     // is known to be greater or equal to the requested value.
8600     if (PtrAlign.getQuantity() >= Alignment)
8601       return true;
8602 
8603     // The alignment could be greater than the minimum at run-time, so we cannot
8604     // infer much about the resulting pointer value. One case is possible:
8605     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
8606     // can infer the correct index if the requested alignment is smaller than
8607     // the base alignment so we can perform the computation on the offset.
8608     if (BaseAlignment.getQuantity() >= Alignment) {
8609       assert(Alignment.getBitWidth() <= 64 &&
8610              "Cannot handle > 64-bit address-space");
8611       uint64_t Alignment64 = Alignment.getZExtValue();
8612       CharUnits NewOffset = CharUnits::fromQuantity(
8613           BuiltinOp == Builtin::BI__builtin_align_down
8614               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
8615               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
8616       Result.adjustOffset(NewOffset - Result.Offset);
8617       // TODO: diagnose out-of-bounds values/only allow for arrays?
8618       return true;
8619     }
8620     // Otherwise, we cannot constant-evaluate the result.
8621     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
8622         << Alignment;
8623     return false;
8624   }
8625   case Builtin::BI__builtin_operator_new:
8626     return HandleOperatorNewCall(Info, E, Result);
8627   case Builtin::BI__builtin_launder:
8628     return evaluatePointer(E->getArg(0), Result);
8629   case Builtin::BIstrchr:
8630   case Builtin::BIwcschr:
8631   case Builtin::BImemchr:
8632   case Builtin::BIwmemchr:
8633     if (Info.getLangOpts().CPlusPlus11)
8634       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8635         << /*isConstexpr*/0 << /*isConstructor*/0
8636         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8637     else
8638       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8639     LLVM_FALLTHROUGH;
8640   case Builtin::BI__builtin_strchr:
8641   case Builtin::BI__builtin_wcschr:
8642   case Builtin::BI__builtin_memchr:
8643   case Builtin::BI__builtin_char_memchr:
8644   case Builtin::BI__builtin_wmemchr: {
8645     if (!Visit(E->getArg(0)))
8646       return false;
8647     APSInt Desired;
8648     if (!EvaluateInteger(E->getArg(1), Desired, Info))
8649       return false;
8650     uint64_t MaxLength = uint64_t(-1);
8651     if (BuiltinOp != Builtin::BIstrchr &&
8652         BuiltinOp != Builtin::BIwcschr &&
8653         BuiltinOp != Builtin::BI__builtin_strchr &&
8654         BuiltinOp != Builtin::BI__builtin_wcschr) {
8655       APSInt N;
8656       if (!EvaluateInteger(E->getArg(2), N, Info))
8657         return false;
8658       MaxLength = N.getExtValue();
8659     }
8660     // We cannot find the value if there are no candidates to match against.
8661     if (MaxLength == 0u)
8662       return ZeroInitialization(E);
8663     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8664         Result.Designator.Invalid)
8665       return false;
8666     QualType CharTy = Result.Designator.getType(Info.Ctx);
8667     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
8668                      BuiltinOp == Builtin::BI__builtin_memchr;
8669     assert(IsRawByte ||
8670            Info.Ctx.hasSameUnqualifiedType(
8671                CharTy, E->getArg(0)->getType()->getPointeeType()));
8672     // Pointers to const void may point to objects of incomplete type.
8673     if (IsRawByte && CharTy->isIncompleteType()) {
8674       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
8675       return false;
8676     }
8677     // Give up on byte-oriented matching against multibyte elements.
8678     // FIXME: We can compare the bytes in the correct order.
8679     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
8680       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
8681           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
8682           << CharTy;
8683       return false;
8684     }
8685     // Figure out what value we're actually looking for (after converting to
8686     // the corresponding unsigned type if necessary).
8687     uint64_t DesiredVal;
8688     bool StopAtNull = false;
8689     switch (BuiltinOp) {
8690     case Builtin::BIstrchr:
8691     case Builtin::BI__builtin_strchr:
8692       // strchr compares directly to the passed integer, and therefore
8693       // always fails if given an int that is not a char.
8694       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
8695                                                   E->getArg(1)->getType(),
8696                                                   Desired),
8697                                Desired))
8698         return ZeroInitialization(E);
8699       StopAtNull = true;
8700       LLVM_FALLTHROUGH;
8701     case Builtin::BImemchr:
8702     case Builtin::BI__builtin_memchr:
8703     case Builtin::BI__builtin_char_memchr:
8704       // memchr compares by converting both sides to unsigned char. That's also
8705       // correct for strchr if we get this far (to cope with plain char being
8706       // unsigned in the strchr case).
8707       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
8708       break;
8709 
8710     case Builtin::BIwcschr:
8711     case Builtin::BI__builtin_wcschr:
8712       StopAtNull = true;
8713       LLVM_FALLTHROUGH;
8714     case Builtin::BIwmemchr:
8715     case Builtin::BI__builtin_wmemchr:
8716       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
8717       DesiredVal = Desired.getZExtValue();
8718       break;
8719     }
8720 
8721     for (; MaxLength; --MaxLength) {
8722       APValue Char;
8723       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
8724           !Char.isInt())
8725         return false;
8726       if (Char.getInt().getZExtValue() == DesiredVal)
8727         return true;
8728       if (StopAtNull && !Char.getInt())
8729         break;
8730       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
8731         return false;
8732     }
8733     // Not found: return nullptr.
8734     return ZeroInitialization(E);
8735   }
8736 
8737   case Builtin::BImemcpy:
8738   case Builtin::BImemmove:
8739   case Builtin::BIwmemcpy:
8740   case Builtin::BIwmemmove:
8741     if (Info.getLangOpts().CPlusPlus11)
8742       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8743         << /*isConstexpr*/0 << /*isConstructor*/0
8744         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8745     else
8746       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8747     LLVM_FALLTHROUGH;
8748   case Builtin::BI__builtin_memcpy:
8749   case Builtin::BI__builtin_memmove:
8750   case Builtin::BI__builtin_wmemcpy:
8751   case Builtin::BI__builtin_wmemmove: {
8752     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
8753                  BuiltinOp == Builtin::BIwmemmove ||
8754                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
8755                  BuiltinOp == Builtin::BI__builtin_wmemmove;
8756     bool Move = BuiltinOp == Builtin::BImemmove ||
8757                 BuiltinOp == Builtin::BIwmemmove ||
8758                 BuiltinOp == Builtin::BI__builtin_memmove ||
8759                 BuiltinOp == Builtin::BI__builtin_wmemmove;
8760 
8761     // The result of mem* is the first argument.
8762     if (!Visit(E->getArg(0)))
8763       return false;
8764     LValue Dest = Result;
8765 
8766     LValue Src;
8767     if (!EvaluatePointer(E->getArg(1), Src, Info))
8768       return false;
8769 
8770     APSInt N;
8771     if (!EvaluateInteger(E->getArg(2), N, Info))
8772       return false;
8773     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
8774 
8775     // If the size is zero, we treat this as always being a valid no-op.
8776     // (Even if one of the src and dest pointers is null.)
8777     if (!N)
8778       return true;
8779 
8780     // Otherwise, if either of the operands is null, we can't proceed. Don't
8781     // try to determine the type of the copied objects, because there aren't
8782     // any.
8783     if (!Src.Base || !Dest.Base) {
8784       APValue Val;
8785       (!Src.Base ? Src : Dest).moveInto(Val);
8786       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
8787           << Move << WChar << !!Src.Base
8788           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
8789       return false;
8790     }
8791     if (Src.Designator.Invalid || Dest.Designator.Invalid)
8792       return false;
8793 
8794     // We require that Src and Dest are both pointers to arrays of
8795     // trivially-copyable type. (For the wide version, the designator will be
8796     // invalid if the designated object is not a wchar_t.)
8797     QualType T = Dest.Designator.getType(Info.Ctx);
8798     QualType SrcT = Src.Designator.getType(Info.Ctx);
8799     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
8800       // FIXME: Consider using our bit_cast implementation to support this.
8801       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
8802       return false;
8803     }
8804     if (T->isIncompleteType()) {
8805       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
8806       return false;
8807     }
8808     if (!T.isTriviallyCopyableType(Info.Ctx)) {
8809       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
8810       return false;
8811     }
8812 
8813     // Figure out how many T's we're copying.
8814     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
8815     if (!WChar) {
8816       uint64_t Remainder;
8817       llvm::APInt OrigN = N;
8818       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
8819       if (Remainder) {
8820         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8821             << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
8822             << (unsigned)TSize;
8823         return false;
8824       }
8825     }
8826 
8827     // Check that the copying will remain within the arrays, just so that we
8828     // can give a more meaningful diagnostic. This implicitly also checks that
8829     // N fits into 64 bits.
8830     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
8831     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
8832     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
8833       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8834           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
8835           << N.toString(10, /*Signed*/false);
8836       return false;
8837     }
8838     uint64_t NElems = N.getZExtValue();
8839     uint64_t NBytes = NElems * TSize;
8840 
8841     // Check for overlap.
8842     int Direction = 1;
8843     if (HasSameBase(Src, Dest)) {
8844       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
8845       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
8846       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
8847         // Dest is inside the source region.
8848         if (!Move) {
8849           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8850           return false;
8851         }
8852         // For memmove and friends, copy backwards.
8853         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
8854             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
8855           return false;
8856         Direction = -1;
8857       } else if (!Move && SrcOffset >= DestOffset &&
8858                  SrcOffset - DestOffset < NBytes) {
8859         // Src is inside the destination region for memcpy: invalid.
8860         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8861         return false;
8862       }
8863     }
8864 
8865     while (true) {
8866       APValue Val;
8867       // FIXME: Set WantObjectRepresentation to true if we're copying a
8868       // char-like type?
8869       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
8870           !handleAssignment(Info, E, Dest, T, Val))
8871         return false;
8872       // Do not iterate past the last element; if we're copying backwards, that
8873       // might take us off the start of the array.
8874       if (--NElems == 0)
8875         return true;
8876       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
8877           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
8878         return false;
8879     }
8880   }
8881 
8882   default:
8883     break;
8884   }
8885 
8886   return visitNonBuiltinCallExpr(E);
8887 }
8888 
8889 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
8890                                      APValue &Result, const InitListExpr *ILE,
8891                                      QualType AllocType);
8892 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
8893                                           APValue &Result,
8894                                           const CXXConstructExpr *CCE,
8895                                           QualType AllocType);
8896 
8897 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
8898   if (!Info.getLangOpts().CPlusPlus20)
8899     Info.CCEDiag(E, diag::note_constexpr_new);
8900 
8901   // We cannot speculatively evaluate a delete expression.
8902   if (Info.SpeculativeEvaluationDepth)
8903     return false;
8904 
8905   FunctionDecl *OperatorNew = E->getOperatorNew();
8906 
8907   bool IsNothrow = false;
8908   bool IsPlacement = false;
8909   if (OperatorNew->isReservedGlobalPlacementOperator() &&
8910       Info.CurrentCall->isStdFunction() && !E->isArray()) {
8911     // FIXME Support array placement new.
8912     assert(E->getNumPlacementArgs() == 1);
8913     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
8914       return false;
8915     if (Result.Designator.Invalid)
8916       return false;
8917     IsPlacement = true;
8918   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
8919     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
8920         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
8921     return false;
8922   } else if (E->getNumPlacementArgs()) {
8923     // The only new-placement list we support is of the form (std::nothrow).
8924     //
8925     // FIXME: There is no restriction on this, but it's not clear that any
8926     // other form makes any sense. We get here for cases such as:
8927     //
8928     //   new (std::align_val_t{N}) X(int)
8929     //
8930     // (which should presumably be valid only if N is a multiple of
8931     // alignof(int), and in any case can't be deallocated unless N is
8932     // alignof(X) and X has new-extended alignment).
8933     if (E->getNumPlacementArgs() != 1 ||
8934         !E->getPlacementArg(0)->getType()->isNothrowT())
8935       return Error(E, diag::note_constexpr_new_placement);
8936 
8937     LValue Nothrow;
8938     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
8939       return false;
8940     IsNothrow = true;
8941   }
8942 
8943   const Expr *Init = E->getInitializer();
8944   const InitListExpr *ResizedArrayILE = nullptr;
8945   const CXXConstructExpr *ResizedArrayCCE = nullptr;
8946 
8947   QualType AllocType = E->getAllocatedType();
8948   if (Optional<const Expr*> ArraySize = E->getArraySize()) {
8949     const Expr *Stripped = *ArraySize;
8950     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
8951          Stripped = ICE->getSubExpr())
8952       if (ICE->getCastKind() != CK_NoOp &&
8953           ICE->getCastKind() != CK_IntegralCast)
8954         break;
8955 
8956     llvm::APSInt ArrayBound;
8957     if (!EvaluateInteger(Stripped, ArrayBound, Info))
8958       return false;
8959 
8960     // C++ [expr.new]p9:
8961     //   The expression is erroneous if:
8962     //   -- [...] its value before converting to size_t [or] applying the
8963     //      second standard conversion sequence is less than zero
8964     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
8965       if (IsNothrow)
8966         return ZeroInitialization(E);
8967 
8968       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
8969           << ArrayBound << (*ArraySize)->getSourceRange();
8970       return false;
8971     }
8972 
8973     //   -- its value is such that the size of the allocated object would
8974     //      exceed the implementation-defined limit
8975     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
8976                                                 ArrayBound) >
8977         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
8978       if (IsNothrow)
8979         return ZeroInitialization(E);
8980 
8981       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
8982         << ArrayBound << (*ArraySize)->getSourceRange();
8983       return false;
8984     }
8985 
8986     //   -- the new-initializer is a braced-init-list and the number of
8987     //      array elements for which initializers are provided [...]
8988     //      exceeds the number of elements to initialize
8989     if (Init && !isa<CXXConstructExpr>(Init)) {
8990       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
8991       assert(CAT && "unexpected type for array initializer");
8992 
8993       unsigned Bits =
8994           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
8995       llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
8996       llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
8997       if (InitBound.ugt(AllocBound)) {
8998         if (IsNothrow)
8999           return ZeroInitialization(E);
9000 
9001         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9002             << AllocBound.toString(10, /*Signed=*/false)
9003             << InitBound.toString(10, /*Signed=*/false)
9004             << (*ArraySize)->getSourceRange();
9005         return false;
9006       }
9007 
9008       // If the sizes differ, we must have an initializer list, and we need
9009       // special handling for this case when we initialize.
9010       if (InitBound != AllocBound)
9011         ResizedArrayILE = cast<InitListExpr>(Init);
9012     } else if (Init) {
9013       ResizedArrayCCE = cast<CXXConstructExpr>(Init);
9014     }
9015 
9016     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9017                                               ArrayType::Normal, 0);
9018   } else {
9019     assert(!AllocType->isArrayType() &&
9020            "array allocation with non-array new");
9021   }
9022 
9023   APValue *Val;
9024   if (IsPlacement) {
9025     AccessKinds AK = AK_Construct;
9026     struct FindObjectHandler {
9027       EvalInfo &Info;
9028       const Expr *E;
9029       QualType AllocType;
9030       const AccessKinds AccessKind;
9031       APValue *Value;
9032 
9033       typedef bool result_type;
9034       bool failed() { return false; }
9035       bool found(APValue &Subobj, QualType SubobjType) {
9036         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9037         // old name of the object to be used to name the new object.
9038         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9039           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9040             SubobjType << AllocType;
9041           return false;
9042         }
9043         Value = &Subobj;
9044         return true;
9045       }
9046       bool found(APSInt &Value, QualType SubobjType) {
9047         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9048         return false;
9049       }
9050       bool found(APFloat &Value, QualType SubobjType) {
9051         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9052         return false;
9053       }
9054     } Handler = {Info, E, AllocType, AK, nullptr};
9055 
9056     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9057     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9058       return false;
9059 
9060     Val = Handler.Value;
9061 
9062     // [basic.life]p1:
9063     //   The lifetime of an object o of type T ends when [...] the storage
9064     //   which the object occupies is [...] reused by an object that is not
9065     //   nested within o (6.6.2).
9066     *Val = APValue();
9067   } else {
9068     // Perform the allocation and obtain a pointer to the resulting object.
9069     Val = Info.createHeapAlloc(E, AllocType, Result);
9070     if (!Val)
9071       return false;
9072   }
9073 
9074   if (ResizedArrayILE) {
9075     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9076                                   AllocType))
9077       return false;
9078   } else if (ResizedArrayCCE) {
9079     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9080                                        AllocType))
9081       return false;
9082   } else if (Init) {
9083     if (!EvaluateInPlace(*Val, Info, Result, Init))
9084       return false;
9085   } else if (!getDefaultInitValue(AllocType, *Val)) {
9086     return false;
9087   }
9088 
9089   // Array new returns a pointer to the first element, not a pointer to the
9090   // array.
9091   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9092     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9093 
9094   return true;
9095 }
9096 //===----------------------------------------------------------------------===//
9097 // Member Pointer Evaluation
9098 //===----------------------------------------------------------------------===//
9099 
9100 namespace {
9101 class MemberPointerExprEvaluator
9102   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9103   MemberPtr &Result;
9104 
9105   bool Success(const ValueDecl *D) {
9106     Result = MemberPtr(D);
9107     return true;
9108   }
9109 public:
9110 
9111   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9112     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9113 
9114   bool Success(const APValue &V, const Expr *E) {
9115     Result.setFrom(V);
9116     return true;
9117   }
9118   bool ZeroInitialization(const Expr *E) {
9119     return Success((const ValueDecl*)nullptr);
9120   }
9121 
9122   bool VisitCastExpr(const CastExpr *E);
9123   bool VisitUnaryAddrOf(const UnaryOperator *E);
9124 };
9125 } // end anonymous namespace
9126 
9127 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9128                                   EvalInfo &Info) {
9129   assert(E->isRValue() && E->getType()->isMemberPointerType());
9130   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9131 }
9132 
9133 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9134   switch (E->getCastKind()) {
9135   default:
9136     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9137 
9138   case CK_NullToMemberPointer:
9139     VisitIgnoredValue(E->getSubExpr());
9140     return ZeroInitialization(E);
9141 
9142   case CK_BaseToDerivedMemberPointer: {
9143     if (!Visit(E->getSubExpr()))
9144       return false;
9145     if (E->path_empty())
9146       return true;
9147     // Base-to-derived member pointer casts store the path in derived-to-base
9148     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9149     // the wrong end of the derived->base arc, so stagger the path by one class.
9150     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9151     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9152          PathI != PathE; ++PathI) {
9153       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9154       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9155       if (!Result.castToDerived(Derived))
9156         return Error(E);
9157     }
9158     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9159     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9160       return Error(E);
9161     return true;
9162   }
9163 
9164   case CK_DerivedToBaseMemberPointer:
9165     if (!Visit(E->getSubExpr()))
9166       return false;
9167     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9168          PathE = E->path_end(); PathI != PathE; ++PathI) {
9169       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9170       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9171       if (!Result.castToBase(Base))
9172         return Error(E);
9173     }
9174     return true;
9175   }
9176 }
9177 
9178 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9179   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9180   // member can be formed.
9181   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9182 }
9183 
9184 //===----------------------------------------------------------------------===//
9185 // Record Evaluation
9186 //===----------------------------------------------------------------------===//
9187 
9188 namespace {
9189   class RecordExprEvaluator
9190   : public ExprEvaluatorBase<RecordExprEvaluator> {
9191     const LValue &This;
9192     APValue &Result;
9193   public:
9194 
9195     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9196       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9197 
9198     bool Success(const APValue &V, const Expr *E) {
9199       Result = V;
9200       return true;
9201     }
9202     bool ZeroInitialization(const Expr *E) {
9203       return ZeroInitialization(E, E->getType());
9204     }
9205     bool ZeroInitialization(const Expr *E, QualType T);
9206 
9207     bool VisitCallExpr(const CallExpr *E) {
9208       return handleCallExpr(E, Result, &This);
9209     }
9210     bool VisitCastExpr(const CastExpr *E);
9211     bool VisitInitListExpr(const InitListExpr *E);
9212     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9213       return VisitCXXConstructExpr(E, E->getType());
9214     }
9215     bool VisitLambdaExpr(const LambdaExpr *E);
9216     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9217     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9218     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9219     bool VisitBinCmp(const BinaryOperator *E);
9220   };
9221 }
9222 
9223 /// Perform zero-initialization on an object of non-union class type.
9224 /// C++11 [dcl.init]p5:
9225 ///  To zero-initialize an object or reference of type T means:
9226 ///    [...]
9227 ///    -- if T is a (possibly cv-qualified) non-union class type,
9228 ///       each non-static data member and each base-class subobject is
9229 ///       zero-initialized
9230 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9231                                           const RecordDecl *RD,
9232                                           const LValue &This, APValue &Result) {
9233   assert(!RD->isUnion() && "Expected non-union class type");
9234   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9235   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9236                    std::distance(RD->field_begin(), RD->field_end()));
9237 
9238   if (RD->isInvalidDecl()) return false;
9239   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9240 
9241   if (CD) {
9242     unsigned Index = 0;
9243     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9244            End = CD->bases_end(); I != End; ++I, ++Index) {
9245       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9246       LValue Subobject = This;
9247       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9248         return false;
9249       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9250                                          Result.getStructBase(Index)))
9251         return false;
9252     }
9253   }
9254 
9255   for (const auto *I : RD->fields()) {
9256     // -- if T is a reference type, no initialization is performed.
9257     if (I->getType()->isReferenceType())
9258       continue;
9259 
9260     LValue Subobject = This;
9261     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9262       return false;
9263 
9264     ImplicitValueInitExpr VIE(I->getType());
9265     if (!EvaluateInPlace(
9266           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9267       return false;
9268   }
9269 
9270   return true;
9271 }
9272 
9273 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9274   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9275   if (RD->isInvalidDecl()) return false;
9276   if (RD->isUnion()) {
9277     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9278     // object's first non-static named data member is zero-initialized
9279     RecordDecl::field_iterator I = RD->field_begin();
9280     if (I == RD->field_end()) {
9281       Result = APValue((const FieldDecl*)nullptr);
9282       return true;
9283     }
9284 
9285     LValue Subobject = This;
9286     if (!HandleLValueMember(Info, E, Subobject, *I))
9287       return false;
9288     Result = APValue(*I);
9289     ImplicitValueInitExpr VIE(I->getType());
9290     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9291   }
9292 
9293   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9294     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9295     return false;
9296   }
9297 
9298   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9299 }
9300 
9301 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9302   switch (E->getCastKind()) {
9303   default:
9304     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9305 
9306   case CK_ConstructorConversion:
9307     return Visit(E->getSubExpr());
9308 
9309   case CK_DerivedToBase:
9310   case CK_UncheckedDerivedToBase: {
9311     APValue DerivedObject;
9312     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9313       return false;
9314     if (!DerivedObject.isStruct())
9315       return Error(E->getSubExpr());
9316 
9317     // Derived-to-base rvalue conversion: just slice off the derived part.
9318     APValue *Value = &DerivedObject;
9319     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9320     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9321          PathE = E->path_end(); PathI != PathE; ++PathI) {
9322       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9323       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9324       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9325       RD = Base;
9326     }
9327     Result = *Value;
9328     return true;
9329   }
9330   }
9331 }
9332 
9333 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9334   if (E->isTransparent())
9335     return Visit(E->getInit(0));
9336 
9337   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9338   if (RD->isInvalidDecl()) return false;
9339   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9340   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9341 
9342   EvalInfo::EvaluatingConstructorRAII EvalObj(
9343       Info,
9344       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9345       CXXRD && CXXRD->getNumBases());
9346 
9347   if (RD->isUnion()) {
9348     const FieldDecl *Field = E->getInitializedFieldInUnion();
9349     Result = APValue(Field);
9350     if (!Field)
9351       return true;
9352 
9353     // If the initializer list for a union does not contain any elements, the
9354     // first element of the union is value-initialized.
9355     // FIXME: The element should be initialized from an initializer list.
9356     //        Is this difference ever observable for initializer lists which
9357     //        we don't build?
9358     ImplicitValueInitExpr VIE(Field->getType());
9359     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9360 
9361     LValue Subobject = This;
9362     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9363       return false;
9364 
9365     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9366     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9367                                   isa<CXXDefaultInitExpr>(InitExpr));
9368 
9369     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
9370   }
9371 
9372   if (!Result.hasValue())
9373     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9374                      std::distance(RD->field_begin(), RD->field_end()));
9375   unsigned ElementNo = 0;
9376   bool Success = true;
9377 
9378   // Initialize base classes.
9379   if (CXXRD && CXXRD->getNumBases()) {
9380     for (const auto &Base : CXXRD->bases()) {
9381       assert(ElementNo < E->getNumInits() && "missing init for base class");
9382       const Expr *Init = E->getInit(ElementNo);
9383 
9384       LValue Subobject = This;
9385       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9386         return false;
9387 
9388       APValue &FieldVal = Result.getStructBase(ElementNo);
9389       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9390         if (!Info.noteFailure())
9391           return false;
9392         Success = false;
9393       }
9394       ++ElementNo;
9395     }
9396 
9397     EvalObj.finishedConstructingBases();
9398   }
9399 
9400   // Initialize members.
9401   for (const auto *Field : RD->fields()) {
9402     // Anonymous bit-fields are not considered members of the class for
9403     // purposes of aggregate initialization.
9404     if (Field->isUnnamedBitfield())
9405       continue;
9406 
9407     LValue Subobject = This;
9408 
9409     bool HaveInit = ElementNo < E->getNumInits();
9410 
9411     // FIXME: Diagnostics here should point to the end of the initializer
9412     // list, not the start.
9413     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9414                             Subobject, Field, &Layout))
9415       return false;
9416 
9417     // Perform an implicit value-initialization for members beyond the end of
9418     // the initializer list.
9419     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9420     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9421 
9422     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9423     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9424                                   isa<CXXDefaultInitExpr>(Init));
9425 
9426     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9427     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9428         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9429                                                        FieldVal, Field))) {
9430       if (!Info.noteFailure())
9431         return false;
9432       Success = false;
9433     }
9434   }
9435 
9436   EvalObj.finishedConstructingFields();
9437 
9438   return Success;
9439 }
9440 
9441 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9442                                                 QualType T) {
9443   // Note that E's type is not necessarily the type of our class here; we might
9444   // be initializing an array element instead.
9445   const CXXConstructorDecl *FD = E->getConstructor();
9446   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9447 
9448   bool ZeroInit = E->requiresZeroInitialization();
9449   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
9450     // If we've already performed zero-initialization, we're already done.
9451     if (Result.hasValue())
9452       return true;
9453 
9454     if (ZeroInit)
9455       return ZeroInitialization(E, T);
9456 
9457     return getDefaultInitValue(T, Result);
9458   }
9459 
9460   const FunctionDecl *Definition = nullptr;
9461   auto Body = FD->getBody(Definition);
9462 
9463   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9464     return false;
9465 
9466   // Avoid materializing a temporary for an elidable copy/move constructor.
9467   if (E->isElidable() && !ZeroInit)
9468     if (const MaterializeTemporaryExpr *ME
9469           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
9470       return Visit(ME->getSubExpr());
9471 
9472   if (ZeroInit && !ZeroInitialization(E, T))
9473     return false;
9474 
9475   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
9476   return HandleConstructorCall(E, This, Args,
9477                                cast<CXXConstructorDecl>(Definition), Info,
9478                                Result);
9479 }
9480 
9481 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9482     const CXXInheritedCtorInitExpr *E) {
9483   if (!Info.CurrentCall) {
9484     assert(Info.checkingPotentialConstantExpression());
9485     return false;
9486   }
9487 
9488   const CXXConstructorDecl *FD = E->getConstructor();
9489   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9490     return false;
9491 
9492   const FunctionDecl *Definition = nullptr;
9493   auto Body = FD->getBody(Definition);
9494 
9495   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9496     return false;
9497 
9498   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
9499                                cast<CXXConstructorDecl>(Definition), Info,
9500                                Result);
9501 }
9502 
9503 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
9504     const CXXStdInitializerListExpr *E) {
9505   const ConstantArrayType *ArrayType =
9506       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
9507 
9508   LValue Array;
9509   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
9510     return false;
9511 
9512   // Get a pointer to the first element of the array.
9513   Array.addArray(Info, E, ArrayType);
9514 
9515   auto InvalidType = [&] {
9516     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
9517       << E->getType();
9518     return false;
9519   };
9520 
9521   // FIXME: Perform the checks on the field types in SemaInit.
9522   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
9523   RecordDecl::field_iterator Field = Record->field_begin();
9524   if (Field == Record->field_end())
9525     return InvalidType();
9526 
9527   // Start pointer.
9528   if (!Field->getType()->isPointerType() ||
9529       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9530                             ArrayType->getElementType()))
9531     return InvalidType();
9532 
9533   // FIXME: What if the initializer_list type has base classes, etc?
9534   Result = APValue(APValue::UninitStruct(), 0, 2);
9535   Array.moveInto(Result.getStructField(0));
9536 
9537   if (++Field == Record->field_end())
9538     return InvalidType();
9539 
9540   if (Field->getType()->isPointerType() &&
9541       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9542                            ArrayType->getElementType())) {
9543     // End pointer.
9544     if (!HandleLValueArrayAdjustment(Info, E, Array,
9545                                      ArrayType->getElementType(),
9546                                      ArrayType->getSize().getZExtValue()))
9547       return false;
9548     Array.moveInto(Result.getStructField(1));
9549   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
9550     // Length.
9551     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
9552   else
9553     return InvalidType();
9554 
9555   if (++Field != Record->field_end())
9556     return InvalidType();
9557 
9558   return true;
9559 }
9560 
9561 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
9562   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
9563   if (ClosureClass->isInvalidDecl())
9564     return false;
9565 
9566   const size_t NumFields =
9567       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
9568 
9569   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
9570                                             E->capture_init_end()) &&
9571          "The number of lambda capture initializers should equal the number of "
9572          "fields within the closure type");
9573 
9574   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
9575   // Iterate through all the lambda's closure object's fields and initialize
9576   // them.
9577   auto *CaptureInitIt = E->capture_init_begin();
9578   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
9579   bool Success = true;
9580   for (const auto *Field : ClosureClass->fields()) {
9581     assert(CaptureInitIt != E->capture_init_end());
9582     // Get the initializer for this field
9583     Expr *const CurFieldInit = *CaptureInitIt++;
9584 
9585     // If there is no initializer, either this is a VLA or an error has
9586     // occurred.
9587     if (!CurFieldInit)
9588       return Error(E);
9589 
9590     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9591     if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
9592       if (!Info.keepEvaluatingAfterFailure())
9593         return false;
9594       Success = false;
9595     }
9596     ++CaptureIt;
9597   }
9598   return Success;
9599 }
9600 
9601 static bool EvaluateRecord(const Expr *E, const LValue &This,
9602                            APValue &Result, EvalInfo &Info) {
9603   assert(E->isRValue() && E->getType()->isRecordType() &&
9604          "can't evaluate expression as a record rvalue");
9605   return RecordExprEvaluator(Info, This, Result).Visit(E);
9606 }
9607 
9608 //===----------------------------------------------------------------------===//
9609 // Temporary Evaluation
9610 //
9611 // Temporaries are represented in the AST as rvalues, but generally behave like
9612 // lvalues. The full-object of which the temporary is a subobject is implicitly
9613 // materialized so that a reference can bind to it.
9614 //===----------------------------------------------------------------------===//
9615 namespace {
9616 class TemporaryExprEvaluator
9617   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
9618 public:
9619   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
9620     LValueExprEvaluatorBaseTy(Info, Result, false) {}
9621 
9622   /// Visit an expression which constructs the value of this temporary.
9623   bool VisitConstructExpr(const Expr *E) {
9624     APValue &Value =
9625         Info.CurrentCall->createTemporary(E, E->getType(), false, Result);
9626     return EvaluateInPlace(Value, Info, Result, E);
9627   }
9628 
9629   bool VisitCastExpr(const CastExpr *E) {
9630     switch (E->getCastKind()) {
9631     default:
9632       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9633 
9634     case CK_ConstructorConversion:
9635       return VisitConstructExpr(E->getSubExpr());
9636     }
9637   }
9638   bool VisitInitListExpr(const InitListExpr *E) {
9639     return VisitConstructExpr(E);
9640   }
9641   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9642     return VisitConstructExpr(E);
9643   }
9644   bool VisitCallExpr(const CallExpr *E) {
9645     return VisitConstructExpr(E);
9646   }
9647   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
9648     return VisitConstructExpr(E);
9649   }
9650   bool VisitLambdaExpr(const LambdaExpr *E) {
9651     return VisitConstructExpr(E);
9652   }
9653 };
9654 } // end anonymous namespace
9655 
9656 /// Evaluate an expression of record type as a temporary.
9657 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
9658   assert(E->isRValue() && E->getType()->isRecordType());
9659   return TemporaryExprEvaluator(Info, Result).Visit(E);
9660 }
9661 
9662 //===----------------------------------------------------------------------===//
9663 // Vector Evaluation
9664 //===----------------------------------------------------------------------===//
9665 
9666 namespace {
9667   class VectorExprEvaluator
9668   : public ExprEvaluatorBase<VectorExprEvaluator> {
9669     APValue &Result;
9670   public:
9671 
9672     VectorExprEvaluator(EvalInfo &info, APValue &Result)
9673       : ExprEvaluatorBaseTy(info), Result(Result) {}
9674 
9675     bool Success(ArrayRef<APValue> V, const Expr *E) {
9676       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
9677       // FIXME: remove this APValue copy.
9678       Result = APValue(V.data(), V.size());
9679       return true;
9680     }
9681     bool Success(const APValue &V, const Expr *E) {
9682       assert(V.isVector());
9683       Result = V;
9684       return true;
9685     }
9686     bool ZeroInitialization(const Expr *E);
9687 
9688     bool VisitUnaryReal(const UnaryOperator *E)
9689       { return Visit(E->getSubExpr()); }
9690     bool VisitCastExpr(const CastExpr* E);
9691     bool VisitInitListExpr(const InitListExpr *E);
9692     bool VisitUnaryImag(const UnaryOperator *E);
9693     bool VisitBinaryOperator(const BinaryOperator *E);
9694     // FIXME: Missing: unary -, unary ~, conditional operator (for GNU
9695     //                 conditional select), shufflevector, ExtVectorElementExpr
9696   };
9697 } // end anonymous namespace
9698 
9699 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
9700   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
9701   return VectorExprEvaluator(Info, Result).Visit(E);
9702 }
9703 
9704 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
9705   const VectorType *VTy = E->getType()->castAs<VectorType>();
9706   unsigned NElts = VTy->getNumElements();
9707 
9708   const Expr *SE = E->getSubExpr();
9709   QualType SETy = SE->getType();
9710 
9711   switch (E->getCastKind()) {
9712   case CK_VectorSplat: {
9713     APValue Val = APValue();
9714     if (SETy->isIntegerType()) {
9715       APSInt IntResult;
9716       if (!EvaluateInteger(SE, IntResult, Info))
9717         return false;
9718       Val = APValue(std::move(IntResult));
9719     } else if (SETy->isRealFloatingType()) {
9720       APFloat FloatResult(0.0);
9721       if (!EvaluateFloat(SE, FloatResult, Info))
9722         return false;
9723       Val = APValue(std::move(FloatResult));
9724     } else {
9725       return Error(E);
9726     }
9727 
9728     // Splat and create vector APValue.
9729     SmallVector<APValue, 4> Elts(NElts, Val);
9730     return Success(Elts, E);
9731   }
9732   case CK_BitCast: {
9733     // Evaluate the operand into an APInt we can extract from.
9734     llvm::APInt SValInt;
9735     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
9736       return false;
9737     // Extract the elements
9738     QualType EltTy = VTy->getElementType();
9739     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
9740     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
9741     SmallVector<APValue, 4> Elts;
9742     if (EltTy->isRealFloatingType()) {
9743       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
9744       unsigned FloatEltSize = EltSize;
9745       if (&Sem == &APFloat::x87DoubleExtended())
9746         FloatEltSize = 80;
9747       for (unsigned i = 0; i < NElts; i++) {
9748         llvm::APInt Elt;
9749         if (BigEndian)
9750           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
9751         else
9752           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
9753         Elts.push_back(APValue(APFloat(Sem, Elt)));
9754       }
9755     } else if (EltTy->isIntegerType()) {
9756       for (unsigned i = 0; i < NElts; i++) {
9757         llvm::APInt Elt;
9758         if (BigEndian)
9759           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
9760         else
9761           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
9762         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
9763       }
9764     } else {
9765       return Error(E);
9766     }
9767     return Success(Elts, E);
9768   }
9769   default:
9770     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9771   }
9772 }
9773 
9774 bool
9775 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9776   const VectorType *VT = E->getType()->castAs<VectorType>();
9777   unsigned NumInits = E->getNumInits();
9778   unsigned NumElements = VT->getNumElements();
9779 
9780   QualType EltTy = VT->getElementType();
9781   SmallVector<APValue, 4> Elements;
9782 
9783   // The number of initializers can be less than the number of
9784   // vector elements. For OpenCL, this can be due to nested vector
9785   // initialization. For GCC compatibility, missing trailing elements
9786   // should be initialized with zeroes.
9787   unsigned CountInits = 0, CountElts = 0;
9788   while (CountElts < NumElements) {
9789     // Handle nested vector initialization.
9790     if (CountInits < NumInits
9791         && E->getInit(CountInits)->getType()->isVectorType()) {
9792       APValue v;
9793       if (!EvaluateVector(E->getInit(CountInits), v, Info))
9794         return Error(E);
9795       unsigned vlen = v.getVectorLength();
9796       for (unsigned j = 0; j < vlen; j++)
9797         Elements.push_back(v.getVectorElt(j));
9798       CountElts += vlen;
9799     } else if (EltTy->isIntegerType()) {
9800       llvm::APSInt sInt(32);
9801       if (CountInits < NumInits) {
9802         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
9803           return false;
9804       } else // trailing integer zero.
9805         sInt = Info.Ctx.MakeIntValue(0, EltTy);
9806       Elements.push_back(APValue(sInt));
9807       CountElts++;
9808     } else {
9809       llvm::APFloat f(0.0);
9810       if (CountInits < NumInits) {
9811         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
9812           return false;
9813       } else // trailing float zero.
9814         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
9815       Elements.push_back(APValue(f));
9816       CountElts++;
9817     }
9818     CountInits++;
9819   }
9820   return Success(Elements, E);
9821 }
9822 
9823 bool
9824 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
9825   const auto *VT = E->getType()->castAs<VectorType>();
9826   QualType EltTy = VT->getElementType();
9827   APValue ZeroElement;
9828   if (EltTy->isIntegerType())
9829     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
9830   else
9831     ZeroElement =
9832         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
9833 
9834   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
9835   return Success(Elements, E);
9836 }
9837 
9838 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9839   VisitIgnoredValue(E->getSubExpr());
9840   return ZeroInitialization(E);
9841 }
9842 
9843 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9844   BinaryOperatorKind Op = E->getOpcode();
9845   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
9846          "Operation not supported on vector types");
9847 
9848   if (Op == BO_Comma)
9849     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9850 
9851   Expr *LHS = E->getLHS();
9852   Expr *RHS = E->getRHS();
9853 
9854   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
9855          "Must both be vector types");
9856   // Checking JUST the types are the same would be fine, except shifts don't
9857   // need to have their types be the same (since you always shift by an int).
9858   assert(LHS->getType()->getAs<VectorType>()->getNumElements() ==
9859              E->getType()->getAs<VectorType>()->getNumElements() &&
9860          RHS->getType()->getAs<VectorType>()->getNumElements() ==
9861              E->getType()->getAs<VectorType>()->getNumElements() &&
9862          "All operands must be the same size.");
9863 
9864   APValue LHSValue;
9865   APValue RHSValue;
9866   bool LHSOK = Evaluate(LHSValue, Info, LHS);
9867   if (!LHSOK && !Info.noteFailure())
9868     return false;
9869   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
9870     return false;
9871 
9872   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
9873     return false;
9874 
9875   return Success(LHSValue, E);
9876 }
9877 
9878 //===----------------------------------------------------------------------===//
9879 // Array Evaluation
9880 //===----------------------------------------------------------------------===//
9881 
9882 namespace {
9883   class ArrayExprEvaluator
9884   : public ExprEvaluatorBase<ArrayExprEvaluator> {
9885     const LValue &This;
9886     APValue &Result;
9887   public:
9888 
9889     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
9890       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
9891 
9892     bool Success(const APValue &V, const Expr *E) {
9893       assert(V.isArray() && "expected array");
9894       Result = V;
9895       return true;
9896     }
9897 
9898     bool ZeroInitialization(const Expr *E) {
9899       const ConstantArrayType *CAT =
9900           Info.Ctx.getAsConstantArrayType(E->getType());
9901       if (!CAT)
9902         return Error(E);
9903 
9904       Result = APValue(APValue::UninitArray(), 0,
9905                        CAT->getSize().getZExtValue());
9906       if (!Result.hasArrayFiller()) return true;
9907 
9908       // Zero-initialize all elements.
9909       LValue Subobject = This;
9910       Subobject.addArray(Info, E, CAT);
9911       ImplicitValueInitExpr VIE(CAT->getElementType());
9912       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
9913     }
9914 
9915     bool VisitCallExpr(const CallExpr *E) {
9916       return handleCallExpr(E, Result, &This);
9917     }
9918     bool VisitInitListExpr(const InitListExpr *E,
9919                            QualType AllocType = QualType());
9920     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
9921     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
9922     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
9923                                const LValue &Subobject,
9924                                APValue *Value, QualType Type);
9925     bool VisitStringLiteral(const StringLiteral *E,
9926                             QualType AllocType = QualType()) {
9927       expandStringLiteral(Info, E, Result, AllocType);
9928       return true;
9929     }
9930   };
9931 } // end anonymous namespace
9932 
9933 static bool EvaluateArray(const Expr *E, const LValue &This,
9934                           APValue &Result, EvalInfo &Info) {
9935   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
9936   return ArrayExprEvaluator(Info, This, Result).Visit(E);
9937 }
9938 
9939 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9940                                      APValue &Result, const InitListExpr *ILE,
9941                                      QualType AllocType) {
9942   assert(ILE->isRValue() && ILE->getType()->isArrayType() &&
9943          "not an array rvalue");
9944   return ArrayExprEvaluator(Info, This, Result)
9945       .VisitInitListExpr(ILE, AllocType);
9946 }
9947 
9948 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9949                                           APValue &Result,
9950                                           const CXXConstructExpr *CCE,
9951                                           QualType AllocType) {
9952   assert(CCE->isRValue() && CCE->getType()->isArrayType() &&
9953          "not an array rvalue");
9954   return ArrayExprEvaluator(Info, This, Result)
9955       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
9956 }
9957 
9958 // Return true iff the given array filler may depend on the element index.
9959 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
9960   // For now, just allow non-class value-initialization and initialization
9961   // lists comprised of them.
9962   if (isa<ImplicitValueInitExpr>(FillerExpr))
9963     return false;
9964   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
9965     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
9966       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
9967         return true;
9968     }
9969     return false;
9970   }
9971   return true;
9972 }
9973 
9974 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
9975                                            QualType AllocType) {
9976   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
9977       AllocType.isNull() ? E->getType() : AllocType);
9978   if (!CAT)
9979     return Error(E);
9980 
9981   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
9982   // an appropriately-typed string literal enclosed in braces.
9983   if (E->isStringLiteralInit()) {
9984     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
9985     // FIXME: Support ObjCEncodeExpr here once we support it in
9986     // ArrayExprEvaluator generally.
9987     if (!SL)
9988       return Error(E);
9989     return VisitStringLiteral(SL, AllocType);
9990   }
9991 
9992   bool Success = true;
9993 
9994   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
9995          "zero-initialized array shouldn't have any initialized elts");
9996   APValue Filler;
9997   if (Result.isArray() && Result.hasArrayFiller())
9998     Filler = Result.getArrayFiller();
9999 
10000   unsigned NumEltsToInit = E->getNumInits();
10001   unsigned NumElts = CAT->getSize().getZExtValue();
10002   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
10003 
10004   // If the initializer might depend on the array index, run it for each
10005   // array element.
10006   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
10007     NumEltsToInit = NumElts;
10008 
10009   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10010                           << NumEltsToInit << ".\n");
10011 
10012   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10013 
10014   // If the array was previously zero-initialized, preserve the
10015   // zero-initialized values.
10016   if (Filler.hasValue()) {
10017     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10018       Result.getArrayInitializedElt(I) = Filler;
10019     if (Result.hasArrayFiller())
10020       Result.getArrayFiller() = Filler;
10021   }
10022 
10023   LValue Subobject = This;
10024   Subobject.addArray(Info, E, CAT);
10025   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10026     const Expr *Init =
10027         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
10028     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10029                          Info, Subobject, Init) ||
10030         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10031                                      CAT->getElementType(), 1)) {
10032       if (!Info.noteFailure())
10033         return false;
10034       Success = false;
10035     }
10036   }
10037 
10038   if (!Result.hasArrayFiller())
10039     return Success;
10040 
10041   // If we get here, we have a trivial filler, which we can just evaluate
10042   // once and splat over the rest of the array elements.
10043   assert(FillerExpr && "no array filler for incomplete init list");
10044   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10045                          FillerExpr) && Success;
10046 }
10047 
10048 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10049   LValue CommonLV;
10050   if (E->getCommonExpr() &&
10051       !Evaluate(Info.CurrentCall->createTemporary(
10052                     E->getCommonExpr(),
10053                     getStorageType(Info.Ctx, E->getCommonExpr()), false,
10054                     CommonLV),
10055                 Info, E->getCommonExpr()->getSourceExpr()))
10056     return false;
10057 
10058   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10059 
10060   uint64_t Elements = CAT->getSize().getZExtValue();
10061   Result = APValue(APValue::UninitArray(), Elements, Elements);
10062 
10063   LValue Subobject = This;
10064   Subobject.addArray(Info, E, CAT);
10065 
10066   bool Success = true;
10067   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10068     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10069                          Info, Subobject, E->getSubExpr()) ||
10070         !HandleLValueArrayAdjustment(Info, E, Subobject,
10071                                      CAT->getElementType(), 1)) {
10072       if (!Info.noteFailure())
10073         return false;
10074       Success = false;
10075     }
10076   }
10077 
10078   return Success;
10079 }
10080 
10081 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10082   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10083 }
10084 
10085 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10086                                                const LValue &Subobject,
10087                                                APValue *Value,
10088                                                QualType Type) {
10089   bool HadZeroInit = Value->hasValue();
10090 
10091   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10092     unsigned N = CAT->getSize().getZExtValue();
10093 
10094     // Preserve the array filler if we had prior zero-initialization.
10095     APValue Filler =
10096       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10097                                              : APValue();
10098 
10099     *Value = APValue(APValue::UninitArray(), N, N);
10100 
10101     if (HadZeroInit)
10102       for (unsigned I = 0; I != N; ++I)
10103         Value->getArrayInitializedElt(I) = Filler;
10104 
10105     // Initialize the elements.
10106     LValue ArrayElt = Subobject;
10107     ArrayElt.addArray(Info, E, CAT);
10108     for (unsigned I = 0; I != N; ++I)
10109       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
10110                                  CAT->getElementType()) ||
10111           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10112                                        CAT->getElementType(), 1))
10113         return false;
10114 
10115     return true;
10116   }
10117 
10118   if (!Type->isRecordType())
10119     return Error(E);
10120 
10121   return RecordExprEvaluator(Info, Subobject, *Value)
10122              .VisitCXXConstructExpr(E, Type);
10123 }
10124 
10125 //===----------------------------------------------------------------------===//
10126 // Integer Evaluation
10127 //
10128 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10129 // types and back in constant folding. Integer values are thus represented
10130 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10131 //===----------------------------------------------------------------------===//
10132 
10133 namespace {
10134 class IntExprEvaluator
10135         : public ExprEvaluatorBase<IntExprEvaluator> {
10136   APValue &Result;
10137 public:
10138   IntExprEvaluator(EvalInfo &info, APValue &result)
10139       : ExprEvaluatorBaseTy(info), Result(result) {}
10140 
10141   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10142     assert(E->getType()->isIntegralOrEnumerationType() &&
10143            "Invalid evaluation result.");
10144     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10145            "Invalid evaluation result.");
10146     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10147            "Invalid evaluation result.");
10148     Result = APValue(SI);
10149     return true;
10150   }
10151   bool Success(const llvm::APSInt &SI, const Expr *E) {
10152     return Success(SI, E, Result);
10153   }
10154 
10155   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10156     assert(E->getType()->isIntegralOrEnumerationType() &&
10157            "Invalid evaluation result.");
10158     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10159            "Invalid evaluation result.");
10160     Result = APValue(APSInt(I));
10161     Result.getInt().setIsUnsigned(
10162                             E->getType()->isUnsignedIntegerOrEnumerationType());
10163     return true;
10164   }
10165   bool Success(const llvm::APInt &I, const Expr *E) {
10166     return Success(I, E, Result);
10167   }
10168 
10169   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10170     assert(E->getType()->isIntegralOrEnumerationType() &&
10171            "Invalid evaluation result.");
10172     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10173     return true;
10174   }
10175   bool Success(uint64_t Value, const Expr *E) {
10176     return Success(Value, E, Result);
10177   }
10178 
10179   bool Success(CharUnits Size, const Expr *E) {
10180     return Success(Size.getQuantity(), E);
10181   }
10182 
10183   bool Success(const APValue &V, const Expr *E) {
10184     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10185       Result = V;
10186       return true;
10187     }
10188     return Success(V.getInt(), E);
10189   }
10190 
10191   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10192 
10193   //===--------------------------------------------------------------------===//
10194   //                            Visitor Methods
10195   //===--------------------------------------------------------------------===//
10196 
10197   bool VisitIntegerLiteral(const IntegerLiteral *E) {
10198     return Success(E->getValue(), E);
10199   }
10200   bool VisitCharacterLiteral(const CharacterLiteral *E) {
10201     return Success(E->getValue(), E);
10202   }
10203 
10204   bool CheckReferencedDecl(const Expr *E, const Decl *D);
10205   bool VisitDeclRefExpr(const DeclRefExpr *E) {
10206     if (CheckReferencedDecl(E, E->getDecl()))
10207       return true;
10208 
10209     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
10210   }
10211   bool VisitMemberExpr(const MemberExpr *E) {
10212     if (CheckReferencedDecl(E, E->getMemberDecl())) {
10213       VisitIgnoredBaseExpression(E->getBase());
10214       return true;
10215     }
10216 
10217     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
10218   }
10219 
10220   bool VisitCallExpr(const CallExpr *E);
10221   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10222   bool VisitBinaryOperator(const BinaryOperator *E);
10223   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
10224   bool VisitUnaryOperator(const UnaryOperator *E);
10225 
10226   bool VisitCastExpr(const CastExpr* E);
10227   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
10228 
10229   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
10230     return Success(E->getValue(), E);
10231   }
10232 
10233   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
10234     return Success(E->getValue(), E);
10235   }
10236 
10237   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
10238     if (Info.ArrayInitIndex == uint64_t(-1)) {
10239       // We were asked to evaluate this subexpression independent of the
10240       // enclosing ArrayInitLoopExpr. We can't do that.
10241       Info.FFDiag(E);
10242       return false;
10243     }
10244     return Success(Info.ArrayInitIndex, E);
10245   }
10246 
10247   // Note, GNU defines __null as an integer, not a pointer.
10248   bool VisitGNUNullExpr(const GNUNullExpr *E) {
10249     return ZeroInitialization(E);
10250   }
10251 
10252   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
10253     return Success(E->getValue(), E);
10254   }
10255 
10256   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
10257     return Success(E->getValue(), E);
10258   }
10259 
10260   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
10261     return Success(E->getValue(), E);
10262   }
10263 
10264   bool VisitUnaryReal(const UnaryOperator *E);
10265   bool VisitUnaryImag(const UnaryOperator *E);
10266 
10267   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
10268   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
10269   bool VisitSourceLocExpr(const SourceLocExpr *E);
10270   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
10271   bool VisitRequiresExpr(const RequiresExpr *E);
10272   // FIXME: Missing: array subscript of vector, member of vector
10273 };
10274 
10275 class FixedPointExprEvaluator
10276     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
10277   APValue &Result;
10278 
10279  public:
10280   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
10281       : ExprEvaluatorBaseTy(info), Result(result) {}
10282 
10283   bool Success(const llvm::APInt &I, const Expr *E) {
10284     return Success(
10285         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10286   }
10287 
10288   bool Success(uint64_t Value, const Expr *E) {
10289     return Success(
10290         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10291   }
10292 
10293   bool Success(const APValue &V, const Expr *E) {
10294     return Success(V.getFixedPoint(), E);
10295   }
10296 
10297   bool Success(const APFixedPoint &V, const Expr *E) {
10298     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
10299     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10300            "Invalid evaluation result.");
10301     Result = APValue(V);
10302     return true;
10303   }
10304 
10305   //===--------------------------------------------------------------------===//
10306   //                            Visitor Methods
10307   //===--------------------------------------------------------------------===//
10308 
10309   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
10310     return Success(E->getValue(), E);
10311   }
10312 
10313   bool VisitCastExpr(const CastExpr *E);
10314   bool VisitUnaryOperator(const UnaryOperator *E);
10315   bool VisitBinaryOperator(const BinaryOperator *E);
10316 };
10317 } // end anonymous namespace
10318 
10319 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
10320 /// produce either the integer value or a pointer.
10321 ///
10322 /// GCC has a heinous extension which folds casts between pointer types and
10323 /// pointer-sized integral types. We support this by allowing the evaluation of
10324 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
10325 /// Some simple arithmetic on such values is supported (they are treated much
10326 /// like char*).
10327 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
10328                                     EvalInfo &Info) {
10329   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
10330   return IntExprEvaluator(Info, Result).Visit(E);
10331 }
10332 
10333 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
10334   APValue Val;
10335   if (!EvaluateIntegerOrLValue(E, Val, Info))
10336     return false;
10337   if (!Val.isInt()) {
10338     // FIXME: It would be better to produce the diagnostic for casting
10339     //        a pointer to an integer.
10340     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10341     return false;
10342   }
10343   Result = Val.getInt();
10344   return true;
10345 }
10346 
10347 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
10348   APValue Evaluated = E->EvaluateInContext(
10349       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10350   return Success(Evaluated, E);
10351 }
10352 
10353 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
10354                                EvalInfo &Info) {
10355   if (E->getType()->isFixedPointType()) {
10356     APValue Val;
10357     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
10358       return false;
10359     if (!Val.isFixedPoint())
10360       return false;
10361 
10362     Result = Val.getFixedPoint();
10363     return true;
10364   }
10365   return false;
10366 }
10367 
10368 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
10369                                         EvalInfo &Info) {
10370   if (E->getType()->isIntegerType()) {
10371     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
10372     APSInt Val;
10373     if (!EvaluateInteger(E, Val, Info))
10374       return false;
10375     Result = APFixedPoint(Val, FXSema);
10376     return true;
10377   } else if (E->getType()->isFixedPointType()) {
10378     return EvaluateFixedPoint(E, Result, Info);
10379   }
10380   return false;
10381 }
10382 
10383 /// Check whether the given declaration can be directly converted to an integral
10384 /// rvalue. If not, no diagnostic is produced; there are other things we can
10385 /// try.
10386 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
10387   // Enums are integer constant exprs.
10388   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
10389     // Check for signedness/width mismatches between E type and ECD value.
10390     bool SameSign = (ECD->getInitVal().isSigned()
10391                      == E->getType()->isSignedIntegerOrEnumerationType());
10392     bool SameWidth = (ECD->getInitVal().getBitWidth()
10393                       == Info.Ctx.getIntWidth(E->getType()));
10394     if (SameSign && SameWidth)
10395       return Success(ECD->getInitVal(), E);
10396     else {
10397       // Get rid of mismatch (otherwise Success assertions will fail)
10398       // by computing a new value matching the type of E.
10399       llvm::APSInt Val = ECD->getInitVal();
10400       if (!SameSign)
10401         Val.setIsSigned(!ECD->getInitVal().isSigned());
10402       if (!SameWidth)
10403         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
10404       return Success(Val, E);
10405     }
10406   }
10407   return false;
10408 }
10409 
10410 /// Values returned by __builtin_classify_type, chosen to match the values
10411 /// produced by GCC's builtin.
10412 enum class GCCTypeClass {
10413   None = -1,
10414   Void = 0,
10415   Integer = 1,
10416   // GCC reserves 2 for character types, but instead classifies them as
10417   // integers.
10418   Enum = 3,
10419   Bool = 4,
10420   Pointer = 5,
10421   // GCC reserves 6 for references, but appears to never use it (because
10422   // expressions never have reference type, presumably).
10423   PointerToDataMember = 7,
10424   RealFloat = 8,
10425   Complex = 9,
10426   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
10427   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
10428   // GCC claims to reserve 11 for pointers to member functions, but *actually*
10429   // uses 12 for that purpose, same as for a class or struct. Maybe it
10430   // internally implements a pointer to member as a struct?  Who knows.
10431   PointerToMemberFunction = 12, // Not a bug, see above.
10432   ClassOrStruct = 12,
10433   Union = 13,
10434   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
10435   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
10436   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
10437   // literals.
10438 };
10439 
10440 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10441 /// as GCC.
10442 static GCCTypeClass
10443 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
10444   assert(!T->isDependentType() && "unexpected dependent type");
10445 
10446   QualType CanTy = T.getCanonicalType();
10447   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
10448 
10449   switch (CanTy->getTypeClass()) {
10450 #define TYPE(ID, BASE)
10451 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
10452 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
10453 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
10454 #include "clang/AST/TypeNodes.inc"
10455   case Type::Auto:
10456   case Type::DeducedTemplateSpecialization:
10457       llvm_unreachable("unexpected non-canonical or dependent type");
10458 
10459   case Type::Builtin:
10460     switch (BT->getKind()) {
10461 #define BUILTIN_TYPE(ID, SINGLETON_ID)
10462 #define SIGNED_TYPE(ID, SINGLETON_ID) \
10463     case BuiltinType::ID: return GCCTypeClass::Integer;
10464 #define FLOATING_TYPE(ID, SINGLETON_ID) \
10465     case BuiltinType::ID: return GCCTypeClass::RealFloat;
10466 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
10467     case BuiltinType::ID: break;
10468 #include "clang/AST/BuiltinTypes.def"
10469     case BuiltinType::Void:
10470       return GCCTypeClass::Void;
10471 
10472     case BuiltinType::Bool:
10473       return GCCTypeClass::Bool;
10474 
10475     case BuiltinType::Char_U:
10476     case BuiltinType::UChar:
10477     case BuiltinType::WChar_U:
10478     case BuiltinType::Char8:
10479     case BuiltinType::Char16:
10480     case BuiltinType::Char32:
10481     case BuiltinType::UShort:
10482     case BuiltinType::UInt:
10483     case BuiltinType::ULong:
10484     case BuiltinType::ULongLong:
10485     case BuiltinType::UInt128:
10486       return GCCTypeClass::Integer;
10487 
10488     case BuiltinType::UShortAccum:
10489     case BuiltinType::UAccum:
10490     case BuiltinType::ULongAccum:
10491     case BuiltinType::UShortFract:
10492     case BuiltinType::UFract:
10493     case BuiltinType::ULongFract:
10494     case BuiltinType::SatUShortAccum:
10495     case BuiltinType::SatUAccum:
10496     case BuiltinType::SatULongAccum:
10497     case BuiltinType::SatUShortFract:
10498     case BuiltinType::SatUFract:
10499     case BuiltinType::SatULongFract:
10500       return GCCTypeClass::None;
10501 
10502     case BuiltinType::NullPtr:
10503 
10504     case BuiltinType::ObjCId:
10505     case BuiltinType::ObjCClass:
10506     case BuiltinType::ObjCSel:
10507 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
10508     case BuiltinType::Id:
10509 #include "clang/Basic/OpenCLImageTypes.def"
10510 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
10511     case BuiltinType::Id:
10512 #include "clang/Basic/OpenCLExtensionTypes.def"
10513     case BuiltinType::OCLSampler:
10514     case BuiltinType::OCLEvent:
10515     case BuiltinType::OCLClkEvent:
10516     case BuiltinType::OCLQueue:
10517     case BuiltinType::OCLReserveID:
10518 #define SVE_TYPE(Name, Id, SingletonId) \
10519     case BuiltinType::Id:
10520 #include "clang/Basic/AArch64SVEACLETypes.def"
10521       return GCCTypeClass::None;
10522 
10523     case BuiltinType::Dependent:
10524       llvm_unreachable("unexpected dependent type");
10525     };
10526     llvm_unreachable("unexpected placeholder type");
10527 
10528   case Type::Enum:
10529     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
10530 
10531   case Type::Pointer:
10532   case Type::ConstantArray:
10533   case Type::VariableArray:
10534   case Type::IncompleteArray:
10535   case Type::FunctionNoProto:
10536   case Type::FunctionProto:
10537     return GCCTypeClass::Pointer;
10538 
10539   case Type::MemberPointer:
10540     return CanTy->isMemberDataPointerType()
10541                ? GCCTypeClass::PointerToDataMember
10542                : GCCTypeClass::PointerToMemberFunction;
10543 
10544   case Type::Complex:
10545     return GCCTypeClass::Complex;
10546 
10547   case Type::Record:
10548     return CanTy->isUnionType() ? GCCTypeClass::Union
10549                                 : GCCTypeClass::ClassOrStruct;
10550 
10551   case Type::Atomic:
10552     // GCC classifies _Atomic T the same as T.
10553     return EvaluateBuiltinClassifyType(
10554         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
10555 
10556   case Type::BlockPointer:
10557   case Type::Vector:
10558   case Type::ExtVector:
10559   case Type::ConstantMatrix:
10560   case Type::ObjCObject:
10561   case Type::ObjCInterface:
10562   case Type::ObjCObjectPointer:
10563   case Type::Pipe:
10564   case Type::ExtInt:
10565     // GCC classifies vectors as None. We follow its lead and classify all
10566     // other types that don't fit into the regular classification the same way.
10567     return GCCTypeClass::None;
10568 
10569   case Type::LValueReference:
10570   case Type::RValueReference:
10571     llvm_unreachable("invalid type for expression");
10572   }
10573 
10574   llvm_unreachable("unexpected type class");
10575 }
10576 
10577 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10578 /// as GCC.
10579 static GCCTypeClass
10580 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
10581   // If no argument was supplied, default to None. This isn't
10582   // ideal, however it is what gcc does.
10583   if (E->getNumArgs() == 0)
10584     return GCCTypeClass::None;
10585 
10586   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
10587   // being an ICE, but still folds it to a constant using the type of the first
10588   // argument.
10589   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
10590 }
10591 
10592 /// EvaluateBuiltinConstantPForLValue - Determine the result of
10593 /// __builtin_constant_p when applied to the given pointer.
10594 ///
10595 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
10596 /// or it points to the first character of a string literal.
10597 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
10598   APValue::LValueBase Base = LV.getLValueBase();
10599   if (Base.isNull()) {
10600     // A null base is acceptable.
10601     return true;
10602   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
10603     if (!isa<StringLiteral>(E))
10604       return false;
10605     return LV.getLValueOffset().isZero();
10606   } else if (Base.is<TypeInfoLValue>()) {
10607     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
10608     // evaluate to true.
10609     return true;
10610   } else {
10611     // Any other base is not constant enough for GCC.
10612     return false;
10613   }
10614 }
10615 
10616 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
10617 /// GCC as we can manage.
10618 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
10619   // This evaluation is not permitted to have side-effects, so evaluate it in
10620   // a speculative evaluation context.
10621   SpeculativeEvaluationRAII SpeculativeEval(Info);
10622 
10623   // Constant-folding is always enabled for the operand of __builtin_constant_p
10624   // (even when the enclosing evaluation context otherwise requires a strict
10625   // language-specific constant expression).
10626   FoldConstant Fold(Info, true);
10627 
10628   QualType ArgType = Arg->getType();
10629 
10630   // __builtin_constant_p always has one operand. The rules which gcc follows
10631   // are not precisely documented, but are as follows:
10632   //
10633   //  - If the operand is of integral, floating, complex or enumeration type,
10634   //    and can be folded to a known value of that type, it returns 1.
10635   //  - If the operand can be folded to a pointer to the first character
10636   //    of a string literal (or such a pointer cast to an integral type)
10637   //    or to a null pointer or an integer cast to a pointer, it returns 1.
10638   //
10639   // Otherwise, it returns 0.
10640   //
10641   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
10642   // its support for this did not work prior to GCC 9 and is not yet well
10643   // understood.
10644   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
10645       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
10646       ArgType->isNullPtrType()) {
10647     APValue V;
10648     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
10649       Fold.keepDiagnostics();
10650       return false;
10651     }
10652 
10653     // For a pointer (possibly cast to integer), there are special rules.
10654     if (V.getKind() == APValue::LValue)
10655       return EvaluateBuiltinConstantPForLValue(V);
10656 
10657     // Otherwise, any constant value is good enough.
10658     return V.hasValue();
10659   }
10660 
10661   // Anything else isn't considered to be sufficiently constant.
10662   return false;
10663 }
10664 
10665 /// Retrieves the "underlying object type" of the given expression,
10666 /// as used by __builtin_object_size.
10667 static QualType getObjectType(APValue::LValueBase B) {
10668   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
10669     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
10670       return VD->getType();
10671   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
10672     if (isa<CompoundLiteralExpr>(E))
10673       return E->getType();
10674   } else if (B.is<TypeInfoLValue>()) {
10675     return B.getTypeInfoType();
10676   } else if (B.is<DynamicAllocLValue>()) {
10677     return B.getDynamicAllocType();
10678   }
10679 
10680   return QualType();
10681 }
10682 
10683 /// A more selective version of E->IgnoreParenCasts for
10684 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
10685 /// to change the type of E.
10686 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
10687 ///
10688 /// Always returns an RValue with a pointer representation.
10689 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
10690   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
10691 
10692   auto *NoParens = E->IgnoreParens();
10693   auto *Cast = dyn_cast<CastExpr>(NoParens);
10694   if (Cast == nullptr)
10695     return NoParens;
10696 
10697   // We only conservatively allow a few kinds of casts, because this code is
10698   // inherently a simple solution that seeks to support the common case.
10699   auto CastKind = Cast->getCastKind();
10700   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
10701       CastKind != CK_AddressSpaceConversion)
10702     return NoParens;
10703 
10704   auto *SubExpr = Cast->getSubExpr();
10705   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
10706     return NoParens;
10707   return ignorePointerCastsAndParens(SubExpr);
10708 }
10709 
10710 /// Checks to see if the given LValue's Designator is at the end of the LValue's
10711 /// record layout. e.g.
10712 ///   struct { struct { int a, b; } fst, snd; } obj;
10713 ///   obj.fst   // no
10714 ///   obj.snd   // yes
10715 ///   obj.fst.a // no
10716 ///   obj.fst.b // no
10717 ///   obj.snd.a // no
10718 ///   obj.snd.b // yes
10719 ///
10720 /// Please note: this function is specialized for how __builtin_object_size
10721 /// views "objects".
10722 ///
10723 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
10724 /// correct result, it will always return true.
10725 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
10726   assert(!LVal.Designator.Invalid);
10727 
10728   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
10729     const RecordDecl *Parent = FD->getParent();
10730     Invalid = Parent->isInvalidDecl();
10731     if (Invalid || Parent->isUnion())
10732       return true;
10733     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
10734     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
10735   };
10736 
10737   auto &Base = LVal.getLValueBase();
10738   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
10739     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
10740       bool Invalid;
10741       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10742         return Invalid;
10743     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
10744       for (auto *FD : IFD->chain()) {
10745         bool Invalid;
10746         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
10747           return Invalid;
10748       }
10749     }
10750   }
10751 
10752   unsigned I = 0;
10753   QualType BaseType = getType(Base);
10754   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
10755     // If we don't know the array bound, conservatively assume we're looking at
10756     // the final array element.
10757     ++I;
10758     if (BaseType->isIncompleteArrayType())
10759       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
10760     else
10761       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
10762   }
10763 
10764   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
10765     const auto &Entry = LVal.Designator.Entries[I];
10766     if (BaseType->isArrayType()) {
10767       // Because __builtin_object_size treats arrays as objects, we can ignore
10768       // the index iff this is the last array in the Designator.
10769       if (I + 1 == E)
10770         return true;
10771       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
10772       uint64_t Index = Entry.getAsArrayIndex();
10773       if (Index + 1 != CAT->getSize())
10774         return false;
10775       BaseType = CAT->getElementType();
10776     } else if (BaseType->isAnyComplexType()) {
10777       const auto *CT = BaseType->castAs<ComplexType>();
10778       uint64_t Index = Entry.getAsArrayIndex();
10779       if (Index != 1)
10780         return false;
10781       BaseType = CT->getElementType();
10782     } else if (auto *FD = getAsField(Entry)) {
10783       bool Invalid;
10784       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10785         return Invalid;
10786       BaseType = FD->getType();
10787     } else {
10788       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
10789       return false;
10790     }
10791   }
10792   return true;
10793 }
10794 
10795 /// Tests to see if the LValue has a user-specified designator (that isn't
10796 /// necessarily valid). Note that this always returns 'true' if the LValue has
10797 /// an unsized array as its first designator entry, because there's currently no
10798 /// way to tell if the user typed *foo or foo[0].
10799 static bool refersToCompleteObject(const LValue &LVal) {
10800   if (LVal.Designator.Invalid)
10801     return false;
10802 
10803   if (!LVal.Designator.Entries.empty())
10804     return LVal.Designator.isMostDerivedAnUnsizedArray();
10805 
10806   if (!LVal.InvalidBase)
10807     return true;
10808 
10809   // If `E` is a MemberExpr, then the first part of the designator is hiding in
10810   // the LValueBase.
10811   const auto *E = LVal.Base.dyn_cast<const Expr *>();
10812   return !E || !isa<MemberExpr>(E);
10813 }
10814 
10815 /// Attempts to detect a user writing into a piece of memory that's impossible
10816 /// to figure out the size of by just using types.
10817 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
10818   const SubobjectDesignator &Designator = LVal.Designator;
10819   // Notes:
10820   // - Users can only write off of the end when we have an invalid base. Invalid
10821   //   bases imply we don't know where the memory came from.
10822   // - We used to be a bit more aggressive here; we'd only be conservative if
10823   //   the array at the end was flexible, or if it had 0 or 1 elements. This
10824   //   broke some common standard library extensions (PR30346), but was
10825   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
10826   //   with some sort of list. OTOH, it seems that GCC is always
10827   //   conservative with the last element in structs (if it's an array), so our
10828   //   current behavior is more compatible than an explicit list approach would
10829   //   be.
10830   return LVal.InvalidBase &&
10831          Designator.Entries.size() == Designator.MostDerivedPathLength &&
10832          Designator.MostDerivedIsArrayElement &&
10833          isDesignatorAtObjectEnd(Ctx, LVal);
10834 }
10835 
10836 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
10837 /// Fails if the conversion would cause loss of precision.
10838 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
10839                                             CharUnits &Result) {
10840   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
10841   if (Int.ugt(CharUnitsMax))
10842     return false;
10843   Result = CharUnits::fromQuantity(Int.getZExtValue());
10844   return true;
10845 }
10846 
10847 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
10848 /// determine how many bytes exist from the beginning of the object to either
10849 /// the end of the current subobject, or the end of the object itself, depending
10850 /// on what the LValue looks like + the value of Type.
10851 ///
10852 /// If this returns false, the value of Result is undefined.
10853 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
10854                                unsigned Type, const LValue &LVal,
10855                                CharUnits &EndOffset) {
10856   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
10857 
10858   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
10859     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
10860       return false;
10861     return HandleSizeof(Info, ExprLoc, Ty, Result);
10862   };
10863 
10864   // We want to evaluate the size of the entire object. This is a valid fallback
10865   // for when Type=1 and the designator is invalid, because we're asked for an
10866   // upper-bound.
10867   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
10868     // Type=3 wants a lower bound, so we can't fall back to this.
10869     if (Type == 3 && !DetermineForCompleteObject)
10870       return false;
10871 
10872     llvm::APInt APEndOffset;
10873     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10874         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10875       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10876 
10877     if (LVal.InvalidBase)
10878       return false;
10879 
10880     QualType BaseTy = getObjectType(LVal.getLValueBase());
10881     return CheckedHandleSizeof(BaseTy, EndOffset);
10882   }
10883 
10884   // We want to evaluate the size of a subobject.
10885   const SubobjectDesignator &Designator = LVal.Designator;
10886 
10887   // The following is a moderately common idiom in C:
10888   //
10889   // struct Foo { int a; char c[1]; };
10890   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
10891   // strcpy(&F->c[0], Bar);
10892   //
10893   // In order to not break too much legacy code, we need to support it.
10894   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
10895     // If we can resolve this to an alloc_size call, we can hand that back,
10896     // because we know for certain how many bytes there are to write to.
10897     llvm::APInt APEndOffset;
10898     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10899         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10900       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10901 
10902     // If we cannot determine the size of the initial allocation, then we can't
10903     // given an accurate upper-bound. However, we are still able to give
10904     // conservative lower-bounds for Type=3.
10905     if (Type == 1)
10906       return false;
10907   }
10908 
10909   CharUnits BytesPerElem;
10910   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
10911     return false;
10912 
10913   // According to the GCC documentation, we want the size of the subobject
10914   // denoted by the pointer. But that's not quite right -- what we actually
10915   // want is the size of the immediately-enclosing array, if there is one.
10916   int64_t ElemsRemaining;
10917   if (Designator.MostDerivedIsArrayElement &&
10918       Designator.Entries.size() == Designator.MostDerivedPathLength) {
10919     uint64_t ArraySize = Designator.getMostDerivedArraySize();
10920     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
10921     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
10922   } else {
10923     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
10924   }
10925 
10926   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
10927   return true;
10928 }
10929 
10930 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
10931 /// returns true and stores the result in @p Size.
10932 ///
10933 /// If @p WasError is non-null, this will report whether the failure to evaluate
10934 /// is to be treated as an Error in IntExprEvaluator.
10935 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
10936                                          EvalInfo &Info, uint64_t &Size) {
10937   // Determine the denoted object.
10938   LValue LVal;
10939   {
10940     // The operand of __builtin_object_size is never evaluated for side-effects.
10941     // If there are any, but we can determine the pointed-to object anyway, then
10942     // ignore the side-effects.
10943     SpeculativeEvaluationRAII SpeculativeEval(Info);
10944     IgnoreSideEffectsRAII Fold(Info);
10945 
10946     if (E->isGLValue()) {
10947       // It's possible for us to be given GLValues if we're called via
10948       // Expr::tryEvaluateObjectSize.
10949       APValue RVal;
10950       if (!EvaluateAsRValue(Info, E, RVal))
10951         return false;
10952       LVal.setFrom(Info.Ctx, RVal);
10953     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
10954                                 /*InvalidBaseOK=*/true))
10955       return false;
10956   }
10957 
10958   // If we point to before the start of the object, there are no accessible
10959   // bytes.
10960   if (LVal.getLValueOffset().isNegative()) {
10961     Size = 0;
10962     return true;
10963   }
10964 
10965   CharUnits EndOffset;
10966   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
10967     return false;
10968 
10969   // If we've fallen outside of the end offset, just pretend there's nothing to
10970   // write to/read from.
10971   if (EndOffset <= LVal.getLValueOffset())
10972     Size = 0;
10973   else
10974     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
10975   return true;
10976 }
10977 
10978 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
10979   if (unsigned BuiltinOp = E->getBuiltinCallee())
10980     return VisitBuiltinCallExpr(E, BuiltinOp);
10981 
10982   return ExprEvaluatorBaseTy::VisitCallExpr(E);
10983 }
10984 
10985 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
10986                                      APValue &Val, APSInt &Alignment) {
10987   QualType SrcTy = E->getArg(0)->getType();
10988   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
10989     return false;
10990   // Even though we are evaluating integer expressions we could get a pointer
10991   // argument for the __builtin_is_aligned() case.
10992   if (SrcTy->isPointerType()) {
10993     LValue Ptr;
10994     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
10995       return false;
10996     Ptr.moveInto(Val);
10997   } else if (!SrcTy->isIntegralOrEnumerationType()) {
10998     Info.FFDiag(E->getArg(0));
10999     return false;
11000   } else {
11001     APSInt SrcInt;
11002     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11003       return false;
11004     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11005            "Bit widths must be the same");
11006     Val = APValue(SrcInt);
11007   }
11008   assert(Val.hasValue());
11009   return true;
11010 }
11011 
11012 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11013                                             unsigned BuiltinOp) {
11014   switch (BuiltinOp) {
11015   default:
11016     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11017 
11018   case Builtin::BI__builtin_dynamic_object_size:
11019   case Builtin::BI__builtin_object_size: {
11020     // The type was checked when we built the expression.
11021     unsigned Type =
11022         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11023     assert(Type <= 3 && "unexpected type");
11024 
11025     uint64_t Size;
11026     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11027       return Success(Size, E);
11028 
11029     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11030       return Success((Type & 2) ? 0 : -1, E);
11031 
11032     // Expression had no side effects, but we couldn't statically determine the
11033     // size of the referenced object.
11034     switch (Info.EvalMode) {
11035     case EvalInfo::EM_ConstantExpression:
11036     case EvalInfo::EM_ConstantFold:
11037     case EvalInfo::EM_IgnoreSideEffects:
11038       // Leave it to IR generation.
11039       return Error(E);
11040     case EvalInfo::EM_ConstantExpressionUnevaluated:
11041       // Reduce it to a constant now.
11042       return Success((Type & 2) ? 0 : -1, E);
11043     }
11044 
11045     llvm_unreachable("unexpected EvalMode");
11046   }
11047 
11048   case Builtin::BI__builtin_os_log_format_buffer_size: {
11049     analyze_os_log::OSLogBufferLayout Layout;
11050     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11051     return Success(Layout.size().getQuantity(), E);
11052   }
11053 
11054   case Builtin::BI__builtin_is_aligned: {
11055     APValue Src;
11056     APSInt Alignment;
11057     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11058       return false;
11059     if (Src.isLValue()) {
11060       // If we evaluated a pointer, check the minimum known alignment.
11061       LValue Ptr;
11062       Ptr.setFrom(Info.Ctx, Src);
11063       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11064       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11065       // We can return true if the known alignment at the computed offset is
11066       // greater than the requested alignment.
11067       assert(PtrAlign.isPowerOfTwo());
11068       assert(Alignment.isPowerOf2());
11069       if (PtrAlign.getQuantity() >= Alignment)
11070         return Success(1, E);
11071       // If the alignment is not known to be sufficient, some cases could still
11072       // be aligned at run time. However, if the requested alignment is less or
11073       // equal to the base alignment and the offset is not aligned, we know that
11074       // the run-time value can never be aligned.
11075       if (BaseAlignment.getQuantity() >= Alignment &&
11076           PtrAlign.getQuantity() < Alignment)
11077         return Success(0, E);
11078       // Otherwise we can't infer whether the value is sufficiently aligned.
11079       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11080       //  in cases where we can't fully evaluate the pointer.
11081       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11082           << Alignment;
11083       return false;
11084     }
11085     assert(Src.isInt());
11086     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11087   }
11088   case Builtin::BI__builtin_align_up: {
11089     APValue Src;
11090     APSInt Alignment;
11091     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11092       return false;
11093     if (!Src.isInt())
11094       return Error(E);
11095     APSInt AlignedVal =
11096         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11097                Src.getInt().isUnsigned());
11098     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11099     return Success(AlignedVal, E);
11100   }
11101   case Builtin::BI__builtin_align_down: {
11102     APValue Src;
11103     APSInt Alignment;
11104     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11105       return false;
11106     if (!Src.isInt())
11107       return Error(E);
11108     APSInt AlignedVal =
11109         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11110     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11111     return Success(AlignedVal, E);
11112   }
11113 
11114   case Builtin::BI__builtin_bswap16:
11115   case Builtin::BI__builtin_bswap32:
11116   case Builtin::BI__builtin_bswap64: {
11117     APSInt Val;
11118     if (!EvaluateInteger(E->getArg(0), Val, Info))
11119       return false;
11120 
11121     return Success(Val.byteSwap(), E);
11122   }
11123 
11124   case Builtin::BI__builtin_classify_type:
11125     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11126 
11127   case Builtin::BI__builtin_clrsb:
11128   case Builtin::BI__builtin_clrsbl:
11129   case Builtin::BI__builtin_clrsbll: {
11130     APSInt Val;
11131     if (!EvaluateInteger(E->getArg(0), Val, Info))
11132       return false;
11133 
11134     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11135   }
11136 
11137   case Builtin::BI__builtin_clz:
11138   case Builtin::BI__builtin_clzl:
11139   case Builtin::BI__builtin_clzll:
11140   case Builtin::BI__builtin_clzs: {
11141     APSInt Val;
11142     if (!EvaluateInteger(E->getArg(0), Val, Info))
11143       return false;
11144     if (!Val)
11145       return Error(E);
11146 
11147     return Success(Val.countLeadingZeros(), E);
11148   }
11149 
11150   case Builtin::BI__builtin_constant_p: {
11151     const Expr *Arg = E->getArg(0);
11152     if (EvaluateBuiltinConstantP(Info, Arg))
11153       return Success(true, E);
11154     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11155       // Outside a constant context, eagerly evaluate to false in the presence
11156       // of side-effects in order to avoid -Wunsequenced false-positives in
11157       // a branch on __builtin_constant_p(expr).
11158       return Success(false, E);
11159     }
11160     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11161     return false;
11162   }
11163 
11164   case Builtin::BI__builtin_is_constant_evaluated: {
11165     const auto *Callee = Info.CurrentCall->getCallee();
11166     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
11167         (Info.CallStackDepth == 1 ||
11168          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
11169           Callee->getIdentifier() &&
11170           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
11171       // FIXME: Find a better way to avoid duplicated diagnostics.
11172       if (Info.EvalStatus.Diag)
11173         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
11174                                                : Info.CurrentCall->CallLoc,
11175                     diag::warn_is_constant_evaluated_always_true_constexpr)
11176             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
11177                                          : "std::is_constant_evaluated");
11178     }
11179 
11180     return Success(Info.InConstantContext, E);
11181   }
11182 
11183   case Builtin::BI__builtin_ctz:
11184   case Builtin::BI__builtin_ctzl:
11185   case Builtin::BI__builtin_ctzll:
11186   case Builtin::BI__builtin_ctzs: {
11187     APSInt Val;
11188     if (!EvaluateInteger(E->getArg(0), Val, Info))
11189       return false;
11190     if (!Val)
11191       return Error(E);
11192 
11193     return Success(Val.countTrailingZeros(), E);
11194   }
11195 
11196   case Builtin::BI__builtin_eh_return_data_regno: {
11197     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11198     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
11199     return Success(Operand, E);
11200   }
11201 
11202   case Builtin::BI__builtin_expect:
11203     return Visit(E->getArg(0));
11204 
11205   case Builtin::BI__builtin_ffs:
11206   case Builtin::BI__builtin_ffsl:
11207   case Builtin::BI__builtin_ffsll: {
11208     APSInt Val;
11209     if (!EvaluateInteger(E->getArg(0), Val, Info))
11210       return false;
11211 
11212     unsigned N = Val.countTrailingZeros();
11213     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
11214   }
11215 
11216   case Builtin::BI__builtin_fpclassify: {
11217     APFloat Val(0.0);
11218     if (!EvaluateFloat(E->getArg(5), Val, Info))
11219       return false;
11220     unsigned Arg;
11221     switch (Val.getCategory()) {
11222     case APFloat::fcNaN: Arg = 0; break;
11223     case APFloat::fcInfinity: Arg = 1; break;
11224     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
11225     case APFloat::fcZero: Arg = 4; break;
11226     }
11227     return Visit(E->getArg(Arg));
11228   }
11229 
11230   case Builtin::BI__builtin_isinf_sign: {
11231     APFloat Val(0.0);
11232     return EvaluateFloat(E->getArg(0), Val, Info) &&
11233            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
11234   }
11235 
11236   case Builtin::BI__builtin_isinf: {
11237     APFloat Val(0.0);
11238     return EvaluateFloat(E->getArg(0), Val, Info) &&
11239            Success(Val.isInfinity() ? 1 : 0, E);
11240   }
11241 
11242   case Builtin::BI__builtin_isfinite: {
11243     APFloat Val(0.0);
11244     return EvaluateFloat(E->getArg(0), Val, Info) &&
11245            Success(Val.isFinite() ? 1 : 0, E);
11246   }
11247 
11248   case Builtin::BI__builtin_isnan: {
11249     APFloat Val(0.0);
11250     return EvaluateFloat(E->getArg(0), Val, Info) &&
11251            Success(Val.isNaN() ? 1 : 0, E);
11252   }
11253 
11254   case Builtin::BI__builtin_isnormal: {
11255     APFloat Val(0.0);
11256     return EvaluateFloat(E->getArg(0), Val, Info) &&
11257            Success(Val.isNormal() ? 1 : 0, E);
11258   }
11259 
11260   case Builtin::BI__builtin_parity:
11261   case Builtin::BI__builtin_parityl:
11262   case Builtin::BI__builtin_parityll: {
11263     APSInt Val;
11264     if (!EvaluateInteger(E->getArg(0), Val, Info))
11265       return false;
11266 
11267     return Success(Val.countPopulation() % 2, E);
11268   }
11269 
11270   case Builtin::BI__builtin_popcount:
11271   case Builtin::BI__builtin_popcountl:
11272   case Builtin::BI__builtin_popcountll: {
11273     APSInt Val;
11274     if (!EvaluateInteger(E->getArg(0), Val, Info))
11275       return false;
11276 
11277     return Success(Val.countPopulation(), E);
11278   }
11279 
11280   case Builtin::BIstrlen:
11281   case Builtin::BIwcslen:
11282     // A call to strlen is not a constant expression.
11283     if (Info.getLangOpts().CPlusPlus11)
11284       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11285         << /*isConstexpr*/0 << /*isConstructor*/0
11286         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11287     else
11288       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11289     LLVM_FALLTHROUGH;
11290   case Builtin::BI__builtin_strlen:
11291   case Builtin::BI__builtin_wcslen: {
11292     // As an extension, we support __builtin_strlen() as a constant expression,
11293     // and support folding strlen() to a constant.
11294     LValue String;
11295     if (!EvaluatePointer(E->getArg(0), String, Info))
11296       return false;
11297 
11298     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
11299 
11300     // Fast path: if it's a string literal, search the string value.
11301     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
11302             String.getLValueBase().dyn_cast<const Expr *>())) {
11303       // The string literal may have embedded null characters. Find the first
11304       // one and truncate there.
11305       StringRef Str = S->getBytes();
11306       int64_t Off = String.Offset.getQuantity();
11307       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
11308           S->getCharByteWidth() == 1 &&
11309           // FIXME: Add fast-path for wchar_t too.
11310           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
11311         Str = Str.substr(Off);
11312 
11313         StringRef::size_type Pos = Str.find(0);
11314         if (Pos != StringRef::npos)
11315           Str = Str.substr(0, Pos);
11316 
11317         return Success(Str.size(), E);
11318       }
11319 
11320       // Fall through to slow path to issue appropriate diagnostic.
11321     }
11322 
11323     // Slow path: scan the bytes of the string looking for the terminating 0.
11324     for (uint64_t Strlen = 0; /**/; ++Strlen) {
11325       APValue Char;
11326       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
11327           !Char.isInt())
11328         return false;
11329       if (!Char.getInt())
11330         return Success(Strlen, E);
11331       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
11332         return false;
11333     }
11334   }
11335 
11336   case Builtin::BIstrcmp:
11337   case Builtin::BIwcscmp:
11338   case Builtin::BIstrncmp:
11339   case Builtin::BIwcsncmp:
11340   case Builtin::BImemcmp:
11341   case Builtin::BIbcmp:
11342   case Builtin::BIwmemcmp:
11343     // A call to strlen is not a constant expression.
11344     if (Info.getLangOpts().CPlusPlus11)
11345       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11346         << /*isConstexpr*/0 << /*isConstructor*/0
11347         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11348     else
11349       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11350     LLVM_FALLTHROUGH;
11351   case Builtin::BI__builtin_strcmp:
11352   case Builtin::BI__builtin_wcscmp:
11353   case Builtin::BI__builtin_strncmp:
11354   case Builtin::BI__builtin_wcsncmp:
11355   case Builtin::BI__builtin_memcmp:
11356   case Builtin::BI__builtin_bcmp:
11357   case Builtin::BI__builtin_wmemcmp: {
11358     LValue String1, String2;
11359     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
11360         !EvaluatePointer(E->getArg(1), String2, Info))
11361       return false;
11362 
11363     uint64_t MaxLength = uint64_t(-1);
11364     if (BuiltinOp != Builtin::BIstrcmp &&
11365         BuiltinOp != Builtin::BIwcscmp &&
11366         BuiltinOp != Builtin::BI__builtin_strcmp &&
11367         BuiltinOp != Builtin::BI__builtin_wcscmp) {
11368       APSInt N;
11369       if (!EvaluateInteger(E->getArg(2), N, Info))
11370         return false;
11371       MaxLength = N.getExtValue();
11372     }
11373 
11374     // Empty substrings compare equal by definition.
11375     if (MaxLength == 0u)
11376       return Success(0, E);
11377 
11378     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11379         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11380         String1.Designator.Invalid || String2.Designator.Invalid)
11381       return false;
11382 
11383     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
11384     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
11385 
11386     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
11387                      BuiltinOp == Builtin::BIbcmp ||
11388                      BuiltinOp == Builtin::BI__builtin_memcmp ||
11389                      BuiltinOp == Builtin::BI__builtin_bcmp;
11390 
11391     assert(IsRawByte ||
11392            (Info.Ctx.hasSameUnqualifiedType(
11393                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
11394             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
11395 
11396     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
11397     // 'char8_t', but no other types.
11398     if (IsRawByte &&
11399         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
11400       // FIXME: Consider using our bit_cast implementation to support this.
11401       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
11402           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
11403           << CharTy1 << CharTy2;
11404       return false;
11405     }
11406 
11407     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
11408       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
11409              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
11410              Char1.isInt() && Char2.isInt();
11411     };
11412     const auto &AdvanceElems = [&] {
11413       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
11414              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
11415     };
11416 
11417     bool StopAtNull =
11418         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
11419          BuiltinOp != Builtin::BIwmemcmp &&
11420          BuiltinOp != Builtin::BI__builtin_memcmp &&
11421          BuiltinOp != Builtin::BI__builtin_bcmp &&
11422          BuiltinOp != Builtin::BI__builtin_wmemcmp);
11423     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
11424                   BuiltinOp == Builtin::BIwcsncmp ||
11425                   BuiltinOp == Builtin::BIwmemcmp ||
11426                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
11427                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
11428                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
11429 
11430     for (; MaxLength; --MaxLength) {
11431       APValue Char1, Char2;
11432       if (!ReadCurElems(Char1, Char2))
11433         return false;
11434       if (Char1.getInt().ne(Char2.getInt())) {
11435         if (IsWide) // wmemcmp compares with wchar_t signedness.
11436           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
11437         // memcmp always compares unsigned chars.
11438         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
11439       }
11440       if (StopAtNull && !Char1.getInt())
11441         return Success(0, E);
11442       assert(!(StopAtNull && !Char2.getInt()));
11443       if (!AdvanceElems())
11444         return false;
11445     }
11446     // We hit the strncmp / memcmp limit.
11447     return Success(0, E);
11448   }
11449 
11450   case Builtin::BI__atomic_always_lock_free:
11451   case Builtin::BI__atomic_is_lock_free:
11452   case Builtin::BI__c11_atomic_is_lock_free: {
11453     APSInt SizeVal;
11454     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
11455       return false;
11456 
11457     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
11458     // of two less than the maximum inline atomic width, we know it is
11459     // lock-free.  If the size isn't a power of two, or greater than the
11460     // maximum alignment where we promote atomics, we know it is not lock-free
11461     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
11462     // the answer can only be determined at runtime; for example, 16-byte
11463     // atomics have lock-free implementations on some, but not all,
11464     // x86-64 processors.
11465 
11466     // Check power-of-two.
11467     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
11468     if (Size.isPowerOfTwo()) {
11469       // Check against inlining width.
11470       unsigned InlineWidthBits =
11471           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
11472       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
11473         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
11474             Size == CharUnits::One() ||
11475             E->getArg(1)->isNullPointerConstant(Info.Ctx,
11476                                                 Expr::NPC_NeverValueDependent))
11477           // OK, we will inline appropriately-aligned operations of this size,
11478           // and _Atomic(T) is appropriately-aligned.
11479           return Success(1, E);
11480 
11481         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
11482           castAs<PointerType>()->getPointeeType();
11483         if (!PointeeType->isIncompleteType() &&
11484             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
11485           // OK, we will inline operations on this object.
11486           return Success(1, E);
11487         }
11488       }
11489     }
11490 
11491     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
11492         Success(0, E) : Error(E);
11493   }
11494   case Builtin::BIomp_is_initial_device:
11495     // We can decide statically which value the runtime would return if called.
11496     return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
11497   case Builtin::BI__builtin_add_overflow:
11498   case Builtin::BI__builtin_sub_overflow:
11499   case Builtin::BI__builtin_mul_overflow:
11500   case Builtin::BI__builtin_sadd_overflow:
11501   case Builtin::BI__builtin_uadd_overflow:
11502   case Builtin::BI__builtin_uaddl_overflow:
11503   case Builtin::BI__builtin_uaddll_overflow:
11504   case Builtin::BI__builtin_usub_overflow:
11505   case Builtin::BI__builtin_usubl_overflow:
11506   case Builtin::BI__builtin_usubll_overflow:
11507   case Builtin::BI__builtin_umul_overflow:
11508   case Builtin::BI__builtin_umull_overflow:
11509   case Builtin::BI__builtin_umulll_overflow:
11510   case Builtin::BI__builtin_saddl_overflow:
11511   case Builtin::BI__builtin_saddll_overflow:
11512   case Builtin::BI__builtin_ssub_overflow:
11513   case Builtin::BI__builtin_ssubl_overflow:
11514   case Builtin::BI__builtin_ssubll_overflow:
11515   case Builtin::BI__builtin_smul_overflow:
11516   case Builtin::BI__builtin_smull_overflow:
11517   case Builtin::BI__builtin_smulll_overflow: {
11518     LValue ResultLValue;
11519     APSInt LHS, RHS;
11520 
11521     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
11522     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
11523         !EvaluateInteger(E->getArg(1), RHS, Info) ||
11524         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
11525       return false;
11526 
11527     APSInt Result;
11528     bool DidOverflow = false;
11529 
11530     // If the types don't have to match, enlarge all 3 to the largest of them.
11531     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11532         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11533         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11534       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
11535                       ResultType->isSignedIntegerOrEnumerationType();
11536       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
11537                       ResultType->isSignedIntegerOrEnumerationType();
11538       uint64_t LHSSize = LHS.getBitWidth();
11539       uint64_t RHSSize = RHS.getBitWidth();
11540       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
11541       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
11542 
11543       // Add an additional bit if the signedness isn't uniformly agreed to. We
11544       // could do this ONLY if there is a signed and an unsigned that both have
11545       // MaxBits, but the code to check that is pretty nasty.  The issue will be
11546       // caught in the shrink-to-result later anyway.
11547       if (IsSigned && !AllSigned)
11548         ++MaxBits;
11549 
11550       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
11551       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
11552       Result = APSInt(MaxBits, !IsSigned);
11553     }
11554 
11555     // Find largest int.
11556     switch (BuiltinOp) {
11557     default:
11558       llvm_unreachable("Invalid value for BuiltinOp");
11559     case Builtin::BI__builtin_add_overflow:
11560     case Builtin::BI__builtin_sadd_overflow:
11561     case Builtin::BI__builtin_saddl_overflow:
11562     case Builtin::BI__builtin_saddll_overflow:
11563     case Builtin::BI__builtin_uadd_overflow:
11564     case Builtin::BI__builtin_uaddl_overflow:
11565     case Builtin::BI__builtin_uaddll_overflow:
11566       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
11567                               : LHS.uadd_ov(RHS, DidOverflow);
11568       break;
11569     case Builtin::BI__builtin_sub_overflow:
11570     case Builtin::BI__builtin_ssub_overflow:
11571     case Builtin::BI__builtin_ssubl_overflow:
11572     case Builtin::BI__builtin_ssubll_overflow:
11573     case Builtin::BI__builtin_usub_overflow:
11574     case Builtin::BI__builtin_usubl_overflow:
11575     case Builtin::BI__builtin_usubll_overflow:
11576       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
11577                               : LHS.usub_ov(RHS, DidOverflow);
11578       break;
11579     case Builtin::BI__builtin_mul_overflow:
11580     case Builtin::BI__builtin_smul_overflow:
11581     case Builtin::BI__builtin_smull_overflow:
11582     case Builtin::BI__builtin_smulll_overflow:
11583     case Builtin::BI__builtin_umul_overflow:
11584     case Builtin::BI__builtin_umull_overflow:
11585     case Builtin::BI__builtin_umulll_overflow:
11586       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
11587                               : LHS.umul_ov(RHS, DidOverflow);
11588       break;
11589     }
11590 
11591     // In the case where multiple sizes are allowed, truncate and see if
11592     // the values are the same.
11593     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11594         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11595         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11596       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
11597       // since it will give us the behavior of a TruncOrSelf in the case where
11598       // its parameter <= its size.  We previously set Result to be at least the
11599       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
11600       // will work exactly like TruncOrSelf.
11601       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
11602       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
11603 
11604       if (!APSInt::isSameValue(Temp, Result))
11605         DidOverflow = true;
11606       Result = Temp;
11607     }
11608 
11609     APValue APV{Result};
11610     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
11611       return false;
11612     return Success(DidOverflow, E);
11613   }
11614   }
11615 }
11616 
11617 /// Determine whether this is a pointer past the end of the complete
11618 /// object referred to by the lvalue.
11619 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
11620                                             const LValue &LV) {
11621   // A null pointer can be viewed as being "past the end" but we don't
11622   // choose to look at it that way here.
11623   if (!LV.getLValueBase())
11624     return false;
11625 
11626   // If the designator is valid and refers to a subobject, we're not pointing
11627   // past the end.
11628   if (!LV.getLValueDesignator().Invalid &&
11629       !LV.getLValueDesignator().isOnePastTheEnd())
11630     return false;
11631 
11632   // A pointer to an incomplete type might be past-the-end if the type's size is
11633   // zero.  We cannot tell because the type is incomplete.
11634   QualType Ty = getType(LV.getLValueBase());
11635   if (Ty->isIncompleteType())
11636     return true;
11637 
11638   // We're a past-the-end pointer if we point to the byte after the object,
11639   // no matter what our type or path is.
11640   auto Size = Ctx.getTypeSizeInChars(Ty);
11641   return LV.getLValueOffset() == Size;
11642 }
11643 
11644 namespace {
11645 
11646 /// Data recursive integer evaluator of certain binary operators.
11647 ///
11648 /// We use a data recursive algorithm for binary operators so that we are able
11649 /// to handle extreme cases of chained binary operators without causing stack
11650 /// overflow.
11651 class DataRecursiveIntBinOpEvaluator {
11652   struct EvalResult {
11653     APValue Val;
11654     bool Failed;
11655 
11656     EvalResult() : Failed(false) { }
11657 
11658     void swap(EvalResult &RHS) {
11659       Val.swap(RHS.Val);
11660       Failed = RHS.Failed;
11661       RHS.Failed = false;
11662     }
11663   };
11664 
11665   struct Job {
11666     const Expr *E;
11667     EvalResult LHSResult; // meaningful only for binary operator expression.
11668     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
11669 
11670     Job() = default;
11671     Job(Job &&) = default;
11672 
11673     void startSpeculativeEval(EvalInfo &Info) {
11674       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
11675     }
11676 
11677   private:
11678     SpeculativeEvaluationRAII SpecEvalRAII;
11679   };
11680 
11681   SmallVector<Job, 16> Queue;
11682 
11683   IntExprEvaluator &IntEval;
11684   EvalInfo &Info;
11685   APValue &FinalResult;
11686 
11687 public:
11688   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
11689     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
11690 
11691   /// True if \param E is a binary operator that we are going to handle
11692   /// data recursively.
11693   /// We handle binary operators that are comma, logical, or that have operands
11694   /// with integral or enumeration type.
11695   static bool shouldEnqueue(const BinaryOperator *E) {
11696     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
11697            (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
11698             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11699             E->getRHS()->getType()->isIntegralOrEnumerationType());
11700   }
11701 
11702   bool Traverse(const BinaryOperator *E) {
11703     enqueue(E);
11704     EvalResult PrevResult;
11705     while (!Queue.empty())
11706       process(PrevResult);
11707 
11708     if (PrevResult.Failed) return false;
11709 
11710     FinalResult.swap(PrevResult.Val);
11711     return true;
11712   }
11713 
11714 private:
11715   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11716     return IntEval.Success(Value, E, Result);
11717   }
11718   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
11719     return IntEval.Success(Value, E, Result);
11720   }
11721   bool Error(const Expr *E) {
11722     return IntEval.Error(E);
11723   }
11724   bool Error(const Expr *E, diag::kind D) {
11725     return IntEval.Error(E, D);
11726   }
11727 
11728   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
11729     return Info.CCEDiag(E, D);
11730   }
11731 
11732   // Returns true if visiting the RHS is necessary, false otherwise.
11733   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
11734                          bool &SuppressRHSDiags);
11735 
11736   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
11737                   const BinaryOperator *E, APValue &Result);
11738 
11739   void EvaluateExpr(const Expr *E, EvalResult &Result) {
11740     Result.Failed = !Evaluate(Result.Val, Info, E);
11741     if (Result.Failed)
11742       Result.Val = APValue();
11743   }
11744 
11745   void process(EvalResult &Result);
11746 
11747   void enqueue(const Expr *E) {
11748     E = E->IgnoreParens();
11749     Queue.resize(Queue.size()+1);
11750     Queue.back().E = E;
11751     Queue.back().Kind = Job::AnyExprKind;
11752   }
11753 };
11754 
11755 }
11756 
11757 bool DataRecursiveIntBinOpEvaluator::
11758        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
11759                          bool &SuppressRHSDiags) {
11760   if (E->getOpcode() == BO_Comma) {
11761     // Ignore LHS but note if we could not evaluate it.
11762     if (LHSResult.Failed)
11763       return Info.noteSideEffect();
11764     return true;
11765   }
11766 
11767   if (E->isLogicalOp()) {
11768     bool LHSAsBool;
11769     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
11770       // We were able to evaluate the LHS, see if we can get away with not
11771       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
11772       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
11773         Success(LHSAsBool, E, LHSResult.Val);
11774         return false; // Ignore RHS
11775       }
11776     } else {
11777       LHSResult.Failed = true;
11778 
11779       // Since we weren't able to evaluate the left hand side, it
11780       // might have had side effects.
11781       if (!Info.noteSideEffect())
11782         return false;
11783 
11784       // We can't evaluate the LHS; however, sometimes the result
11785       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
11786       // Don't ignore RHS and suppress diagnostics from this arm.
11787       SuppressRHSDiags = true;
11788     }
11789 
11790     return true;
11791   }
11792 
11793   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11794          E->getRHS()->getType()->isIntegralOrEnumerationType());
11795 
11796   if (LHSResult.Failed && !Info.noteFailure())
11797     return false; // Ignore RHS;
11798 
11799   return true;
11800 }
11801 
11802 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
11803                                     bool IsSub) {
11804   // Compute the new offset in the appropriate width, wrapping at 64 bits.
11805   // FIXME: When compiling for a 32-bit target, we should use 32-bit
11806   // offsets.
11807   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
11808   CharUnits &Offset = LVal.getLValueOffset();
11809   uint64_t Offset64 = Offset.getQuantity();
11810   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
11811   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
11812                                          : Offset64 + Index64);
11813 }
11814 
11815 bool DataRecursiveIntBinOpEvaluator::
11816        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
11817                   const BinaryOperator *E, APValue &Result) {
11818   if (E->getOpcode() == BO_Comma) {
11819     if (RHSResult.Failed)
11820       return false;
11821     Result = RHSResult.Val;
11822     return true;
11823   }
11824 
11825   if (E->isLogicalOp()) {
11826     bool lhsResult, rhsResult;
11827     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
11828     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
11829 
11830     if (LHSIsOK) {
11831       if (RHSIsOK) {
11832         if (E->getOpcode() == BO_LOr)
11833           return Success(lhsResult || rhsResult, E, Result);
11834         else
11835           return Success(lhsResult && rhsResult, E, Result);
11836       }
11837     } else {
11838       if (RHSIsOK) {
11839         // We can't evaluate the LHS; however, sometimes the result
11840         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
11841         if (rhsResult == (E->getOpcode() == BO_LOr))
11842           return Success(rhsResult, E, Result);
11843       }
11844     }
11845 
11846     return false;
11847   }
11848 
11849   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11850          E->getRHS()->getType()->isIntegralOrEnumerationType());
11851 
11852   if (LHSResult.Failed || RHSResult.Failed)
11853     return false;
11854 
11855   const APValue &LHSVal = LHSResult.Val;
11856   const APValue &RHSVal = RHSResult.Val;
11857 
11858   // Handle cases like (unsigned long)&a + 4.
11859   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
11860     Result = LHSVal;
11861     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
11862     return true;
11863   }
11864 
11865   // Handle cases like 4 + (unsigned long)&a
11866   if (E->getOpcode() == BO_Add &&
11867       RHSVal.isLValue() && LHSVal.isInt()) {
11868     Result = RHSVal;
11869     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
11870     return true;
11871   }
11872 
11873   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
11874     // Handle (intptr_t)&&A - (intptr_t)&&B.
11875     if (!LHSVal.getLValueOffset().isZero() ||
11876         !RHSVal.getLValueOffset().isZero())
11877       return false;
11878     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
11879     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
11880     if (!LHSExpr || !RHSExpr)
11881       return false;
11882     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
11883     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
11884     if (!LHSAddrExpr || !RHSAddrExpr)
11885       return false;
11886     // Make sure both labels come from the same function.
11887     if (LHSAddrExpr->getLabel()->getDeclContext() !=
11888         RHSAddrExpr->getLabel()->getDeclContext())
11889       return false;
11890     Result = APValue(LHSAddrExpr, RHSAddrExpr);
11891     return true;
11892   }
11893 
11894   // All the remaining cases expect both operands to be an integer
11895   if (!LHSVal.isInt() || !RHSVal.isInt())
11896     return Error(E);
11897 
11898   // Set up the width and signedness manually, in case it can't be deduced
11899   // from the operation we're performing.
11900   // FIXME: Don't do this in the cases where we can deduce it.
11901   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
11902                E->getType()->isUnsignedIntegerOrEnumerationType());
11903   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
11904                          RHSVal.getInt(), Value))
11905     return false;
11906   return Success(Value, E, Result);
11907 }
11908 
11909 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
11910   Job &job = Queue.back();
11911 
11912   switch (job.Kind) {
11913     case Job::AnyExprKind: {
11914       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
11915         if (shouldEnqueue(Bop)) {
11916           job.Kind = Job::BinOpKind;
11917           enqueue(Bop->getLHS());
11918           return;
11919         }
11920       }
11921 
11922       EvaluateExpr(job.E, Result);
11923       Queue.pop_back();
11924       return;
11925     }
11926 
11927     case Job::BinOpKind: {
11928       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
11929       bool SuppressRHSDiags = false;
11930       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
11931         Queue.pop_back();
11932         return;
11933       }
11934       if (SuppressRHSDiags)
11935         job.startSpeculativeEval(Info);
11936       job.LHSResult.swap(Result);
11937       job.Kind = Job::BinOpVisitedLHSKind;
11938       enqueue(Bop->getRHS());
11939       return;
11940     }
11941 
11942     case Job::BinOpVisitedLHSKind: {
11943       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
11944       EvalResult RHS;
11945       RHS.swap(Result);
11946       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
11947       Queue.pop_back();
11948       return;
11949     }
11950   }
11951 
11952   llvm_unreachable("Invalid Job::Kind!");
11953 }
11954 
11955 namespace {
11956 /// Used when we determine that we should fail, but can keep evaluating prior to
11957 /// noting that we had a failure.
11958 class DelayedNoteFailureRAII {
11959   EvalInfo &Info;
11960   bool NoteFailure;
11961 
11962 public:
11963   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
11964       : Info(Info), NoteFailure(NoteFailure) {}
11965   ~DelayedNoteFailureRAII() {
11966     if (NoteFailure) {
11967       bool ContinueAfterFailure = Info.noteFailure();
11968       (void)ContinueAfterFailure;
11969       assert(ContinueAfterFailure &&
11970              "Shouldn't have kept evaluating on failure.");
11971     }
11972   }
11973 };
11974 
11975 enum class CmpResult {
11976   Unequal,
11977   Less,
11978   Equal,
11979   Greater,
11980   Unordered,
11981 };
11982 }
11983 
11984 template <class SuccessCB, class AfterCB>
11985 static bool
11986 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
11987                                  SuccessCB &&Success, AfterCB &&DoAfter) {
11988   assert(E->isComparisonOp() && "expected comparison operator");
11989   assert((E->getOpcode() == BO_Cmp ||
11990           E->getType()->isIntegralOrEnumerationType()) &&
11991          "unsupported binary expression evaluation");
11992   auto Error = [&](const Expr *E) {
11993     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11994     return false;
11995   };
11996 
11997   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
11998   bool IsEquality = E->isEqualityOp();
11999 
12000   QualType LHSTy = E->getLHS()->getType();
12001   QualType RHSTy = E->getRHS()->getType();
12002 
12003   if (LHSTy->isIntegralOrEnumerationType() &&
12004       RHSTy->isIntegralOrEnumerationType()) {
12005     APSInt LHS, RHS;
12006     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12007     if (!LHSOK && !Info.noteFailure())
12008       return false;
12009     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12010       return false;
12011     if (LHS < RHS)
12012       return Success(CmpResult::Less, E);
12013     if (LHS > RHS)
12014       return Success(CmpResult::Greater, E);
12015     return Success(CmpResult::Equal, E);
12016   }
12017 
12018   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12019     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12020     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12021 
12022     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12023     if (!LHSOK && !Info.noteFailure())
12024       return false;
12025     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12026       return false;
12027     if (LHSFX < RHSFX)
12028       return Success(CmpResult::Less, E);
12029     if (LHSFX > RHSFX)
12030       return Success(CmpResult::Greater, E);
12031     return Success(CmpResult::Equal, E);
12032   }
12033 
12034   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12035     ComplexValue LHS, RHS;
12036     bool LHSOK;
12037     if (E->isAssignmentOp()) {
12038       LValue LV;
12039       EvaluateLValue(E->getLHS(), LV, Info);
12040       LHSOK = false;
12041     } else if (LHSTy->isRealFloatingType()) {
12042       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12043       if (LHSOK) {
12044         LHS.makeComplexFloat();
12045         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12046       }
12047     } else {
12048       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12049     }
12050     if (!LHSOK && !Info.noteFailure())
12051       return false;
12052 
12053     if (E->getRHS()->getType()->isRealFloatingType()) {
12054       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12055         return false;
12056       RHS.makeComplexFloat();
12057       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12058     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12059       return false;
12060 
12061     if (LHS.isComplexFloat()) {
12062       APFloat::cmpResult CR_r =
12063         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12064       APFloat::cmpResult CR_i =
12065         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12066       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12067       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12068     } else {
12069       assert(IsEquality && "invalid complex comparison");
12070       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12071                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
12072       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12073     }
12074   }
12075 
12076   if (LHSTy->isRealFloatingType() &&
12077       RHSTy->isRealFloatingType()) {
12078     APFloat RHS(0.0), LHS(0.0);
12079 
12080     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12081     if (!LHSOK && !Info.noteFailure())
12082       return false;
12083 
12084     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12085       return false;
12086 
12087     assert(E->isComparisonOp() && "Invalid binary operator!");
12088     auto GetCmpRes = [&]() {
12089       switch (LHS.compare(RHS)) {
12090       case APFloat::cmpEqual:
12091         return CmpResult::Equal;
12092       case APFloat::cmpLessThan:
12093         return CmpResult::Less;
12094       case APFloat::cmpGreaterThan:
12095         return CmpResult::Greater;
12096       case APFloat::cmpUnordered:
12097         return CmpResult::Unordered;
12098       }
12099       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12100     };
12101     return Success(GetCmpRes(), E);
12102   }
12103 
12104   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12105     LValue LHSValue, RHSValue;
12106 
12107     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12108     if (!LHSOK && !Info.noteFailure())
12109       return false;
12110 
12111     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12112       return false;
12113 
12114     // Reject differing bases from the normal codepath; we special-case
12115     // comparisons to null.
12116     if (!HasSameBase(LHSValue, RHSValue)) {
12117       // Inequalities and subtractions between unrelated pointers have
12118       // unspecified or undefined behavior.
12119       if (!IsEquality) {
12120         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
12121         return false;
12122       }
12123       // A constant address may compare equal to the address of a symbol.
12124       // The one exception is that address of an object cannot compare equal
12125       // to a null pointer constant.
12126       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12127           (!RHSValue.Base && !RHSValue.Offset.isZero()))
12128         return Error(E);
12129       // It's implementation-defined whether distinct literals will have
12130       // distinct addresses. In clang, the result of such a comparison is
12131       // unspecified, so it is not a constant expression. However, we do know
12132       // that the address of a literal will be non-null.
12133       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12134           LHSValue.Base && RHSValue.Base)
12135         return Error(E);
12136       // We can't tell whether weak symbols will end up pointing to the same
12137       // object.
12138       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12139         return Error(E);
12140       // We can't compare the address of the start of one object with the
12141       // past-the-end address of another object, per C++ DR1652.
12142       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
12143            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
12144           (RHSValue.Base && RHSValue.Offset.isZero() &&
12145            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
12146         return Error(E);
12147       // We can't tell whether an object is at the same address as another
12148       // zero sized object.
12149       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12150           (LHSValue.Base && isZeroSized(RHSValue)))
12151         return Error(E);
12152       return Success(CmpResult::Unequal, E);
12153     }
12154 
12155     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12156     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12157 
12158     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12159     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12160 
12161     // C++11 [expr.rel]p3:
12162     //   Pointers to void (after pointer conversions) can be compared, with a
12163     //   result defined as follows: If both pointers represent the same
12164     //   address or are both the null pointer value, the result is true if the
12165     //   operator is <= or >= and false otherwise; otherwise the result is
12166     //   unspecified.
12167     // We interpret this as applying to pointers to *cv* void.
12168     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
12169       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
12170 
12171     // C++11 [expr.rel]p2:
12172     // - If two pointers point to non-static data members of the same object,
12173     //   or to subobjects or array elements fo such members, recursively, the
12174     //   pointer to the later declared member compares greater provided the
12175     //   two members have the same access control and provided their class is
12176     //   not a union.
12177     //   [...]
12178     // - Otherwise pointer comparisons are unspecified.
12179     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
12180       bool WasArrayIndex;
12181       unsigned Mismatch = FindDesignatorMismatch(
12182           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
12183       // At the point where the designators diverge, the comparison has a
12184       // specified value if:
12185       //  - we are comparing array indices
12186       //  - we are comparing fields of a union, or fields with the same access
12187       // Otherwise, the result is unspecified and thus the comparison is not a
12188       // constant expression.
12189       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
12190           Mismatch < RHSDesignator.Entries.size()) {
12191         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
12192         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
12193         if (!LF && !RF)
12194           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
12195         else if (!LF)
12196           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12197               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
12198               << RF->getParent() << RF;
12199         else if (!RF)
12200           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12201               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
12202               << LF->getParent() << LF;
12203         else if (!LF->getParent()->isUnion() &&
12204                  LF->getAccess() != RF->getAccess())
12205           Info.CCEDiag(E,
12206                        diag::note_constexpr_pointer_comparison_differing_access)
12207               << LF << LF->getAccess() << RF << RF->getAccess()
12208               << LF->getParent();
12209       }
12210     }
12211 
12212     // The comparison here must be unsigned, and performed with the same
12213     // width as the pointer.
12214     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
12215     uint64_t CompareLHS = LHSOffset.getQuantity();
12216     uint64_t CompareRHS = RHSOffset.getQuantity();
12217     assert(PtrSize <= 64 && "Unexpected pointer width");
12218     uint64_t Mask = ~0ULL >> (64 - PtrSize);
12219     CompareLHS &= Mask;
12220     CompareRHS &= Mask;
12221 
12222     // If there is a base and this is a relational operator, we can only
12223     // compare pointers within the object in question; otherwise, the result
12224     // depends on where the object is located in memory.
12225     if (!LHSValue.Base.isNull() && IsRelational) {
12226       QualType BaseTy = getType(LHSValue.Base);
12227       if (BaseTy->isIncompleteType())
12228         return Error(E);
12229       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
12230       uint64_t OffsetLimit = Size.getQuantity();
12231       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
12232         return Error(E);
12233     }
12234 
12235     if (CompareLHS < CompareRHS)
12236       return Success(CmpResult::Less, E);
12237     if (CompareLHS > CompareRHS)
12238       return Success(CmpResult::Greater, E);
12239     return Success(CmpResult::Equal, E);
12240   }
12241 
12242   if (LHSTy->isMemberPointerType()) {
12243     assert(IsEquality && "unexpected member pointer operation");
12244     assert(RHSTy->isMemberPointerType() && "invalid comparison");
12245 
12246     MemberPtr LHSValue, RHSValue;
12247 
12248     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
12249     if (!LHSOK && !Info.noteFailure())
12250       return false;
12251 
12252     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12253       return false;
12254 
12255     // C++11 [expr.eq]p2:
12256     //   If both operands are null, they compare equal. Otherwise if only one is
12257     //   null, they compare unequal.
12258     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
12259       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
12260       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12261     }
12262 
12263     //   Otherwise if either is a pointer to a virtual member function, the
12264     //   result is unspecified.
12265     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
12266       if (MD->isVirtual())
12267         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12268     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
12269       if (MD->isVirtual())
12270         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12271 
12272     //   Otherwise they compare equal if and only if they would refer to the
12273     //   same member of the same most derived object or the same subobject if
12274     //   they were dereferenced with a hypothetical object of the associated
12275     //   class type.
12276     bool Equal = LHSValue == RHSValue;
12277     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12278   }
12279 
12280   if (LHSTy->isNullPtrType()) {
12281     assert(E->isComparisonOp() && "unexpected nullptr operation");
12282     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12283     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12284     // are compared, the result is true of the operator is <=, >= or ==, and
12285     // false otherwise.
12286     return Success(CmpResult::Equal, E);
12287   }
12288 
12289   return DoAfter();
12290 }
12291 
12292 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
12293   if (!CheckLiteralType(Info, E))
12294     return false;
12295 
12296   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12297     ComparisonCategoryResult CCR;
12298     switch (CR) {
12299     case CmpResult::Unequal:
12300       llvm_unreachable("should never produce Unequal for three-way comparison");
12301     case CmpResult::Less:
12302       CCR = ComparisonCategoryResult::Less;
12303       break;
12304     case CmpResult::Equal:
12305       CCR = ComparisonCategoryResult::Equal;
12306       break;
12307     case CmpResult::Greater:
12308       CCR = ComparisonCategoryResult::Greater;
12309       break;
12310     case CmpResult::Unordered:
12311       CCR = ComparisonCategoryResult::Unordered;
12312       break;
12313     }
12314     // Evaluation succeeded. Lookup the information for the comparison category
12315     // type and fetch the VarDecl for the result.
12316     const ComparisonCategoryInfo &CmpInfo =
12317         Info.Ctx.CompCategories.getInfoForType(E->getType());
12318     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
12319     // Check and evaluate the result as a constant expression.
12320     LValue LV;
12321     LV.set(VD);
12322     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12323       return false;
12324     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
12325   };
12326   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12327     return ExprEvaluatorBaseTy::VisitBinCmp(E);
12328   });
12329 }
12330 
12331 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12332   // We don't call noteFailure immediately because the assignment happens after
12333   // we evaluate LHS and RHS.
12334   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
12335     return Error(E);
12336 
12337   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
12338   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
12339     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
12340 
12341   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
12342           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
12343          "DataRecursiveIntBinOpEvaluator should have handled integral types");
12344 
12345   if (E->isComparisonOp()) {
12346     // Evaluate builtin binary comparisons by evaluating them as three-way
12347     // comparisons and then translating the result.
12348     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12349       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
12350              "should only produce Unequal for equality comparisons");
12351       bool IsEqual   = CR == CmpResult::Equal,
12352            IsLess    = CR == CmpResult::Less,
12353            IsGreater = CR == CmpResult::Greater;
12354       auto Op = E->getOpcode();
12355       switch (Op) {
12356       default:
12357         llvm_unreachable("unsupported binary operator");
12358       case BO_EQ:
12359       case BO_NE:
12360         return Success(IsEqual == (Op == BO_EQ), E);
12361       case BO_LT:
12362         return Success(IsLess, E);
12363       case BO_GT:
12364         return Success(IsGreater, E);
12365       case BO_LE:
12366         return Success(IsEqual || IsLess, E);
12367       case BO_GE:
12368         return Success(IsEqual || IsGreater, E);
12369       }
12370     };
12371     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12372       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12373     });
12374   }
12375 
12376   QualType LHSTy = E->getLHS()->getType();
12377   QualType RHSTy = E->getRHS()->getType();
12378 
12379   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
12380       E->getOpcode() == BO_Sub) {
12381     LValue LHSValue, RHSValue;
12382 
12383     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12384     if (!LHSOK && !Info.noteFailure())
12385       return false;
12386 
12387     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12388       return false;
12389 
12390     // Reject differing bases from the normal codepath; we special-case
12391     // comparisons to null.
12392     if (!HasSameBase(LHSValue, RHSValue)) {
12393       // Handle &&A - &&B.
12394       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
12395         return Error(E);
12396       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
12397       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
12398       if (!LHSExpr || !RHSExpr)
12399         return Error(E);
12400       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12401       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12402       if (!LHSAddrExpr || !RHSAddrExpr)
12403         return Error(E);
12404       // Make sure both labels come from the same function.
12405       if (LHSAddrExpr->getLabel()->getDeclContext() !=
12406           RHSAddrExpr->getLabel()->getDeclContext())
12407         return Error(E);
12408       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
12409     }
12410     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12411     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12412 
12413     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12414     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12415 
12416     // C++11 [expr.add]p6:
12417     //   Unless both pointers point to elements of the same array object, or
12418     //   one past the last element of the array object, the behavior is
12419     //   undefined.
12420     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
12421         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
12422                                 RHSDesignator))
12423       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
12424 
12425     QualType Type = E->getLHS()->getType();
12426     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
12427 
12428     CharUnits ElementSize;
12429     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
12430       return false;
12431 
12432     // As an extension, a type may have zero size (empty struct or union in
12433     // C, array of zero length). Pointer subtraction in such cases has
12434     // undefined behavior, so is not constant.
12435     if (ElementSize.isZero()) {
12436       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
12437           << ElementType;
12438       return false;
12439     }
12440 
12441     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
12442     // and produce incorrect results when it overflows. Such behavior
12443     // appears to be non-conforming, but is common, so perhaps we should
12444     // assume the standard intended for such cases to be undefined behavior
12445     // and check for them.
12446 
12447     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
12448     // overflow in the final conversion to ptrdiff_t.
12449     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
12450     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
12451     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
12452                     false);
12453     APSInt TrueResult = (LHS - RHS) / ElemSize;
12454     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
12455 
12456     if (Result.extend(65) != TrueResult &&
12457         !HandleOverflow(Info, E, TrueResult, E->getType()))
12458       return false;
12459     return Success(Result, E);
12460   }
12461 
12462   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12463 }
12464 
12465 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
12466 /// a result as the expression's type.
12467 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
12468                                     const UnaryExprOrTypeTraitExpr *E) {
12469   switch(E->getKind()) {
12470   case UETT_PreferredAlignOf:
12471   case UETT_AlignOf: {
12472     if (E->isArgumentType())
12473       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
12474                      E);
12475     else
12476       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
12477                      E);
12478   }
12479 
12480   case UETT_VecStep: {
12481     QualType Ty = E->getTypeOfArgument();
12482 
12483     if (Ty->isVectorType()) {
12484       unsigned n = Ty->castAs<VectorType>()->getNumElements();
12485 
12486       // The vec_step built-in functions that take a 3-component
12487       // vector return 4. (OpenCL 1.1 spec 6.11.12)
12488       if (n == 3)
12489         n = 4;
12490 
12491       return Success(n, E);
12492     } else
12493       return Success(1, E);
12494   }
12495 
12496   case UETT_SizeOf: {
12497     QualType SrcTy = E->getTypeOfArgument();
12498     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
12499     //   the result is the size of the referenced type."
12500     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
12501       SrcTy = Ref->getPointeeType();
12502 
12503     CharUnits Sizeof;
12504     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
12505       return false;
12506     return Success(Sizeof, E);
12507   }
12508   case UETT_OpenMPRequiredSimdAlign:
12509     assert(E->isArgumentType());
12510     return Success(
12511         Info.Ctx.toCharUnitsFromBits(
12512                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
12513             .getQuantity(),
12514         E);
12515   }
12516 
12517   llvm_unreachable("unknown expr/type trait");
12518 }
12519 
12520 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
12521   CharUnits Result;
12522   unsigned n = OOE->getNumComponents();
12523   if (n == 0)
12524     return Error(OOE);
12525   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
12526   for (unsigned i = 0; i != n; ++i) {
12527     OffsetOfNode ON = OOE->getComponent(i);
12528     switch (ON.getKind()) {
12529     case OffsetOfNode::Array: {
12530       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
12531       APSInt IdxResult;
12532       if (!EvaluateInteger(Idx, IdxResult, Info))
12533         return false;
12534       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
12535       if (!AT)
12536         return Error(OOE);
12537       CurrentType = AT->getElementType();
12538       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
12539       Result += IdxResult.getSExtValue() * ElementSize;
12540       break;
12541     }
12542 
12543     case OffsetOfNode::Field: {
12544       FieldDecl *MemberDecl = ON.getField();
12545       const RecordType *RT = CurrentType->getAs<RecordType>();
12546       if (!RT)
12547         return Error(OOE);
12548       RecordDecl *RD = RT->getDecl();
12549       if (RD->isInvalidDecl()) return false;
12550       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
12551       unsigned i = MemberDecl->getFieldIndex();
12552       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
12553       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
12554       CurrentType = MemberDecl->getType().getNonReferenceType();
12555       break;
12556     }
12557 
12558     case OffsetOfNode::Identifier:
12559       llvm_unreachable("dependent __builtin_offsetof");
12560 
12561     case OffsetOfNode::Base: {
12562       CXXBaseSpecifier *BaseSpec = ON.getBase();
12563       if (BaseSpec->isVirtual())
12564         return Error(OOE);
12565 
12566       // Find the layout of the class whose base we are looking into.
12567       const RecordType *RT = CurrentType->getAs<RecordType>();
12568       if (!RT)
12569         return Error(OOE);
12570       RecordDecl *RD = RT->getDecl();
12571       if (RD->isInvalidDecl()) return false;
12572       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
12573 
12574       // Find the base class itself.
12575       CurrentType = BaseSpec->getType();
12576       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
12577       if (!BaseRT)
12578         return Error(OOE);
12579 
12580       // Add the offset to the base.
12581       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
12582       break;
12583     }
12584     }
12585   }
12586   return Success(Result, OOE);
12587 }
12588 
12589 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12590   switch (E->getOpcode()) {
12591   default:
12592     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
12593     // See C99 6.6p3.
12594     return Error(E);
12595   case UO_Extension:
12596     // FIXME: Should extension allow i-c-e extension expressions in its scope?
12597     // If so, we could clear the diagnostic ID.
12598     return Visit(E->getSubExpr());
12599   case UO_Plus:
12600     // The result is just the value.
12601     return Visit(E->getSubExpr());
12602   case UO_Minus: {
12603     if (!Visit(E->getSubExpr()))
12604       return false;
12605     if (!Result.isInt()) return Error(E);
12606     const APSInt &Value = Result.getInt();
12607     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
12608         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
12609                         E->getType()))
12610       return false;
12611     return Success(-Value, E);
12612   }
12613   case UO_Not: {
12614     if (!Visit(E->getSubExpr()))
12615       return false;
12616     if (!Result.isInt()) return Error(E);
12617     return Success(~Result.getInt(), E);
12618   }
12619   case UO_LNot: {
12620     bool bres;
12621     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
12622       return false;
12623     return Success(!bres, E);
12624   }
12625   }
12626 }
12627 
12628 /// HandleCast - This is used to evaluate implicit or explicit casts where the
12629 /// result type is integer.
12630 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
12631   const Expr *SubExpr = E->getSubExpr();
12632   QualType DestType = E->getType();
12633   QualType SrcType = SubExpr->getType();
12634 
12635   switch (E->getCastKind()) {
12636   case CK_BaseToDerived:
12637   case CK_DerivedToBase:
12638   case CK_UncheckedDerivedToBase:
12639   case CK_Dynamic:
12640   case CK_ToUnion:
12641   case CK_ArrayToPointerDecay:
12642   case CK_FunctionToPointerDecay:
12643   case CK_NullToPointer:
12644   case CK_NullToMemberPointer:
12645   case CK_BaseToDerivedMemberPointer:
12646   case CK_DerivedToBaseMemberPointer:
12647   case CK_ReinterpretMemberPointer:
12648   case CK_ConstructorConversion:
12649   case CK_IntegralToPointer:
12650   case CK_ToVoid:
12651   case CK_VectorSplat:
12652   case CK_IntegralToFloating:
12653   case CK_FloatingCast:
12654   case CK_CPointerToObjCPointerCast:
12655   case CK_BlockPointerToObjCPointerCast:
12656   case CK_AnyPointerToBlockPointerCast:
12657   case CK_ObjCObjectLValueCast:
12658   case CK_FloatingRealToComplex:
12659   case CK_FloatingComplexToReal:
12660   case CK_FloatingComplexCast:
12661   case CK_FloatingComplexToIntegralComplex:
12662   case CK_IntegralRealToComplex:
12663   case CK_IntegralComplexCast:
12664   case CK_IntegralComplexToFloatingComplex:
12665   case CK_BuiltinFnToFnPtr:
12666   case CK_ZeroToOCLOpaqueType:
12667   case CK_NonAtomicToAtomic:
12668   case CK_AddressSpaceConversion:
12669   case CK_IntToOCLSampler:
12670   case CK_FixedPointCast:
12671   case CK_IntegralToFixedPoint:
12672     llvm_unreachable("invalid cast kind for integral value");
12673 
12674   case CK_BitCast:
12675   case CK_Dependent:
12676   case CK_LValueBitCast:
12677   case CK_ARCProduceObject:
12678   case CK_ARCConsumeObject:
12679   case CK_ARCReclaimReturnedObject:
12680   case CK_ARCExtendBlockObject:
12681   case CK_CopyAndAutoreleaseBlockObject:
12682     return Error(E);
12683 
12684   case CK_UserDefinedConversion:
12685   case CK_LValueToRValue:
12686   case CK_AtomicToNonAtomic:
12687   case CK_NoOp:
12688   case CK_LValueToRValueBitCast:
12689     return ExprEvaluatorBaseTy::VisitCastExpr(E);
12690 
12691   case CK_MemberPointerToBoolean:
12692   case CK_PointerToBoolean:
12693   case CK_IntegralToBoolean:
12694   case CK_FloatingToBoolean:
12695   case CK_BooleanToSignedIntegral:
12696   case CK_FloatingComplexToBoolean:
12697   case CK_IntegralComplexToBoolean: {
12698     bool BoolResult;
12699     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
12700       return false;
12701     uint64_t IntResult = BoolResult;
12702     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
12703       IntResult = (uint64_t)-1;
12704     return Success(IntResult, E);
12705   }
12706 
12707   case CK_FixedPointToIntegral: {
12708     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
12709     if (!EvaluateFixedPoint(SubExpr, Src, Info))
12710       return false;
12711     bool Overflowed;
12712     llvm::APSInt Result = Src.convertToInt(
12713         Info.Ctx.getIntWidth(DestType),
12714         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
12715     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
12716       return false;
12717     return Success(Result, E);
12718   }
12719 
12720   case CK_FixedPointToBoolean: {
12721     // Unsigned padding does not affect this.
12722     APValue Val;
12723     if (!Evaluate(Val, Info, SubExpr))
12724       return false;
12725     return Success(Val.getFixedPoint().getBoolValue(), E);
12726   }
12727 
12728   case CK_IntegralCast: {
12729     if (!Visit(SubExpr))
12730       return false;
12731 
12732     if (!Result.isInt()) {
12733       // Allow casts of address-of-label differences if they are no-ops
12734       // or narrowing.  (The narrowing case isn't actually guaranteed to
12735       // be constant-evaluatable except in some narrow cases which are hard
12736       // to detect here.  We let it through on the assumption the user knows
12737       // what they are doing.)
12738       if (Result.isAddrLabelDiff())
12739         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
12740       // Only allow casts of lvalues if they are lossless.
12741       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
12742     }
12743 
12744     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
12745                                       Result.getInt()), E);
12746   }
12747 
12748   case CK_PointerToIntegral: {
12749     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
12750 
12751     LValue LV;
12752     if (!EvaluatePointer(SubExpr, LV, Info))
12753       return false;
12754 
12755     if (LV.getLValueBase()) {
12756       // Only allow based lvalue casts if they are lossless.
12757       // FIXME: Allow a larger integer size than the pointer size, and allow
12758       // narrowing back down to pointer width in subsequent integral casts.
12759       // FIXME: Check integer type's active bits, not its type size.
12760       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
12761         return Error(E);
12762 
12763       LV.Designator.setInvalid();
12764       LV.moveInto(Result);
12765       return true;
12766     }
12767 
12768     APSInt AsInt;
12769     APValue V;
12770     LV.moveInto(V);
12771     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
12772       llvm_unreachable("Can't cast this!");
12773 
12774     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
12775   }
12776 
12777   case CK_IntegralComplexToReal: {
12778     ComplexValue C;
12779     if (!EvaluateComplex(SubExpr, C, Info))
12780       return false;
12781     return Success(C.getComplexIntReal(), E);
12782   }
12783 
12784   case CK_FloatingToIntegral: {
12785     APFloat F(0.0);
12786     if (!EvaluateFloat(SubExpr, F, Info))
12787       return false;
12788 
12789     APSInt Value;
12790     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
12791       return false;
12792     return Success(Value, E);
12793   }
12794   }
12795 
12796   llvm_unreachable("unknown cast resulting in integral value");
12797 }
12798 
12799 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
12800   if (E->getSubExpr()->getType()->isAnyComplexType()) {
12801     ComplexValue LV;
12802     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
12803       return false;
12804     if (!LV.isComplexInt())
12805       return Error(E);
12806     return Success(LV.getComplexIntReal(), E);
12807   }
12808 
12809   return Visit(E->getSubExpr());
12810 }
12811 
12812 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
12813   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
12814     ComplexValue LV;
12815     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
12816       return false;
12817     if (!LV.isComplexInt())
12818       return Error(E);
12819     return Success(LV.getComplexIntImag(), E);
12820   }
12821 
12822   VisitIgnoredValue(E->getSubExpr());
12823   return Success(0, E);
12824 }
12825 
12826 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
12827   return Success(E->getPackLength(), E);
12828 }
12829 
12830 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
12831   return Success(E->getValue(), E);
12832 }
12833 
12834 bool IntExprEvaluator::VisitConceptSpecializationExpr(
12835        const ConceptSpecializationExpr *E) {
12836   return Success(E->isSatisfied(), E);
12837 }
12838 
12839 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
12840   return Success(E->isSatisfied(), E);
12841 }
12842 
12843 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12844   switch (E->getOpcode()) {
12845     default:
12846       // Invalid unary operators
12847       return Error(E);
12848     case UO_Plus:
12849       // The result is just the value.
12850       return Visit(E->getSubExpr());
12851     case UO_Minus: {
12852       if (!Visit(E->getSubExpr())) return false;
12853       if (!Result.isFixedPoint())
12854         return Error(E);
12855       bool Overflowed;
12856       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
12857       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
12858         return false;
12859       return Success(Negated, E);
12860     }
12861     case UO_LNot: {
12862       bool bres;
12863       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
12864         return false;
12865       return Success(!bres, E);
12866     }
12867   }
12868 }
12869 
12870 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
12871   const Expr *SubExpr = E->getSubExpr();
12872   QualType DestType = E->getType();
12873   assert(DestType->isFixedPointType() &&
12874          "Expected destination type to be a fixed point type");
12875   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
12876 
12877   switch (E->getCastKind()) {
12878   case CK_FixedPointCast: {
12879     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
12880     if (!EvaluateFixedPoint(SubExpr, Src, Info))
12881       return false;
12882     bool Overflowed;
12883     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
12884     if (Overflowed) {
12885       if (Info.checkingForUndefinedBehavior())
12886         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
12887                                          diag::warn_fixedpoint_constant_overflow)
12888           << Result.toString() << E->getType();
12889       else if (!HandleOverflow(Info, E, Result, E->getType()))
12890         return false;
12891     }
12892     return Success(Result, E);
12893   }
12894   case CK_IntegralToFixedPoint: {
12895     APSInt Src;
12896     if (!EvaluateInteger(SubExpr, Src, Info))
12897       return false;
12898 
12899     bool Overflowed;
12900     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
12901         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
12902 
12903     if (Overflowed) {
12904       if (Info.checkingForUndefinedBehavior())
12905         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
12906                                          diag::warn_fixedpoint_constant_overflow)
12907           << IntResult.toString() << E->getType();
12908       else if (!HandleOverflow(Info, E, IntResult, E->getType()))
12909         return false;
12910     }
12911 
12912     return Success(IntResult, E);
12913   }
12914   case CK_NoOp:
12915   case CK_LValueToRValue:
12916     return ExprEvaluatorBaseTy::VisitCastExpr(E);
12917   default:
12918     return Error(E);
12919   }
12920 }
12921 
12922 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12923   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
12924     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12925 
12926   const Expr *LHS = E->getLHS();
12927   const Expr *RHS = E->getRHS();
12928   FixedPointSemantics ResultFXSema =
12929       Info.Ctx.getFixedPointSemantics(E->getType());
12930 
12931   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
12932   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
12933     return false;
12934   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
12935   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
12936     return false;
12937 
12938   bool OpOverflow = false, ConversionOverflow = false;
12939   APFixedPoint Result(LHSFX.getSemantics());
12940   switch (E->getOpcode()) {
12941   case BO_Add: {
12942     Result = LHSFX.add(RHSFX, &OpOverflow)
12943                   .convert(ResultFXSema, &ConversionOverflow);
12944     break;
12945   }
12946   case BO_Sub: {
12947     Result = LHSFX.sub(RHSFX, &OpOverflow)
12948                   .convert(ResultFXSema, &ConversionOverflow);
12949     break;
12950   }
12951   case BO_Mul: {
12952     Result = LHSFX.mul(RHSFX, &OpOverflow)
12953                   .convert(ResultFXSema, &ConversionOverflow);
12954     break;
12955   }
12956   case BO_Div: {
12957     Result = LHSFX.div(RHSFX, &OpOverflow)
12958                   .convert(ResultFXSema, &ConversionOverflow);
12959     break;
12960   }
12961   default:
12962     return false;
12963   }
12964   if (OpOverflow || ConversionOverflow) {
12965     if (Info.checkingForUndefinedBehavior())
12966       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
12967                                        diag::warn_fixedpoint_constant_overflow)
12968         << Result.toString() << E->getType();
12969     else if (!HandleOverflow(Info, E, Result, E->getType()))
12970       return false;
12971   }
12972   return Success(Result, E);
12973 }
12974 
12975 //===----------------------------------------------------------------------===//
12976 // Float Evaluation
12977 //===----------------------------------------------------------------------===//
12978 
12979 namespace {
12980 class FloatExprEvaluator
12981   : public ExprEvaluatorBase<FloatExprEvaluator> {
12982   APFloat &Result;
12983 public:
12984   FloatExprEvaluator(EvalInfo &info, APFloat &result)
12985     : ExprEvaluatorBaseTy(info), Result(result) {}
12986 
12987   bool Success(const APValue &V, const Expr *e) {
12988     Result = V.getFloat();
12989     return true;
12990   }
12991 
12992   bool ZeroInitialization(const Expr *E) {
12993     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
12994     return true;
12995   }
12996 
12997   bool VisitCallExpr(const CallExpr *E);
12998 
12999   bool VisitUnaryOperator(const UnaryOperator *E);
13000   bool VisitBinaryOperator(const BinaryOperator *E);
13001   bool VisitFloatingLiteral(const FloatingLiteral *E);
13002   bool VisitCastExpr(const CastExpr *E);
13003 
13004   bool VisitUnaryReal(const UnaryOperator *E);
13005   bool VisitUnaryImag(const UnaryOperator *E);
13006 
13007   // FIXME: Missing: array subscript of vector, member of vector
13008 };
13009 } // end anonymous namespace
13010 
13011 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13012   assert(E->isRValue() && E->getType()->isRealFloatingType());
13013   return FloatExprEvaluator(Info, Result).Visit(E);
13014 }
13015 
13016 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13017                                   QualType ResultTy,
13018                                   const Expr *Arg,
13019                                   bool SNaN,
13020                                   llvm::APFloat &Result) {
13021   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13022   if (!S) return false;
13023 
13024   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13025 
13026   llvm::APInt fill;
13027 
13028   // Treat empty strings as if they were zero.
13029   if (S->getString().empty())
13030     fill = llvm::APInt(32, 0);
13031   else if (S->getString().getAsInteger(0, fill))
13032     return false;
13033 
13034   if (Context.getTargetInfo().isNan2008()) {
13035     if (SNaN)
13036       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13037     else
13038       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13039   } else {
13040     // Prior to IEEE 754-2008, architectures were allowed to choose whether
13041     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13042     // a different encoding to what became a standard in 2008, and for pre-
13043     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13044     // sNaN. This is now known as "legacy NaN" encoding.
13045     if (SNaN)
13046       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13047     else
13048       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13049   }
13050 
13051   return true;
13052 }
13053 
13054 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
13055   switch (E->getBuiltinCallee()) {
13056   default:
13057     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13058 
13059   case Builtin::BI__builtin_huge_val:
13060   case Builtin::BI__builtin_huge_valf:
13061   case Builtin::BI__builtin_huge_vall:
13062   case Builtin::BI__builtin_huge_valf128:
13063   case Builtin::BI__builtin_inf:
13064   case Builtin::BI__builtin_inff:
13065   case Builtin::BI__builtin_infl:
13066   case Builtin::BI__builtin_inff128: {
13067     const llvm::fltSemantics &Sem =
13068       Info.Ctx.getFloatTypeSemantics(E->getType());
13069     Result = llvm::APFloat::getInf(Sem);
13070     return true;
13071   }
13072 
13073   case Builtin::BI__builtin_nans:
13074   case Builtin::BI__builtin_nansf:
13075   case Builtin::BI__builtin_nansl:
13076   case Builtin::BI__builtin_nansf128:
13077     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13078                                true, Result))
13079       return Error(E);
13080     return true;
13081 
13082   case Builtin::BI__builtin_nan:
13083   case Builtin::BI__builtin_nanf:
13084   case Builtin::BI__builtin_nanl:
13085   case Builtin::BI__builtin_nanf128:
13086     // If this is __builtin_nan() turn this into a nan, otherwise we
13087     // can't constant fold it.
13088     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13089                                false, Result))
13090       return Error(E);
13091     return true;
13092 
13093   case Builtin::BI__builtin_fabs:
13094   case Builtin::BI__builtin_fabsf:
13095   case Builtin::BI__builtin_fabsl:
13096   case Builtin::BI__builtin_fabsf128:
13097     if (!EvaluateFloat(E->getArg(0), Result, Info))
13098       return false;
13099 
13100     if (Result.isNegative())
13101       Result.changeSign();
13102     return true;
13103 
13104   // FIXME: Builtin::BI__builtin_powi
13105   // FIXME: Builtin::BI__builtin_powif
13106   // FIXME: Builtin::BI__builtin_powil
13107 
13108   case Builtin::BI__builtin_copysign:
13109   case Builtin::BI__builtin_copysignf:
13110   case Builtin::BI__builtin_copysignl:
13111   case Builtin::BI__builtin_copysignf128: {
13112     APFloat RHS(0.);
13113     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
13114         !EvaluateFloat(E->getArg(1), RHS, Info))
13115       return false;
13116     Result.copySign(RHS);
13117     return true;
13118   }
13119   }
13120 }
13121 
13122 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13123   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13124     ComplexValue CV;
13125     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13126       return false;
13127     Result = CV.FloatReal;
13128     return true;
13129   }
13130 
13131   return Visit(E->getSubExpr());
13132 }
13133 
13134 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13135   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13136     ComplexValue CV;
13137     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13138       return false;
13139     Result = CV.FloatImag;
13140     return true;
13141   }
13142 
13143   VisitIgnoredValue(E->getSubExpr());
13144   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
13145   Result = llvm::APFloat::getZero(Sem);
13146   return true;
13147 }
13148 
13149 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13150   switch (E->getOpcode()) {
13151   default: return Error(E);
13152   case UO_Plus:
13153     return EvaluateFloat(E->getSubExpr(), Result, Info);
13154   case UO_Minus:
13155     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
13156       return false;
13157     Result.changeSign();
13158     return true;
13159   }
13160 }
13161 
13162 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13163   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13164     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13165 
13166   APFloat RHS(0.0);
13167   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
13168   if (!LHSOK && !Info.noteFailure())
13169     return false;
13170   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
13171          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
13172 }
13173 
13174 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
13175   Result = E->getValue();
13176   return true;
13177 }
13178 
13179 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
13180   const Expr* SubExpr = E->getSubExpr();
13181 
13182   switch (E->getCastKind()) {
13183   default:
13184     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13185 
13186   case CK_IntegralToFloating: {
13187     APSInt IntResult;
13188     return EvaluateInteger(SubExpr, IntResult, Info) &&
13189            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
13190                                 E->getType(), Result);
13191   }
13192 
13193   case CK_FloatingCast: {
13194     if (!Visit(SubExpr))
13195       return false;
13196     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
13197                                   Result);
13198   }
13199 
13200   case CK_FloatingComplexToReal: {
13201     ComplexValue V;
13202     if (!EvaluateComplex(SubExpr, V, Info))
13203       return false;
13204     Result = V.getComplexFloatReal();
13205     return true;
13206   }
13207   }
13208 }
13209 
13210 //===----------------------------------------------------------------------===//
13211 // Complex Evaluation (for float and integer)
13212 //===----------------------------------------------------------------------===//
13213 
13214 namespace {
13215 class ComplexExprEvaluator
13216   : public ExprEvaluatorBase<ComplexExprEvaluator> {
13217   ComplexValue &Result;
13218 
13219 public:
13220   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
13221     : ExprEvaluatorBaseTy(info), Result(Result) {}
13222 
13223   bool Success(const APValue &V, const Expr *e) {
13224     Result.setFrom(V);
13225     return true;
13226   }
13227 
13228   bool ZeroInitialization(const Expr *E);
13229 
13230   //===--------------------------------------------------------------------===//
13231   //                            Visitor Methods
13232   //===--------------------------------------------------------------------===//
13233 
13234   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
13235   bool VisitCastExpr(const CastExpr *E);
13236   bool VisitBinaryOperator(const BinaryOperator *E);
13237   bool VisitUnaryOperator(const UnaryOperator *E);
13238   bool VisitInitListExpr(const InitListExpr *E);
13239 };
13240 } // end anonymous namespace
13241 
13242 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
13243                             EvalInfo &Info) {
13244   assert(E->isRValue() && E->getType()->isAnyComplexType());
13245   return ComplexExprEvaluator(Info, Result).Visit(E);
13246 }
13247 
13248 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
13249   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
13250   if (ElemTy->isRealFloatingType()) {
13251     Result.makeComplexFloat();
13252     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
13253     Result.FloatReal = Zero;
13254     Result.FloatImag = Zero;
13255   } else {
13256     Result.makeComplexInt();
13257     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
13258     Result.IntReal = Zero;
13259     Result.IntImag = Zero;
13260   }
13261   return true;
13262 }
13263 
13264 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
13265   const Expr* SubExpr = E->getSubExpr();
13266 
13267   if (SubExpr->getType()->isRealFloatingType()) {
13268     Result.makeComplexFloat();
13269     APFloat &Imag = Result.FloatImag;
13270     if (!EvaluateFloat(SubExpr, Imag, Info))
13271       return false;
13272 
13273     Result.FloatReal = APFloat(Imag.getSemantics());
13274     return true;
13275   } else {
13276     assert(SubExpr->getType()->isIntegerType() &&
13277            "Unexpected imaginary literal.");
13278 
13279     Result.makeComplexInt();
13280     APSInt &Imag = Result.IntImag;
13281     if (!EvaluateInteger(SubExpr, Imag, Info))
13282       return false;
13283 
13284     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
13285     return true;
13286   }
13287 }
13288 
13289 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
13290 
13291   switch (E->getCastKind()) {
13292   case CK_BitCast:
13293   case CK_BaseToDerived:
13294   case CK_DerivedToBase:
13295   case CK_UncheckedDerivedToBase:
13296   case CK_Dynamic:
13297   case CK_ToUnion:
13298   case CK_ArrayToPointerDecay:
13299   case CK_FunctionToPointerDecay:
13300   case CK_NullToPointer:
13301   case CK_NullToMemberPointer:
13302   case CK_BaseToDerivedMemberPointer:
13303   case CK_DerivedToBaseMemberPointer:
13304   case CK_MemberPointerToBoolean:
13305   case CK_ReinterpretMemberPointer:
13306   case CK_ConstructorConversion:
13307   case CK_IntegralToPointer:
13308   case CK_PointerToIntegral:
13309   case CK_PointerToBoolean:
13310   case CK_ToVoid:
13311   case CK_VectorSplat:
13312   case CK_IntegralCast:
13313   case CK_BooleanToSignedIntegral:
13314   case CK_IntegralToBoolean:
13315   case CK_IntegralToFloating:
13316   case CK_FloatingToIntegral:
13317   case CK_FloatingToBoolean:
13318   case CK_FloatingCast:
13319   case CK_CPointerToObjCPointerCast:
13320   case CK_BlockPointerToObjCPointerCast:
13321   case CK_AnyPointerToBlockPointerCast:
13322   case CK_ObjCObjectLValueCast:
13323   case CK_FloatingComplexToReal:
13324   case CK_FloatingComplexToBoolean:
13325   case CK_IntegralComplexToReal:
13326   case CK_IntegralComplexToBoolean:
13327   case CK_ARCProduceObject:
13328   case CK_ARCConsumeObject:
13329   case CK_ARCReclaimReturnedObject:
13330   case CK_ARCExtendBlockObject:
13331   case CK_CopyAndAutoreleaseBlockObject:
13332   case CK_BuiltinFnToFnPtr:
13333   case CK_ZeroToOCLOpaqueType:
13334   case CK_NonAtomicToAtomic:
13335   case CK_AddressSpaceConversion:
13336   case CK_IntToOCLSampler:
13337   case CK_FixedPointCast:
13338   case CK_FixedPointToBoolean:
13339   case CK_FixedPointToIntegral:
13340   case CK_IntegralToFixedPoint:
13341     llvm_unreachable("invalid cast kind for complex value");
13342 
13343   case CK_LValueToRValue:
13344   case CK_AtomicToNonAtomic:
13345   case CK_NoOp:
13346   case CK_LValueToRValueBitCast:
13347     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13348 
13349   case CK_Dependent:
13350   case CK_LValueBitCast:
13351   case CK_UserDefinedConversion:
13352     return Error(E);
13353 
13354   case CK_FloatingRealToComplex: {
13355     APFloat &Real = Result.FloatReal;
13356     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
13357       return false;
13358 
13359     Result.makeComplexFloat();
13360     Result.FloatImag = APFloat(Real.getSemantics());
13361     return true;
13362   }
13363 
13364   case CK_FloatingComplexCast: {
13365     if (!Visit(E->getSubExpr()))
13366       return false;
13367 
13368     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13369     QualType From
13370       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13371 
13372     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
13373            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
13374   }
13375 
13376   case CK_FloatingComplexToIntegralComplex: {
13377     if (!Visit(E->getSubExpr()))
13378       return false;
13379 
13380     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13381     QualType From
13382       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13383     Result.makeComplexInt();
13384     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
13385                                 To, Result.IntReal) &&
13386            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
13387                                 To, Result.IntImag);
13388   }
13389 
13390   case CK_IntegralRealToComplex: {
13391     APSInt &Real = Result.IntReal;
13392     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
13393       return false;
13394 
13395     Result.makeComplexInt();
13396     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
13397     return true;
13398   }
13399 
13400   case CK_IntegralComplexCast: {
13401     if (!Visit(E->getSubExpr()))
13402       return false;
13403 
13404     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13405     QualType From
13406       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13407 
13408     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
13409     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
13410     return true;
13411   }
13412 
13413   case CK_IntegralComplexToFloatingComplex: {
13414     if (!Visit(E->getSubExpr()))
13415       return false;
13416 
13417     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13418     QualType From
13419       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13420     Result.makeComplexFloat();
13421     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
13422                                 To, Result.FloatReal) &&
13423            HandleIntToFloatCast(Info, E, From, Result.IntImag,
13424                                 To, Result.FloatImag);
13425   }
13426   }
13427 
13428   llvm_unreachable("unknown cast resulting in complex value");
13429 }
13430 
13431 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13432   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13433     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13434 
13435   // Track whether the LHS or RHS is real at the type system level. When this is
13436   // the case we can simplify our evaluation strategy.
13437   bool LHSReal = false, RHSReal = false;
13438 
13439   bool LHSOK;
13440   if (E->getLHS()->getType()->isRealFloatingType()) {
13441     LHSReal = true;
13442     APFloat &Real = Result.FloatReal;
13443     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
13444     if (LHSOK) {
13445       Result.makeComplexFloat();
13446       Result.FloatImag = APFloat(Real.getSemantics());
13447     }
13448   } else {
13449     LHSOK = Visit(E->getLHS());
13450   }
13451   if (!LHSOK && !Info.noteFailure())
13452     return false;
13453 
13454   ComplexValue RHS;
13455   if (E->getRHS()->getType()->isRealFloatingType()) {
13456     RHSReal = true;
13457     APFloat &Real = RHS.FloatReal;
13458     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
13459       return false;
13460     RHS.makeComplexFloat();
13461     RHS.FloatImag = APFloat(Real.getSemantics());
13462   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
13463     return false;
13464 
13465   assert(!(LHSReal && RHSReal) &&
13466          "Cannot have both operands of a complex operation be real.");
13467   switch (E->getOpcode()) {
13468   default: return Error(E);
13469   case BO_Add:
13470     if (Result.isComplexFloat()) {
13471       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
13472                                        APFloat::rmNearestTiesToEven);
13473       if (LHSReal)
13474         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
13475       else if (!RHSReal)
13476         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
13477                                          APFloat::rmNearestTiesToEven);
13478     } else {
13479       Result.getComplexIntReal() += RHS.getComplexIntReal();
13480       Result.getComplexIntImag() += RHS.getComplexIntImag();
13481     }
13482     break;
13483   case BO_Sub:
13484     if (Result.isComplexFloat()) {
13485       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
13486                                             APFloat::rmNearestTiesToEven);
13487       if (LHSReal) {
13488         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
13489         Result.getComplexFloatImag().changeSign();
13490       } else if (!RHSReal) {
13491         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
13492                                               APFloat::rmNearestTiesToEven);
13493       }
13494     } else {
13495       Result.getComplexIntReal() -= RHS.getComplexIntReal();
13496       Result.getComplexIntImag() -= RHS.getComplexIntImag();
13497     }
13498     break;
13499   case BO_Mul:
13500     if (Result.isComplexFloat()) {
13501       // This is an implementation of complex multiplication according to the
13502       // constraints laid out in C11 Annex G. The implementation uses the
13503       // following naming scheme:
13504       //   (a + ib) * (c + id)
13505       ComplexValue LHS = Result;
13506       APFloat &A = LHS.getComplexFloatReal();
13507       APFloat &B = LHS.getComplexFloatImag();
13508       APFloat &C = RHS.getComplexFloatReal();
13509       APFloat &D = RHS.getComplexFloatImag();
13510       APFloat &ResR = Result.getComplexFloatReal();
13511       APFloat &ResI = Result.getComplexFloatImag();
13512       if (LHSReal) {
13513         assert(!RHSReal && "Cannot have two real operands for a complex op!");
13514         ResR = A * C;
13515         ResI = A * D;
13516       } else if (RHSReal) {
13517         ResR = C * A;
13518         ResI = C * B;
13519       } else {
13520         // In the fully general case, we need to handle NaNs and infinities
13521         // robustly.
13522         APFloat AC = A * C;
13523         APFloat BD = B * D;
13524         APFloat AD = A * D;
13525         APFloat BC = B * C;
13526         ResR = AC - BD;
13527         ResI = AD + BC;
13528         if (ResR.isNaN() && ResI.isNaN()) {
13529           bool Recalc = false;
13530           if (A.isInfinity() || B.isInfinity()) {
13531             A = APFloat::copySign(
13532                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
13533             B = APFloat::copySign(
13534                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
13535             if (C.isNaN())
13536               C = APFloat::copySign(APFloat(C.getSemantics()), C);
13537             if (D.isNaN())
13538               D = APFloat::copySign(APFloat(D.getSemantics()), D);
13539             Recalc = true;
13540           }
13541           if (C.isInfinity() || D.isInfinity()) {
13542             C = APFloat::copySign(
13543                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
13544             D = APFloat::copySign(
13545                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
13546             if (A.isNaN())
13547               A = APFloat::copySign(APFloat(A.getSemantics()), A);
13548             if (B.isNaN())
13549               B = APFloat::copySign(APFloat(B.getSemantics()), B);
13550             Recalc = true;
13551           }
13552           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
13553                           AD.isInfinity() || BC.isInfinity())) {
13554             if (A.isNaN())
13555               A = APFloat::copySign(APFloat(A.getSemantics()), A);
13556             if (B.isNaN())
13557               B = APFloat::copySign(APFloat(B.getSemantics()), B);
13558             if (C.isNaN())
13559               C = APFloat::copySign(APFloat(C.getSemantics()), C);
13560             if (D.isNaN())
13561               D = APFloat::copySign(APFloat(D.getSemantics()), D);
13562             Recalc = true;
13563           }
13564           if (Recalc) {
13565             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
13566             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
13567           }
13568         }
13569       }
13570     } else {
13571       ComplexValue LHS = Result;
13572       Result.getComplexIntReal() =
13573         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
13574          LHS.getComplexIntImag() * RHS.getComplexIntImag());
13575       Result.getComplexIntImag() =
13576         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
13577          LHS.getComplexIntImag() * RHS.getComplexIntReal());
13578     }
13579     break;
13580   case BO_Div:
13581     if (Result.isComplexFloat()) {
13582       // This is an implementation of complex division according to the
13583       // constraints laid out in C11 Annex G. The implementation uses the
13584       // following naming scheme:
13585       //   (a + ib) / (c + id)
13586       ComplexValue LHS = Result;
13587       APFloat &A = LHS.getComplexFloatReal();
13588       APFloat &B = LHS.getComplexFloatImag();
13589       APFloat &C = RHS.getComplexFloatReal();
13590       APFloat &D = RHS.getComplexFloatImag();
13591       APFloat &ResR = Result.getComplexFloatReal();
13592       APFloat &ResI = Result.getComplexFloatImag();
13593       if (RHSReal) {
13594         ResR = A / C;
13595         ResI = B / C;
13596       } else {
13597         if (LHSReal) {
13598           // No real optimizations we can do here, stub out with zero.
13599           B = APFloat::getZero(A.getSemantics());
13600         }
13601         int DenomLogB = 0;
13602         APFloat MaxCD = maxnum(abs(C), abs(D));
13603         if (MaxCD.isFinite()) {
13604           DenomLogB = ilogb(MaxCD);
13605           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
13606           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
13607         }
13608         APFloat Denom = C * C + D * D;
13609         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
13610                       APFloat::rmNearestTiesToEven);
13611         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
13612                       APFloat::rmNearestTiesToEven);
13613         if (ResR.isNaN() && ResI.isNaN()) {
13614           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
13615             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
13616             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
13617           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
13618                      D.isFinite()) {
13619             A = APFloat::copySign(
13620                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
13621             B = APFloat::copySign(
13622                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
13623             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
13624             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
13625           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
13626             C = APFloat::copySign(
13627                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
13628             D = APFloat::copySign(
13629                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
13630             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
13631             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
13632           }
13633         }
13634       }
13635     } else {
13636       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
13637         return Error(E, diag::note_expr_divide_by_zero);
13638 
13639       ComplexValue LHS = Result;
13640       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
13641         RHS.getComplexIntImag() * RHS.getComplexIntImag();
13642       Result.getComplexIntReal() =
13643         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
13644          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
13645       Result.getComplexIntImag() =
13646         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
13647          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
13648     }
13649     break;
13650   }
13651 
13652   return true;
13653 }
13654 
13655 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13656   // Get the operand value into 'Result'.
13657   if (!Visit(E->getSubExpr()))
13658     return false;
13659 
13660   switch (E->getOpcode()) {
13661   default:
13662     return Error(E);
13663   case UO_Extension:
13664     return true;
13665   case UO_Plus:
13666     // The result is always just the subexpr.
13667     return true;
13668   case UO_Minus:
13669     if (Result.isComplexFloat()) {
13670       Result.getComplexFloatReal().changeSign();
13671       Result.getComplexFloatImag().changeSign();
13672     }
13673     else {
13674       Result.getComplexIntReal() = -Result.getComplexIntReal();
13675       Result.getComplexIntImag() = -Result.getComplexIntImag();
13676     }
13677     return true;
13678   case UO_Not:
13679     if (Result.isComplexFloat())
13680       Result.getComplexFloatImag().changeSign();
13681     else
13682       Result.getComplexIntImag() = -Result.getComplexIntImag();
13683     return true;
13684   }
13685 }
13686 
13687 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
13688   if (E->getNumInits() == 2) {
13689     if (E->getType()->isComplexType()) {
13690       Result.makeComplexFloat();
13691       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
13692         return false;
13693       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
13694         return false;
13695     } else {
13696       Result.makeComplexInt();
13697       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
13698         return false;
13699       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
13700         return false;
13701     }
13702     return true;
13703   }
13704   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
13705 }
13706 
13707 //===----------------------------------------------------------------------===//
13708 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
13709 // implicit conversion.
13710 //===----------------------------------------------------------------------===//
13711 
13712 namespace {
13713 class AtomicExprEvaluator :
13714     public ExprEvaluatorBase<AtomicExprEvaluator> {
13715   const LValue *This;
13716   APValue &Result;
13717 public:
13718   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
13719       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
13720 
13721   bool Success(const APValue &V, const Expr *E) {
13722     Result = V;
13723     return true;
13724   }
13725 
13726   bool ZeroInitialization(const Expr *E) {
13727     ImplicitValueInitExpr VIE(
13728         E->getType()->castAs<AtomicType>()->getValueType());
13729     // For atomic-qualified class (and array) types in C++, initialize the
13730     // _Atomic-wrapped subobject directly, in-place.
13731     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
13732                 : Evaluate(Result, Info, &VIE);
13733   }
13734 
13735   bool VisitCastExpr(const CastExpr *E) {
13736     switch (E->getCastKind()) {
13737     default:
13738       return ExprEvaluatorBaseTy::VisitCastExpr(E);
13739     case CK_NonAtomicToAtomic:
13740       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
13741                   : Evaluate(Result, Info, E->getSubExpr());
13742     }
13743   }
13744 };
13745 } // end anonymous namespace
13746 
13747 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
13748                            EvalInfo &Info) {
13749   assert(E->isRValue() && E->getType()->isAtomicType());
13750   return AtomicExprEvaluator(Info, This, Result).Visit(E);
13751 }
13752 
13753 //===----------------------------------------------------------------------===//
13754 // Void expression evaluation, primarily for a cast to void on the LHS of a
13755 // comma operator
13756 //===----------------------------------------------------------------------===//
13757 
13758 namespace {
13759 class VoidExprEvaluator
13760   : public ExprEvaluatorBase<VoidExprEvaluator> {
13761 public:
13762   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
13763 
13764   bool Success(const APValue &V, const Expr *e) { return true; }
13765 
13766   bool ZeroInitialization(const Expr *E) { return true; }
13767 
13768   bool VisitCastExpr(const CastExpr *E) {
13769     switch (E->getCastKind()) {
13770     default:
13771       return ExprEvaluatorBaseTy::VisitCastExpr(E);
13772     case CK_ToVoid:
13773       VisitIgnoredValue(E->getSubExpr());
13774       return true;
13775     }
13776   }
13777 
13778   bool VisitCallExpr(const CallExpr *E) {
13779     switch (E->getBuiltinCallee()) {
13780     case Builtin::BI__assume:
13781     case Builtin::BI__builtin_assume:
13782       // The argument is not evaluated!
13783       return true;
13784 
13785     case Builtin::BI__builtin_operator_delete:
13786       return HandleOperatorDeleteCall(Info, E);
13787 
13788     default:
13789       break;
13790     }
13791 
13792     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13793   }
13794 
13795   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
13796 };
13797 } // end anonymous namespace
13798 
13799 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
13800   // We cannot speculatively evaluate a delete expression.
13801   if (Info.SpeculativeEvaluationDepth)
13802     return false;
13803 
13804   FunctionDecl *OperatorDelete = E->getOperatorDelete();
13805   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
13806     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
13807         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
13808     return false;
13809   }
13810 
13811   const Expr *Arg = E->getArgument();
13812 
13813   LValue Pointer;
13814   if (!EvaluatePointer(Arg, Pointer, Info))
13815     return false;
13816   if (Pointer.Designator.Invalid)
13817     return false;
13818 
13819   // Deleting a null pointer has no effect.
13820   if (Pointer.isNullPointer()) {
13821     // This is the only case where we need to produce an extension warning:
13822     // the only other way we can succeed is if we find a dynamic allocation,
13823     // and we will have warned when we allocated it in that case.
13824     if (!Info.getLangOpts().CPlusPlus20)
13825       Info.CCEDiag(E, diag::note_constexpr_new);
13826     return true;
13827   }
13828 
13829   Optional<DynAlloc *> Alloc = CheckDeleteKind(
13830       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
13831   if (!Alloc)
13832     return false;
13833   QualType AllocType = Pointer.Base.getDynamicAllocType();
13834 
13835   // For the non-array case, the designator must be empty if the static type
13836   // does not have a virtual destructor.
13837   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
13838       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
13839     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
13840         << Arg->getType()->getPointeeType() << AllocType;
13841     return false;
13842   }
13843 
13844   // For a class type with a virtual destructor, the selected operator delete
13845   // is the one looked up when building the destructor.
13846   if (!E->isArrayForm() && !E->isGlobalDelete()) {
13847     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
13848     if (VirtualDelete &&
13849         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
13850       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
13851           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
13852       return false;
13853     }
13854   }
13855 
13856   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
13857                          (*Alloc)->Value, AllocType))
13858     return false;
13859 
13860   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
13861     // The element was already erased. This means the destructor call also
13862     // deleted the object.
13863     // FIXME: This probably results in undefined behavior before we get this
13864     // far, and should be diagnosed elsewhere first.
13865     Info.FFDiag(E, diag::note_constexpr_double_delete);
13866     return false;
13867   }
13868 
13869   return true;
13870 }
13871 
13872 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
13873   assert(E->isRValue() && E->getType()->isVoidType());
13874   return VoidExprEvaluator(Info).Visit(E);
13875 }
13876 
13877 //===----------------------------------------------------------------------===//
13878 // Top level Expr::EvaluateAsRValue method.
13879 //===----------------------------------------------------------------------===//
13880 
13881 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
13882   // In C, function designators are not lvalues, but we evaluate them as if they
13883   // are.
13884   QualType T = E->getType();
13885   if (E->isGLValue() || T->isFunctionType()) {
13886     LValue LV;
13887     if (!EvaluateLValue(E, LV, Info))
13888       return false;
13889     LV.moveInto(Result);
13890   } else if (T->isVectorType()) {
13891     if (!EvaluateVector(E, Result, Info))
13892       return false;
13893   } else if (T->isIntegralOrEnumerationType()) {
13894     if (!IntExprEvaluator(Info, Result).Visit(E))
13895       return false;
13896   } else if (T->hasPointerRepresentation()) {
13897     LValue LV;
13898     if (!EvaluatePointer(E, LV, Info))
13899       return false;
13900     LV.moveInto(Result);
13901   } else if (T->isRealFloatingType()) {
13902     llvm::APFloat F(0.0);
13903     if (!EvaluateFloat(E, F, Info))
13904       return false;
13905     Result = APValue(F);
13906   } else if (T->isAnyComplexType()) {
13907     ComplexValue C;
13908     if (!EvaluateComplex(E, C, Info))
13909       return false;
13910     C.moveInto(Result);
13911   } else if (T->isFixedPointType()) {
13912     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
13913   } else if (T->isMemberPointerType()) {
13914     MemberPtr P;
13915     if (!EvaluateMemberPointer(E, P, Info))
13916       return false;
13917     P.moveInto(Result);
13918     return true;
13919   } else if (T->isArrayType()) {
13920     LValue LV;
13921     APValue &Value =
13922         Info.CurrentCall->createTemporary(E, T, false, LV);
13923     if (!EvaluateArray(E, LV, Value, Info))
13924       return false;
13925     Result = Value;
13926   } else if (T->isRecordType()) {
13927     LValue LV;
13928     APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV);
13929     if (!EvaluateRecord(E, LV, Value, Info))
13930       return false;
13931     Result = Value;
13932   } else if (T->isVoidType()) {
13933     if (!Info.getLangOpts().CPlusPlus11)
13934       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
13935         << E->getType();
13936     if (!EvaluateVoid(E, Info))
13937       return false;
13938   } else if (T->isAtomicType()) {
13939     QualType Unqual = T.getAtomicUnqualifiedType();
13940     if (Unqual->isArrayType() || Unqual->isRecordType()) {
13941       LValue LV;
13942       APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV);
13943       if (!EvaluateAtomic(E, &LV, Value, Info))
13944         return false;
13945     } else {
13946       if (!EvaluateAtomic(E, nullptr, Result, Info))
13947         return false;
13948     }
13949   } else if (Info.getLangOpts().CPlusPlus11) {
13950     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
13951     return false;
13952   } else {
13953     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
13954     return false;
13955   }
13956 
13957   return true;
13958 }
13959 
13960 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
13961 /// cases, the in-place evaluation is essential, since later initializers for
13962 /// an object can indirectly refer to subobjects which were initialized earlier.
13963 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
13964                             const Expr *E, bool AllowNonLiteralTypes) {
13965   assert(!E->isValueDependent());
13966 
13967   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
13968     return false;
13969 
13970   if (E->isRValue()) {
13971     // Evaluate arrays and record types in-place, so that later initializers can
13972     // refer to earlier-initialized members of the object.
13973     QualType T = E->getType();
13974     if (T->isArrayType())
13975       return EvaluateArray(E, This, Result, Info);
13976     else if (T->isRecordType())
13977       return EvaluateRecord(E, This, Result, Info);
13978     else if (T->isAtomicType()) {
13979       QualType Unqual = T.getAtomicUnqualifiedType();
13980       if (Unqual->isArrayType() || Unqual->isRecordType())
13981         return EvaluateAtomic(E, &This, Result, Info);
13982     }
13983   }
13984 
13985   // For any other type, in-place evaluation is unimportant.
13986   return Evaluate(Result, Info, E);
13987 }
13988 
13989 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
13990 /// lvalue-to-rvalue cast if it is an lvalue.
13991 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
13992   if (Info.EnableNewConstInterp) {
13993     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
13994       return false;
13995   } else {
13996     if (E->getType().isNull())
13997       return false;
13998 
13999     if (!CheckLiteralType(Info, E))
14000       return false;
14001 
14002     if (!::Evaluate(Result, Info, E))
14003       return false;
14004 
14005     if (E->isGLValue()) {
14006       LValue LV;
14007       LV.setFrom(Info.Ctx, Result);
14008       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14009         return false;
14010     }
14011   }
14012 
14013   // Check this core constant expression is a constant expression.
14014   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) &&
14015          CheckMemoryLeaks(Info);
14016 }
14017 
14018 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
14019                                  const ASTContext &Ctx, bool &IsConst) {
14020   // Fast-path evaluations of integer literals, since we sometimes see files
14021   // containing vast quantities of these.
14022   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
14023     Result.Val = APValue(APSInt(L->getValue(),
14024                                 L->getType()->isUnsignedIntegerType()));
14025     IsConst = true;
14026     return true;
14027   }
14028 
14029   // This case should be rare, but we need to check it before we check on
14030   // the type below.
14031   if (Exp->getType().isNull()) {
14032     IsConst = false;
14033     return true;
14034   }
14035 
14036   // FIXME: Evaluating values of large array and record types can cause
14037   // performance problems. Only do so in C++11 for now.
14038   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
14039                           Exp->getType()->isRecordType()) &&
14040       !Ctx.getLangOpts().CPlusPlus11) {
14041     IsConst = false;
14042     return true;
14043   }
14044   return false;
14045 }
14046 
14047 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
14048                                       Expr::SideEffectsKind SEK) {
14049   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
14050          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
14051 }
14052 
14053 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
14054                              const ASTContext &Ctx, EvalInfo &Info) {
14055   bool IsConst;
14056   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
14057     return IsConst;
14058 
14059   return EvaluateAsRValue(Info, E, Result.Val);
14060 }
14061 
14062 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
14063                           const ASTContext &Ctx,
14064                           Expr::SideEffectsKind AllowSideEffects,
14065                           EvalInfo &Info) {
14066   if (!E->getType()->isIntegralOrEnumerationType())
14067     return false;
14068 
14069   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
14070       !ExprResult.Val.isInt() ||
14071       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14072     return false;
14073 
14074   return true;
14075 }
14076 
14077 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
14078                                  const ASTContext &Ctx,
14079                                  Expr::SideEffectsKind AllowSideEffects,
14080                                  EvalInfo &Info) {
14081   if (!E->getType()->isFixedPointType())
14082     return false;
14083 
14084   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
14085     return false;
14086 
14087   if (!ExprResult.Val.isFixedPoint() ||
14088       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14089     return false;
14090 
14091   return true;
14092 }
14093 
14094 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
14095 /// any crazy technique (that has nothing to do with language standards) that
14096 /// we want to.  If this function returns true, it returns the folded constant
14097 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
14098 /// will be applied to the result.
14099 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
14100                             bool InConstantContext) const {
14101   assert(!isValueDependent() &&
14102          "Expression evaluator can't be called on a dependent expression.");
14103   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14104   Info.InConstantContext = InConstantContext;
14105   return ::EvaluateAsRValue(this, Result, Ctx, Info);
14106 }
14107 
14108 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
14109                                       bool InConstantContext) const {
14110   assert(!isValueDependent() &&
14111          "Expression evaluator can't be called on a dependent expression.");
14112   EvalResult Scratch;
14113   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
14114          HandleConversionToBool(Scratch.Val, Result);
14115 }
14116 
14117 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
14118                          SideEffectsKind AllowSideEffects,
14119                          bool InConstantContext) const {
14120   assert(!isValueDependent() &&
14121          "Expression evaluator can't be called on a dependent expression.");
14122   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14123   Info.InConstantContext = InConstantContext;
14124   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
14125 }
14126 
14127 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
14128                                 SideEffectsKind AllowSideEffects,
14129                                 bool InConstantContext) const {
14130   assert(!isValueDependent() &&
14131          "Expression evaluator can't be called on a dependent expression.");
14132   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14133   Info.InConstantContext = InConstantContext;
14134   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
14135 }
14136 
14137 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
14138                            SideEffectsKind AllowSideEffects,
14139                            bool InConstantContext) const {
14140   assert(!isValueDependent() &&
14141          "Expression evaluator can't be called on a dependent expression.");
14142 
14143   if (!getType()->isRealFloatingType())
14144     return false;
14145 
14146   EvalResult ExprResult;
14147   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
14148       !ExprResult.Val.isFloat() ||
14149       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14150     return false;
14151 
14152   Result = ExprResult.Val.getFloat();
14153   return true;
14154 }
14155 
14156 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
14157                             bool InConstantContext) const {
14158   assert(!isValueDependent() &&
14159          "Expression evaluator can't be called on a dependent expression.");
14160 
14161   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
14162   Info.InConstantContext = InConstantContext;
14163   LValue LV;
14164   CheckedTemporaries CheckedTemps;
14165   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
14166       Result.HasSideEffects ||
14167       !CheckLValueConstantExpression(Info, getExprLoc(),
14168                                      Ctx.getLValueReferenceType(getType()), LV,
14169                                      Expr::EvaluateForCodeGen, CheckedTemps))
14170     return false;
14171 
14172   LV.moveInto(Result.Val);
14173   return true;
14174 }
14175 
14176 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
14177                                   const ASTContext &Ctx, bool InPlace) const {
14178   assert(!isValueDependent() &&
14179          "Expression evaluator can't be called on a dependent expression.");
14180 
14181   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
14182   EvalInfo Info(Ctx, Result, EM);
14183   Info.InConstantContext = true;
14184 
14185   if (InPlace) {
14186     Info.setEvaluatingDecl(this, Result.Val);
14187     LValue LVal;
14188     LVal.set(this);
14189     if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
14190         Result.HasSideEffects)
14191       return false;
14192   } else if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects)
14193     return false;
14194 
14195   if (!Info.discardCleanups())
14196     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14197 
14198   return CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
14199                                  Result.Val, Usage) &&
14200          CheckMemoryLeaks(Info);
14201 }
14202 
14203 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
14204                                  const VarDecl *VD,
14205                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
14206   assert(!isValueDependent() &&
14207          "Expression evaluator can't be called on a dependent expression.");
14208 
14209   // FIXME: Evaluating initializers for large array and record types can cause
14210   // performance problems. Only do so in C++11 for now.
14211   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
14212       !Ctx.getLangOpts().CPlusPlus11)
14213     return false;
14214 
14215   Expr::EvalStatus EStatus;
14216   EStatus.Diag = &Notes;
14217 
14218   EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
14219                                       ? EvalInfo::EM_ConstantExpression
14220                                       : EvalInfo::EM_ConstantFold);
14221   Info.setEvaluatingDecl(VD, Value);
14222   Info.InConstantContext = true;
14223 
14224   SourceLocation DeclLoc = VD->getLocation();
14225   QualType DeclTy = VD->getType();
14226 
14227   if (Info.EnableNewConstInterp) {
14228     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
14229     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
14230       return false;
14231   } else {
14232     LValue LVal;
14233     LVal.set(VD);
14234 
14235     if (!EvaluateInPlace(Value, Info, LVal, this,
14236                          /*AllowNonLiteralTypes=*/true) ||
14237         EStatus.HasSideEffects)
14238       return false;
14239 
14240     // At this point, any lifetime-extended temporaries are completely
14241     // initialized.
14242     Info.performLifetimeExtension();
14243 
14244     if (!Info.discardCleanups())
14245       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14246   }
14247   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) &&
14248          CheckMemoryLeaks(Info);
14249 }
14250 
14251 bool VarDecl::evaluateDestruction(
14252     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
14253   Expr::EvalStatus EStatus;
14254   EStatus.Diag = &Notes;
14255 
14256   // Make a copy of the value for the destructor to mutate, if we know it.
14257   // Otherwise, treat the value as default-initialized; if the destructor works
14258   // anyway, then the destruction is constant (and must be essentially empty).
14259   APValue DestroyedValue;
14260   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
14261     DestroyedValue = *getEvaluatedValue();
14262   else if (!getDefaultInitValue(getType(), DestroyedValue))
14263     return false;
14264 
14265   EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression);
14266   Info.setEvaluatingDecl(this, DestroyedValue,
14267                          EvalInfo::EvaluatingDeclKind::Dtor);
14268   Info.InConstantContext = true;
14269 
14270   SourceLocation DeclLoc = getLocation();
14271   QualType DeclTy = getType();
14272 
14273   LValue LVal;
14274   LVal.set(this);
14275 
14276   if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) ||
14277       EStatus.HasSideEffects)
14278     return false;
14279 
14280   if (!Info.discardCleanups())
14281     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14282 
14283   ensureEvaluatedStmt()->HasConstantDestruction = true;
14284   return true;
14285 }
14286 
14287 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
14288 /// constant folded, but discard the result.
14289 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
14290   assert(!isValueDependent() &&
14291          "Expression evaluator can't be called on a dependent expression.");
14292 
14293   EvalResult Result;
14294   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
14295          !hasUnacceptableSideEffect(Result, SEK);
14296 }
14297 
14298 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
14299                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14300   assert(!isValueDependent() &&
14301          "Expression evaluator can't be called on a dependent expression.");
14302 
14303   EvalResult EVResult;
14304   EVResult.Diag = Diag;
14305   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14306   Info.InConstantContext = true;
14307 
14308   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
14309   (void)Result;
14310   assert(Result && "Could not evaluate expression");
14311   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14312 
14313   return EVResult.Val.getInt();
14314 }
14315 
14316 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
14317     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14318   assert(!isValueDependent() &&
14319          "Expression evaluator can't be called on a dependent expression.");
14320 
14321   EvalResult EVResult;
14322   EVResult.Diag = Diag;
14323   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14324   Info.InConstantContext = true;
14325   Info.CheckingForUndefinedBehavior = true;
14326 
14327   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
14328   (void)Result;
14329   assert(Result && "Could not evaluate expression");
14330   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14331 
14332   return EVResult.Val.getInt();
14333 }
14334 
14335 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
14336   assert(!isValueDependent() &&
14337          "Expression evaluator can't be called on a dependent expression.");
14338 
14339   bool IsConst;
14340   EvalResult EVResult;
14341   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
14342     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14343     Info.CheckingForUndefinedBehavior = true;
14344     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
14345   }
14346 }
14347 
14348 bool Expr::EvalResult::isGlobalLValue() const {
14349   assert(Val.isLValue());
14350   return IsGlobalLValue(Val.getLValueBase());
14351 }
14352 
14353 
14354 /// isIntegerConstantExpr - this recursive routine will test if an expression is
14355 /// an integer constant expression.
14356 
14357 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
14358 /// comma, etc
14359 
14360 // CheckICE - This function does the fundamental ICE checking: the returned
14361 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
14362 // and a (possibly null) SourceLocation indicating the location of the problem.
14363 //
14364 // Note that to reduce code duplication, this helper does no evaluation
14365 // itself; the caller checks whether the expression is evaluatable, and
14366 // in the rare cases where CheckICE actually cares about the evaluated
14367 // value, it calls into Evaluate.
14368 
14369 namespace {
14370 
14371 enum ICEKind {
14372   /// This expression is an ICE.
14373   IK_ICE,
14374   /// This expression is not an ICE, but if it isn't evaluated, it's
14375   /// a legal subexpression for an ICE. This return value is used to handle
14376   /// the comma operator in C99 mode, and non-constant subexpressions.
14377   IK_ICEIfUnevaluated,
14378   /// This expression is not an ICE, and is not a legal subexpression for one.
14379   IK_NotICE
14380 };
14381 
14382 struct ICEDiag {
14383   ICEKind Kind;
14384   SourceLocation Loc;
14385 
14386   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
14387 };
14388 
14389 }
14390 
14391 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
14392 
14393 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
14394 
14395 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
14396   Expr::EvalResult EVResult;
14397   Expr::EvalStatus Status;
14398   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
14399 
14400   Info.InConstantContext = true;
14401   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
14402       !EVResult.Val.isInt())
14403     return ICEDiag(IK_NotICE, E->getBeginLoc());
14404 
14405   return NoDiag();
14406 }
14407 
14408 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
14409   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
14410   if (!E->getType()->isIntegralOrEnumerationType())
14411     return ICEDiag(IK_NotICE, E->getBeginLoc());
14412 
14413   switch (E->getStmtClass()) {
14414 #define ABSTRACT_STMT(Node)
14415 #define STMT(Node, Base) case Expr::Node##Class:
14416 #define EXPR(Node, Base)
14417 #include "clang/AST/StmtNodes.inc"
14418   case Expr::PredefinedExprClass:
14419   case Expr::FloatingLiteralClass:
14420   case Expr::ImaginaryLiteralClass:
14421   case Expr::StringLiteralClass:
14422   case Expr::ArraySubscriptExprClass:
14423   case Expr::MatrixSubscriptExprClass:
14424   case Expr::OMPArraySectionExprClass:
14425   case Expr::OMPArrayShapingExprClass:
14426   case Expr::OMPIteratorExprClass:
14427   case Expr::MemberExprClass:
14428   case Expr::CompoundAssignOperatorClass:
14429   case Expr::CompoundLiteralExprClass:
14430   case Expr::ExtVectorElementExprClass:
14431   case Expr::DesignatedInitExprClass:
14432   case Expr::ArrayInitLoopExprClass:
14433   case Expr::ArrayInitIndexExprClass:
14434   case Expr::NoInitExprClass:
14435   case Expr::DesignatedInitUpdateExprClass:
14436   case Expr::ImplicitValueInitExprClass:
14437   case Expr::ParenListExprClass:
14438   case Expr::VAArgExprClass:
14439   case Expr::AddrLabelExprClass:
14440   case Expr::StmtExprClass:
14441   case Expr::CXXMemberCallExprClass:
14442   case Expr::CUDAKernelCallExprClass:
14443   case Expr::CXXAddrspaceCastExprClass:
14444   case Expr::CXXDynamicCastExprClass:
14445   case Expr::CXXTypeidExprClass:
14446   case Expr::CXXUuidofExprClass:
14447   case Expr::MSPropertyRefExprClass:
14448   case Expr::MSPropertySubscriptExprClass:
14449   case Expr::CXXNullPtrLiteralExprClass:
14450   case Expr::UserDefinedLiteralClass:
14451   case Expr::CXXThisExprClass:
14452   case Expr::CXXThrowExprClass:
14453   case Expr::CXXNewExprClass:
14454   case Expr::CXXDeleteExprClass:
14455   case Expr::CXXPseudoDestructorExprClass:
14456   case Expr::UnresolvedLookupExprClass:
14457   case Expr::TypoExprClass:
14458   case Expr::RecoveryExprClass:
14459   case Expr::DependentScopeDeclRefExprClass:
14460   case Expr::CXXConstructExprClass:
14461   case Expr::CXXInheritedCtorInitExprClass:
14462   case Expr::CXXStdInitializerListExprClass:
14463   case Expr::CXXBindTemporaryExprClass:
14464   case Expr::ExprWithCleanupsClass:
14465   case Expr::CXXTemporaryObjectExprClass:
14466   case Expr::CXXUnresolvedConstructExprClass:
14467   case Expr::CXXDependentScopeMemberExprClass:
14468   case Expr::UnresolvedMemberExprClass:
14469   case Expr::ObjCStringLiteralClass:
14470   case Expr::ObjCBoxedExprClass:
14471   case Expr::ObjCArrayLiteralClass:
14472   case Expr::ObjCDictionaryLiteralClass:
14473   case Expr::ObjCEncodeExprClass:
14474   case Expr::ObjCMessageExprClass:
14475   case Expr::ObjCSelectorExprClass:
14476   case Expr::ObjCProtocolExprClass:
14477   case Expr::ObjCIvarRefExprClass:
14478   case Expr::ObjCPropertyRefExprClass:
14479   case Expr::ObjCSubscriptRefExprClass:
14480   case Expr::ObjCIsaExprClass:
14481   case Expr::ObjCAvailabilityCheckExprClass:
14482   case Expr::ShuffleVectorExprClass:
14483   case Expr::ConvertVectorExprClass:
14484   case Expr::BlockExprClass:
14485   case Expr::NoStmtClass:
14486   case Expr::OpaqueValueExprClass:
14487   case Expr::PackExpansionExprClass:
14488   case Expr::SubstNonTypeTemplateParmPackExprClass:
14489   case Expr::FunctionParmPackExprClass:
14490   case Expr::AsTypeExprClass:
14491   case Expr::ObjCIndirectCopyRestoreExprClass:
14492   case Expr::MaterializeTemporaryExprClass:
14493   case Expr::PseudoObjectExprClass:
14494   case Expr::AtomicExprClass:
14495   case Expr::LambdaExprClass:
14496   case Expr::CXXFoldExprClass:
14497   case Expr::CoawaitExprClass:
14498   case Expr::DependentCoawaitExprClass:
14499   case Expr::CoyieldExprClass:
14500     return ICEDiag(IK_NotICE, E->getBeginLoc());
14501 
14502   case Expr::InitListExprClass: {
14503     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
14504     // form "T x = { a };" is equivalent to "T x = a;".
14505     // Unless we're initializing a reference, T is a scalar as it is known to be
14506     // of integral or enumeration type.
14507     if (E->isRValue())
14508       if (cast<InitListExpr>(E)->getNumInits() == 1)
14509         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
14510     return ICEDiag(IK_NotICE, E->getBeginLoc());
14511   }
14512 
14513   case Expr::SizeOfPackExprClass:
14514   case Expr::GNUNullExprClass:
14515   case Expr::SourceLocExprClass:
14516     return NoDiag();
14517 
14518   case Expr::SubstNonTypeTemplateParmExprClass:
14519     return
14520       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
14521 
14522   case Expr::ConstantExprClass:
14523     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
14524 
14525   case Expr::ParenExprClass:
14526     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
14527   case Expr::GenericSelectionExprClass:
14528     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
14529   case Expr::IntegerLiteralClass:
14530   case Expr::FixedPointLiteralClass:
14531   case Expr::CharacterLiteralClass:
14532   case Expr::ObjCBoolLiteralExprClass:
14533   case Expr::CXXBoolLiteralExprClass:
14534   case Expr::CXXScalarValueInitExprClass:
14535   case Expr::TypeTraitExprClass:
14536   case Expr::ConceptSpecializationExprClass:
14537   case Expr::RequiresExprClass:
14538   case Expr::ArrayTypeTraitExprClass:
14539   case Expr::ExpressionTraitExprClass:
14540   case Expr::CXXNoexceptExprClass:
14541     return NoDiag();
14542   case Expr::CallExprClass:
14543   case Expr::CXXOperatorCallExprClass: {
14544     // C99 6.6/3 allows function calls within unevaluated subexpressions of
14545     // constant expressions, but they can never be ICEs because an ICE cannot
14546     // contain an operand of (pointer to) function type.
14547     const CallExpr *CE = cast<CallExpr>(E);
14548     if (CE->getBuiltinCallee())
14549       return CheckEvalInICE(E, Ctx);
14550     return ICEDiag(IK_NotICE, E->getBeginLoc());
14551   }
14552   case Expr::CXXRewrittenBinaryOperatorClass:
14553     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
14554                     Ctx);
14555   case Expr::DeclRefExprClass: {
14556     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
14557       return NoDiag();
14558     const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
14559     if (Ctx.getLangOpts().CPlusPlus &&
14560         D && IsConstNonVolatile(D->getType())) {
14561       // Parameter variables are never constants.  Without this check,
14562       // getAnyInitializer() can find a default argument, which leads
14563       // to chaos.
14564       if (isa<ParmVarDecl>(D))
14565         return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14566 
14567       // C++ 7.1.5.1p2
14568       //   A variable of non-volatile const-qualified integral or enumeration
14569       //   type initialized by an ICE can be used in ICEs.
14570       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
14571         if (!Dcl->getType()->isIntegralOrEnumerationType())
14572           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14573 
14574         const VarDecl *VD;
14575         // Look for a declaration of this variable that has an initializer, and
14576         // check whether it is an ICE.
14577         if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
14578           return NoDiag();
14579         else
14580           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14581       }
14582     }
14583     return ICEDiag(IK_NotICE, E->getBeginLoc());
14584   }
14585   case Expr::UnaryOperatorClass: {
14586     const UnaryOperator *Exp = cast<UnaryOperator>(E);
14587     switch (Exp->getOpcode()) {
14588     case UO_PostInc:
14589     case UO_PostDec:
14590     case UO_PreInc:
14591     case UO_PreDec:
14592     case UO_AddrOf:
14593     case UO_Deref:
14594     case UO_Coawait:
14595       // C99 6.6/3 allows increment and decrement within unevaluated
14596       // subexpressions of constant expressions, but they can never be ICEs
14597       // because an ICE cannot contain an lvalue operand.
14598       return ICEDiag(IK_NotICE, E->getBeginLoc());
14599     case UO_Extension:
14600     case UO_LNot:
14601     case UO_Plus:
14602     case UO_Minus:
14603     case UO_Not:
14604     case UO_Real:
14605     case UO_Imag:
14606       return CheckICE(Exp->getSubExpr(), Ctx);
14607     }
14608     llvm_unreachable("invalid unary operator class");
14609   }
14610   case Expr::OffsetOfExprClass: {
14611     // Note that per C99, offsetof must be an ICE. And AFAIK, using
14612     // EvaluateAsRValue matches the proposed gcc behavior for cases like
14613     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
14614     // compliance: we should warn earlier for offsetof expressions with
14615     // array subscripts that aren't ICEs, and if the array subscripts
14616     // are ICEs, the value of the offsetof must be an integer constant.
14617     return CheckEvalInICE(E, Ctx);
14618   }
14619   case Expr::UnaryExprOrTypeTraitExprClass: {
14620     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
14621     if ((Exp->getKind() ==  UETT_SizeOf) &&
14622         Exp->getTypeOfArgument()->isVariableArrayType())
14623       return ICEDiag(IK_NotICE, E->getBeginLoc());
14624     return NoDiag();
14625   }
14626   case Expr::BinaryOperatorClass: {
14627     const BinaryOperator *Exp = cast<BinaryOperator>(E);
14628     switch (Exp->getOpcode()) {
14629     case BO_PtrMemD:
14630     case BO_PtrMemI:
14631     case BO_Assign:
14632     case BO_MulAssign:
14633     case BO_DivAssign:
14634     case BO_RemAssign:
14635     case BO_AddAssign:
14636     case BO_SubAssign:
14637     case BO_ShlAssign:
14638     case BO_ShrAssign:
14639     case BO_AndAssign:
14640     case BO_XorAssign:
14641     case BO_OrAssign:
14642       // C99 6.6/3 allows assignments within unevaluated subexpressions of
14643       // constant expressions, but they can never be ICEs because an ICE cannot
14644       // contain an lvalue operand.
14645       return ICEDiag(IK_NotICE, E->getBeginLoc());
14646 
14647     case BO_Mul:
14648     case BO_Div:
14649     case BO_Rem:
14650     case BO_Add:
14651     case BO_Sub:
14652     case BO_Shl:
14653     case BO_Shr:
14654     case BO_LT:
14655     case BO_GT:
14656     case BO_LE:
14657     case BO_GE:
14658     case BO_EQ:
14659     case BO_NE:
14660     case BO_And:
14661     case BO_Xor:
14662     case BO_Or:
14663     case BO_Comma:
14664     case BO_Cmp: {
14665       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
14666       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
14667       if (Exp->getOpcode() == BO_Div ||
14668           Exp->getOpcode() == BO_Rem) {
14669         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
14670         // we don't evaluate one.
14671         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
14672           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
14673           if (REval == 0)
14674             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14675           if (REval.isSigned() && REval.isAllOnesValue()) {
14676             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
14677             if (LEval.isMinSignedValue())
14678               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14679           }
14680         }
14681       }
14682       if (Exp->getOpcode() == BO_Comma) {
14683         if (Ctx.getLangOpts().C99) {
14684           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
14685           // if it isn't evaluated.
14686           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
14687             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14688         } else {
14689           // In both C89 and C++, commas in ICEs are illegal.
14690           return ICEDiag(IK_NotICE, E->getBeginLoc());
14691         }
14692       }
14693       return Worst(LHSResult, RHSResult);
14694     }
14695     case BO_LAnd:
14696     case BO_LOr: {
14697       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
14698       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
14699       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
14700         // Rare case where the RHS has a comma "side-effect"; we need
14701         // to actually check the condition to see whether the side
14702         // with the comma is evaluated.
14703         if ((Exp->getOpcode() == BO_LAnd) !=
14704             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
14705           return RHSResult;
14706         return NoDiag();
14707       }
14708 
14709       return Worst(LHSResult, RHSResult);
14710     }
14711     }
14712     llvm_unreachable("invalid binary operator kind");
14713   }
14714   case Expr::ImplicitCastExprClass:
14715   case Expr::CStyleCastExprClass:
14716   case Expr::CXXFunctionalCastExprClass:
14717   case Expr::CXXStaticCastExprClass:
14718   case Expr::CXXReinterpretCastExprClass:
14719   case Expr::CXXConstCastExprClass:
14720   case Expr::ObjCBridgedCastExprClass: {
14721     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
14722     if (isa<ExplicitCastExpr>(E)) {
14723       if (const FloatingLiteral *FL
14724             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
14725         unsigned DestWidth = Ctx.getIntWidth(E->getType());
14726         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
14727         APSInt IgnoredVal(DestWidth, !DestSigned);
14728         bool Ignored;
14729         // If the value does not fit in the destination type, the behavior is
14730         // undefined, so we are not required to treat it as a constant
14731         // expression.
14732         if (FL->getValue().convertToInteger(IgnoredVal,
14733                                             llvm::APFloat::rmTowardZero,
14734                                             &Ignored) & APFloat::opInvalidOp)
14735           return ICEDiag(IK_NotICE, E->getBeginLoc());
14736         return NoDiag();
14737       }
14738     }
14739     switch (cast<CastExpr>(E)->getCastKind()) {
14740     case CK_LValueToRValue:
14741     case CK_AtomicToNonAtomic:
14742     case CK_NonAtomicToAtomic:
14743     case CK_NoOp:
14744     case CK_IntegralToBoolean:
14745     case CK_IntegralCast:
14746       return CheckICE(SubExpr, Ctx);
14747     default:
14748       return ICEDiag(IK_NotICE, E->getBeginLoc());
14749     }
14750   }
14751   case Expr::BinaryConditionalOperatorClass: {
14752     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
14753     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
14754     if (CommonResult.Kind == IK_NotICE) return CommonResult;
14755     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
14756     if (FalseResult.Kind == IK_NotICE) return FalseResult;
14757     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
14758     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
14759         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
14760     return FalseResult;
14761   }
14762   case Expr::ConditionalOperatorClass: {
14763     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
14764     // If the condition (ignoring parens) is a __builtin_constant_p call,
14765     // then only the true side is actually considered in an integer constant
14766     // expression, and it is fully evaluated.  This is an important GNU
14767     // extension.  See GCC PR38377 for discussion.
14768     if (const CallExpr *CallCE
14769         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
14770       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
14771         return CheckEvalInICE(E, Ctx);
14772     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
14773     if (CondResult.Kind == IK_NotICE)
14774       return CondResult;
14775 
14776     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
14777     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
14778 
14779     if (TrueResult.Kind == IK_NotICE)
14780       return TrueResult;
14781     if (FalseResult.Kind == IK_NotICE)
14782       return FalseResult;
14783     if (CondResult.Kind == IK_ICEIfUnevaluated)
14784       return CondResult;
14785     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
14786       return NoDiag();
14787     // Rare case where the diagnostics depend on which side is evaluated
14788     // Note that if we get here, CondResult is 0, and at least one of
14789     // TrueResult and FalseResult is non-zero.
14790     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
14791       return FalseResult;
14792     return TrueResult;
14793   }
14794   case Expr::CXXDefaultArgExprClass:
14795     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
14796   case Expr::CXXDefaultInitExprClass:
14797     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
14798   case Expr::ChooseExprClass: {
14799     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
14800   }
14801   case Expr::BuiltinBitCastExprClass: {
14802     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
14803       return ICEDiag(IK_NotICE, E->getBeginLoc());
14804     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
14805   }
14806   }
14807 
14808   llvm_unreachable("Invalid StmtClass!");
14809 }
14810 
14811 /// Evaluate an expression as a C++11 integral constant expression.
14812 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
14813                                                     const Expr *E,
14814                                                     llvm::APSInt *Value,
14815                                                     SourceLocation *Loc) {
14816   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14817     if (Loc) *Loc = E->getExprLoc();
14818     return false;
14819   }
14820 
14821   APValue Result;
14822   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
14823     return false;
14824 
14825   if (!Result.isInt()) {
14826     if (Loc) *Loc = E->getExprLoc();
14827     return false;
14828   }
14829 
14830   if (Value) *Value = Result.getInt();
14831   return true;
14832 }
14833 
14834 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
14835                                  SourceLocation *Loc) const {
14836   assert(!isValueDependent() &&
14837          "Expression evaluator can't be called on a dependent expression.");
14838 
14839   if (Ctx.getLangOpts().CPlusPlus11)
14840     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
14841 
14842   ICEDiag D = CheckICE(this, Ctx);
14843   if (D.Kind != IK_ICE) {
14844     if (Loc) *Loc = D.Loc;
14845     return false;
14846   }
14847   return true;
14848 }
14849 
14850 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
14851                                  SourceLocation *Loc, bool isEvaluated) const {
14852   assert(!isValueDependent() &&
14853          "Expression evaluator can't be called on a dependent expression.");
14854 
14855   if (Ctx.getLangOpts().CPlusPlus11)
14856     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
14857 
14858   if (!isIntegerConstantExpr(Ctx, Loc))
14859     return false;
14860 
14861   // The only possible side-effects here are due to UB discovered in the
14862   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
14863   // required to treat the expression as an ICE, so we produce the folded
14864   // value.
14865   EvalResult ExprResult;
14866   Expr::EvalStatus Status;
14867   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
14868   Info.InConstantContext = true;
14869 
14870   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
14871     llvm_unreachable("ICE cannot be evaluated!");
14872 
14873   Value = ExprResult.Val.getInt();
14874   return true;
14875 }
14876 
14877 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
14878   assert(!isValueDependent() &&
14879          "Expression evaluator can't be called on a dependent expression.");
14880 
14881   return CheckICE(this, Ctx).Kind == IK_ICE;
14882 }
14883 
14884 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
14885                                SourceLocation *Loc) const {
14886   assert(!isValueDependent() &&
14887          "Expression evaluator can't be called on a dependent expression.");
14888 
14889   // We support this checking in C++98 mode in order to diagnose compatibility
14890   // issues.
14891   assert(Ctx.getLangOpts().CPlusPlus);
14892 
14893   // Build evaluation settings.
14894   Expr::EvalStatus Status;
14895   SmallVector<PartialDiagnosticAt, 8> Diags;
14896   Status.Diag = &Diags;
14897   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
14898 
14899   APValue Scratch;
14900   bool IsConstExpr =
14901       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
14902       // FIXME: We don't produce a diagnostic for this, but the callers that
14903       // call us on arbitrary full-expressions should generally not care.
14904       Info.discardCleanups() && !Status.HasSideEffects;
14905 
14906   if (!Diags.empty()) {
14907     IsConstExpr = false;
14908     if (Loc) *Loc = Diags[0].first;
14909   } else if (!IsConstExpr) {
14910     // FIXME: This shouldn't happen.
14911     if (Loc) *Loc = getExprLoc();
14912   }
14913 
14914   return IsConstExpr;
14915 }
14916 
14917 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
14918                                     const FunctionDecl *Callee,
14919                                     ArrayRef<const Expr*> Args,
14920                                     const Expr *This) const {
14921   assert(!isValueDependent() &&
14922          "Expression evaluator can't be called on a dependent expression.");
14923 
14924   Expr::EvalStatus Status;
14925   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
14926   Info.InConstantContext = true;
14927 
14928   LValue ThisVal;
14929   const LValue *ThisPtr = nullptr;
14930   if (This) {
14931 #ifndef NDEBUG
14932     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
14933     assert(MD && "Don't provide `this` for non-methods.");
14934     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
14935 #endif
14936     if (!This->isValueDependent() &&
14937         EvaluateObjectArgument(Info, This, ThisVal) &&
14938         !Info.EvalStatus.HasSideEffects)
14939       ThisPtr = &ThisVal;
14940 
14941     // Ignore any side-effects from a failed evaluation. This is safe because
14942     // they can't interfere with any other argument evaluation.
14943     Info.EvalStatus.HasSideEffects = false;
14944   }
14945 
14946   ArgVector ArgValues(Args.size());
14947   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
14948        I != E; ++I) {
14949     if ((*I)->isValueDependent() ||
14950         !Evaluate(ArgValues[I - Args.begin()], Info, *I) ||
14951         Info.EvalStatus.HasSideEffects)
14952       // If evaluation fails, throw away the argument entirely.
14953       ArgValues[I - Args.begin()] = APValue();
14954 
14955     // Ignore any side-effects from a failed evaluation. This is safe because
14956     // they can't interfere with any other argument evaluation.
14957     Info.EvalStatus.HasSideEffects = false;
14958   }
14959 
14960   // Parameter cleanups happen in the caller and are not part of this
14961   // evaluation.
14962   Info.discardCleanups();
14963   Info.EvalStatus.HasSideEffects = false;
14964 
14965   // Build fake call to Callee.
14966   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
14967                        ArgValues.data());
14968   // FIXME: Missing ExprWithCleanups in enable_if conditions?
14969   FullExpressionRAII Scope(Info);
14970   return Evaluate(Value, Info, this) && Scope.destroy() &&
14971          !Info.EvalStatus.HasSideEffects;
14972 }
14973 
14974 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
14975                                    SmallVectorImpl<
14976                                      PartialDiagnosticAt> &Diags) {
14977   // FIXME: It would be useful to check constexpr function templates, but at the
14978   // moment the constant expression evaluator cannot cope with the non-rigorous
14979   // ASTs which we build for dependent expressions.
14980   if (FD->isDependentContext())
14981     return true;
14982 
14983   // Bail out if a constexpr constructor has an initializer that contains an
14984   // error. We deliberately don't produce a diagnostic, as we have produced a
14985   // relevant diagnostic when parsing the error initializer.
14986   if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14987     for (const auto *InitExpr : Ctor->inits()) {
14988       if (InitExpr->getInit() && InitExpr->getInit()->containsErrors())
14989         return false;
14990     }
14991   }
14992   Expr::EvalStatus Status;
14993   Status.Diag = &Diags;
14994 
14995   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
14996   Info.InConstantContext = true;
14997   Info.CheckingPotentialConstantExpression = true;
14998 
14999   // The constexpr VM attempts to compile all methods to bytecode here.
15000   if (Info.EnableNewConstInterp) {
15001     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
15002     return Diags.empty();
15003   }
15004 
15005   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
15006   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
15007 
15008   // Fabricate an arbitrary expression on the stack and pretend that it
15009   // is a temporary being used as the 'this' pointer.
15010   LValue This;
15011   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
15012   This.set({&VIE, Info.CurrentCall->Index});
15013 
15014   ArrayRef<const Expr*> Args;
15015 
15016   APValue Scratch;
15017   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
15018     // Evaluate the call as a constant initializer, to allow the construction
15019     // of objects of non-literal types.
15020     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
15021     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
15022   } else {
15023     SourceLocation Loc = FD->getLocation();
15024     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
15025                        Args, FD->getBody(), Info, Scratch, nullptr);
15026   }
15027 
15028   return Diags.empty();
15029 }
15030 
15031 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
15032                                               const FunctionDecl *FD,
15033                                               SmallVectorImpl<
15034                                                 PartialDiagnosticAt> &Diags) {
15035   assert(!E->isValueDependent() &&
15036          "Expression evaluator can't be called on a dependent expression.");
15037 
15038   Expr::EvalStatus Status;
15039   Status.Diag = &Diags;
15040 
15041   EvalInfo Info(FD->getASTContext(), Status,
15042                 EvalInfo::EM_ConstantExpressionUnevaluated);
15043   Info.InConstantContext = true;
15044   Info.CheckingPotentialConstantExpression = true;
15045 
15046   // Fabricate a call stack frame to give the arguments a plausible cover story.
15047   ArrayRef<const Expr*> Args;
15048   ArgVector ArgValues(0);
15049   bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
15050   (void)Success;
15051   assert(Success &&
15052          "Failed to set up arguments for potential constant evaluation");
15053   CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
15054 
15055   APValue ResultScratch;
15056   Evaluate(ResultScratch, Info, E);
15057   return Diags.empty();
15058 }
15059 
15060 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
15061                                  unsigned Type) const {
15062   if (!getType()->isPointerType())
15063     return false;
15064 
15065   Expr::EvalStatus Status;
15066   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15067   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
15068 }
15069