1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Expr constant evaluator.
10 //
11 // Constant expression evaluation produces four main results:
12 //
13 //  * A success/failure flag indicating whether constant folding was successful.
14 //    This is the 'bool' return value used by most of the code in this file. A
15 //    'false' return value indicates that constant folding has failed, and any
16 //    appropriate diagnostic has already been produced.
17 //
18 //  * An evaluated result, valid only if constant folding has not failed.
19 //
20 //  * A flag indicating if evaluation encountered (unevaluated) side-effects.
21 //    These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22 //    where it is possible to determine the evaluated result regardless.
23 //
24 //  * A set of notes indicating why the evaluation was not a constant expression
25 //    (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26 //    too, why the expression could not be folded.
27 //
28 // If we are checking for a potential constant expression, failure to constant
29 // fold a potential constant sub-expression will be indicated by a 'false'
30 // return value (the expression could not be folded) and no diagnostic (the
31 // expression is not necessarily non-constant).
32 //
33 //===----------------------------------------------------------------------===//
34 
35 #include "Interp/Context.h"
36 #include "Interp/Frame.h"
37 #include "Interp/State.h"
38 #include "clang/AST/APValue.h"
39 #include "clang/AST/ASTContext.h"
40 #include "clang/AST/ASTDiagnostic.h"
41 #include "clang/AST/ASTLambda.h"
42 #include "clang/AST/Attr.h"
43 #include "clang/AST/CXXInheritance.h"
44 #include "clang/AST/CharUnits.h"
45 #include "clang/AST/CurrentSourceLocExprScope.h"
46 #include "clang/AST/Expr.h"
47 #include "clang/AST/OSLog.h"
48 #include "clang/AST/OptionalDiagnostic.h"
49 #include "clang/AST/RecordLayout.h"
50 #include "clang/AST/StmtVisitor.h"
51 #include "clang/AST/TypeLoc.h"
52 #include "clang/Basic/Builtins.h"
53 #include "clang/Basic/TargetInfo.h"
54 #include "llvm/ADT/APFixedPoint.h"
55 #include "llvm/ADT/Optional.h"
56 #include "llvm/ADT/SmallBitVector.h"
57 #include "llvm/Support/Debug.h"
58 #include "llvm/Support/SaveAndRestore.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include <cstring>
61 #include <functional>
62 
63 #define DEBUG_TYPE "exprconstant"
64 
65 using namespace clang;
66 using llvm::APFixedPoint;
67 using llvm::APInt;
68 using llvm::APSInt;
69 using llvm::APFloat;
70 using llvm::FixedPointSemantics;
71 using llvm::Optional;
72 
73 namespace {
74   struct LValue;
75   class CallStackFrame;
76   class EvalInfo;
77 
78   using SourceLocExprScopeGuard =
79       CurrentSourceLocExprScope::SourceLocExprScopeGuard;
80 
81   static QualType getType(APValue::LValueBase B) {
82     if (!B) return QualType();
83     if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
84       // FIXME: It's unclear where we're supposed to take the type from, and
85       // this actually matters for arrays of unknown bound. Eg:
86       //
87       // extern int arr[]; void f() { extern int arr[3]; };
88       // constexpr int *p = &arr[1]; // valid?
89       //
90       // For now, we take the array bound from the most recent declaration.
91       for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
92            Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
93         QualType T = Redecl->getType();
94         if (!T->isIncompleteArrayType())
95           return T;
96       }
97       return D->getType();
98     }
99 
100     if (B.is<TypeInfoLValue>())
101       return B.getTypeInfoType();
102 
103     if (B.is<DynamicAllocLValue>())
104       return B.getDynamicAllocType();
105 
106     const Expr *Base = B.get<const Expr*>();
107 
108     // For a materialized temporary, the type of the temporary we materialized
109     // may not be the type of the expression.
110     if (const MaterializeTemporaryExpr *MTE =
111             dyn_cast<MaterializeTemporaryExpr>(Base)) {
112       SmallVector<const Expr *, 2> CommaLHSs;
113       SmallVector<SubobjectAdjustment, 2> Adjustments;
114       const Expr *Temp = MTE->getSubExpr();
115       const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
116                                                                Adjustments);
117       // Keep any cv-qualifiers from the reference if we generated a temporary
118       // for it directly. Otherwise use the type after adjustment.
119       if (!Adjustments.empty())
120         return Inner->getType();
121     }
122 
123     return Base->getType();
124   }
125 
126   /// Get an LValue path entry, which is known to not be an array index, as a
127   /// field declaration.
128   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
129     return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
130   }
131   /// Get an LValue path entry, which is known to not be an array index, as a
132   /// base class declaration.
133   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
134     return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
135   }
136   /// Determine whether this LValue path entry for a base class names a virtual
137   /// base class.
138   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
139     return E.getAsBaseOrMember().getInt();
140   }
141 
142   /// Given an expression, determine the type used to store the result of
143   /// evaluating that expression.
144   static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
145     if (E->isRValue())
146       return E->getType();
147     return Ctx.getLValueReferenceType(E->getType());
148   }
149 
150   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
151   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
152     const FunctionDecl *Callee = CE->getDirectCallee();
153     return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
154   }
155 
156   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
157   /// This will look through a single cast.
158   ///
159   /// Returns null if we couldn't unwrap a function with alloc_size.
160   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
161     if (!E->getType()->isPointerType())
162       return nullptr;
163 
164     E = E->IgnoreParens();
165     // If we're doing a variable assignment from e.g. malloc(N), there will
166     // probably be a cast of some kind. In exotic cases, we might also see a
167     // top-level ExprWithCleanups. Ignore them either way.
168     if (const auto *FE = dyn_cast<FullExpr>(E))
169       E = FE->getSubExpr()->IgnoreParens();
170 
171     if (const auto *Cast = dyn_cast<CastExpr>(E))
172       E = Cast->getSubExpr()->IgnoreParens();
173 
174     if (const auto *CE = dyn_cast<CallExpr>(E))
175       return getAllocSizeAttr(CE) ? CE : nullptr;
176     return nullptr;
177   }
178 
179   /// Determines whether or not the given Base contains a call to a function
180   /// with the alloc_size attribute.
181   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
182     const auto *E = Base.dyn_cast<const Expr *>();
183     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
184   }
185 
186   /// The bound to claim that an array of unknown bound has.
187   /// The value in MostDerivedArraySize is undefined in this case. So, set it
188   /// to an arbitrary value that's likely to loudly break things if it's used.
189   static const uint64_t AssumedSizeForUnsizedArray =
190       std::numeric_limits<uint64_t>::max() / 2;
191 
192   /// Determines if an LValue with the given LValueBase will have an unsized
193   /// array in its designator.
194   /// Find the path length and type of the most-derived subobject in the given
195   /// path, and find the size of the containing array, if any.
196   static unsigned
197   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
198                            ArrayRef<APValue::LValuePathEntry> Path,
199                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
200                            bool &FirstEntryIsUnsizedArray) {
201     // This only accepts LValueBases from APValues, and APValues don't support
202     // arrays that lack size info.
203     assert(!isBaseAnAllocSizeCall(Base) &&
204            "Unsized arrays shouldn't appear here");
205     unsigned MostDerivedLength = 0;
206     Type = getType(Base);
207 
208     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
209       if (Type->isArrayType()) {
210         const ArrayType *AT = Ctx.getAsArrayType(Type);
211         Type = AT->getElementType();
212         MostDerivedLength = I + 1;
213         IsArray = true;
214 
215         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
216           ArraySize = CAT->getSize().getZExtValue();
217         } else {
218           assert(I == 0 && "unexpected unsized array designator");
219           FirstEntryIsUnsizedArray = true;
220           ArraySize = AssumedSizeForUnsizedArray;
221         }
222       } else if (Type->isAnyComplexType()) {
223         const ComplexType *CT = Type->castAs<ComplexType>();
224         Type = CT->getElementType();
225         ArraySize = 2;
226         MostDerivedLength = I + 1;
227         IsArray = true;
228       } else if (const FieldDecl *FD = getAsField(Path[I])) {
229         Type = FD->getType();
230         ArraySize = 0;
231         MostDerivedLength = I + 1;
232         IsArray = false;
233       } else {
234         // Path[I] describes a base class.
235         ArraySize = 0;
236         IsArray = false;
237       }
238     }
239     return MostDerivedLength;
240   }
241 
242   /// A path from a glvalue to a subobject of that glvalue.
243   struct SubobjectDesignator {
244     /// True if the subobject was named in a manner not supported by C++11. Such
245     /// lvalues can still be folded, but they are not core constant expressions
246     /// and we cannot perform lvalue-to-rvalue conversions on them.
247     unsigned Invalid : 1;
248 
249     /// Is this a pointer one past the end of an object?
250     unsigned IsOnePastTheEnd : 1;
251 
252     /// Indicator of whether the first entry is an unsized array.
253     unsigned FirstEntryIsAnUnsizedArray : 1;
254 
255     /// Indicator of whether the most-derived object is an array element.
256     unsigned MostDerivedIsArrayElement : 1;
257 
258     /// The length of the path to the most-derived object of which this is a
259     /// subobject.
260     unsigned MostDerivedPathLength : 28;
261 
262     /// The size of the array of which the most-derived object is an element.
263     /// This will always be 0 if the most-derived object is not an array
264     /// element. 0 is not an indicator of whether or not the most-derived object
265     /// is an array, however, because 0-length arrays are allowed.
266     ///
267     /// If the current array is an unsized array, the value of this is
268     /// undefined.
269     uint64_t MostDerivedArraySize;
270 
271     /// The type of the most derived object referred to by this address.
272     QualType MostDerivedType;
273 
274     typedef APValue::LValuePathEntry PathEntry;
275 
276     /// The entries on the path from the glvalue to the designated subobject.
277     SmallVector<PathEntry, 8> Entries;
278 
279     SubobjectDesignator() : Invalid(true) {}
280 
281     explicit SubobjectDesignator(QualType T)
282         : Invalid(false), IsOnePastTheEnd(false),
283           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
284           MostDerivedPathLength(0), MostDerivedArraySize(0),
285           MostDerivedType(T) {}
286 
287     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
288         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
289           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
290           MostDerivedPathLength(0), MostDerivedArraySize(0) {
291       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
292       if (!Invalid) {
293         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
294         ArrayRef<PathEntry> VEntries = V.getLValuePath();
295         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
296         if (V.getLValueBase()) {
297           bool IsArray = false;
298           bool FirstIsUnsizedArray = false;
299           MostDerivedPathLength = findMostDerivedSubobject(
300               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
301               MostDerivedType, IsArray, FirstIsUnsizedArray);
302           MostDerivedIsArrayElement = IsArray;
303           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
304         }
305       }
306     }
307 
308     void truncate(ASTContext &Ctx, APValue::LValueBase Base,
309                   unsigned NewLength) {
310       if (Invalid)
311         return;
312 
313       assert(Base && "cannot truncate path for null pointer");
314       assert(NewLength <= Entries.size() && "not a truncation");
315 
316       if (NewLength == Entries.size())
317         return;
318       Entries.resize(NewLength);
319 
320       bool IsArray = false;
321       bool FirstIsUnsizedArray = false;
322       MostDerivedPathLength = findMostDerivedSubobject(
323           Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
324           FirstIsUnsizedArray);
325       MostDerivedIsArrayElement = IsArray;
326       FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
327     }
328 
329     void setInvalid() {
330       Invalid = true;
331       Entries.clear();
332     }
333 
334     /// Determine whether the most derived subobject is an array without a
335     /// known bound.
336     bool isMostDerivedAnUnsizedArray() const {
337       assert(!Invalid && "Calling this makes no sense on invalid designators");
338       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
339     }
340 
341     /// Determine what the most derived array's size is. Results in an assertion
342     /// failure if the most derived array lacks a size.
343     uint64_t getMostDerivedArraySize() const {
344       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
345       return MostDerivedArraySize;
346     }
347 
348     /// Determine whether this is a one-past-the-end pointer.
349     bool isOnePastTheEnd() const {
350       assert(!Invalid);
351       if (IsOnePastTheEnd)
352         return true;
353       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
354           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
355               MostDerivedArraySize)
356         return true;
357       return false;
358     }
359 
360     /// Get the range of valid index adjustments in the form
361     ///   {maximum value that can be subtracted from this pointer,
362     ///    maximum value that can be added to this pointer}
363     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
364       if (Invalid || isMostDerivedAnUnsizedArray())
365         return {0, 0};
366 
367       // [expr.add]p4: For the purposes of these operators, a pointer to a
368       // nonarray object behaves the same as a pointer to the first element of
369       // an array of length one with the type of the object as its element type.
370       bool IsArray = MostDerivedPathLength == Entries.size() &&
371                      MostDerivedIsArrayElement;
372       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
373                                     : (uint64_t)IsOnePastTheEnd;
374       uint64_t ArraySize =
375           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
376       return {ArrayIndex, ArraySize - ArrayIndex};
377     }
378 
379     /// Check that this refers to a valid subobject.
380     bool isValidSubobject() const {
381       if (Invalid)
382         return false;
383       return !isOnePastTheEnd();
384     }
385     /// Check that this refers to a valid subobject, and if not, produce a
386     /// relevant diagnostic and set the designator as invalid.
387     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
388 
389     /// Get the type of the designated object.
390     QualType getType(ASTContext &Ctx) const {
391       assert(!Invalid && "invalid designator has no subobject type");
392       return MostDerivedPathLength == Entries.size()
393                  ? MostDerivedType
394                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
395     }
396 
397     /// Update this designator to refer to the first element within this array.
398     void addArrayUnchecked(const ConstantArrayType *CAT) {
399       Entries.push_back(PathEntry::ArrayIndex(0));
400 
401       // This is a most-derived object.
402       MostDerivedType = CAT->getElementType();
403       MostDerivedIsArrayElement = true;
404       MostDerivedArraySize = CAT->getSize().getZExtValue();
405       MostDerivedPathLength = Entries.size();
406     }
407     /// Update this designator to refer to the first element within the array of
408     /// elements of type T. This is an array of unknown size.
409     void addUnsizedArrayUnchecked(QualType ElemTy) {
410       Entries.push_back(PathEntry::ArrayIndex(0));
411 
412       MostDerivedType = ElemTy;
413       MostDerivedIsArrayElement = true;
414       // The value in MostDerivedArraySize is undefined in this case. So, set it
415       // to an arbitrary value that's likely to loudly break things if it's
416       // used.
417       MostDerivedArraySize = AssumedSizeForUnsizedArray;
418       MostDerivedPathLength = Entries.size();
419     }
420     /// Update this designator to refer to the given base or member of this
421     /// object.
422     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
423       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
424 
425       // If this isn't a base class, it's a new most-derived object.
426       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
427         MostDerivedType = FD->getType();
428         MostDerivedIsArrayElement = false;
429         MostDerivedArraySize = 0;
430         MostDerivedPathLength = Entries.size();
431       }
432     }
433     /// Update this designator to refer to the given complex component.
434     void addComplexUnchecked(QualType EltTy, bool Imag) {
435       Entries.push_back(PathEntry::ArrayIndex(Imag));
436 
437       // This is technically a most-derived object, though in practice this
438       // is unlikely to matter.
439       MostDerivedType = EltTy;
440       MostDerivedIsArrayElement = true;
441       MostDerivedArraySize = 2;
442       MostDerivedPathLength = Entries.size();
443     }
444     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
445     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
446                                    const APSInt &N);
447     /// Add N to the address of this subobject.
448     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
449       if (Invalid || !N) return;
450       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
451       if (isMostDerivedAnUnsizedArray()) {
452         diagnoseUnsizedArrayPointerArithmetic(Info, E);
453         // Can't verify -- trust that the user is doing the right thing (or if
454         // not, trust that the caller will catch the bad behavior).
455         // FIXME: Should we reject if this overflows, at least?
456         Entries.back() = PathEntry::ArrayIndex(
457             Entries.back().getAsArrayIndex() + TruncatedN);
458         return;
459       }
460 
461       // [expr.add]p4: For the purposes of these operators, a pointer to a
462       // nonarray object behaves the same as a pointer to the first element of
463       // an array of length one with the type of the object as its element type.
464       bool IsArray = MostDerivedPathLength == Entries.size() &&
465                      MostDerivedIsArrayElement;
466       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
467                                     : (uint64_t)IsOnePastTheEnd;
468       uint64_t ArraySize =
469           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
470 
471       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
472         // Calculate the actual index in a wide enough type, so we can include
473         // it in the note.
474         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
475         (llvm::APInt&)N += ArrayIndex;
476         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
477         diagnosePointerArithmetic(Info, E, N);
478         setInvalid();
479         return;
480       }
481 
482       ArrayIndex += TruncatedN;
483       assert(ArrayIndex <= ArraySize &&
484              "bounds check succeeded for out-of-bounds index");
485 
486       if (IsArray)
487         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
488       else
489         IsOnePastTheEnd = (ArrayIndex != 0);
490     }
491   };
492 
493   /// A stack frame in the constexpr call stack.
494   class CallStackFrame : public interp::Frame {
495   public:
496     EvalInfo &Info;
497 
498     /// Parent - The caller of this stack frame.
499     CallStackFrame *Caller;
500 
501     /// Callee - The function which was called.
502     const FunctionDecl *Callee;
503 
504     /// This - The binding for the this pointer in this call, if any.
505     const LValue *This;
506 
507     /// Arguments - Parameter bindings for this function call, indexed by
508     /// parameters' function scope indices.
509     APValue *Arguments;
510 
511     /// Source location information about the default argument or default
512     /// initializer expression we're evaluating, if any.
513     CurrentSourceLocExprScope CurSourceLocExprScope;
514 
515     // Note that we intentionally use std::map here so that references to
516     // values are stable.
517     typedef std::pair<const void *, unsigned> MapKeyTy;
518     typedef std::map<MapKeyTy, APValue> MapTy;
519     /// Temporaries - Temporary lvalues materialized within this stack frame.
520     MapTy Temporaries;
521 
522     /// CallLoc - The location of the call expression for this call.
523     SourceLocation CallLoc;
524 
525     /// Index - The call index of this call.
526     unsigned Index;
527 
528     /// The stack of integers for tracking version numbers for temporaries.
529     SmallVector<unsigned, 2> TempVersionStack = {1};
530     unsigned CurTempVersion = TempVersionStack.back();
531 
532     unsigned getTempVersion() const { return TempVersionStack.back(); }
533 
534     void pushTempVersion() {
535       TempVersionStack.push_back(++CurTempVersion);
536     }
537 
538     void popTempVersion() {
539       TempVersionStack.pop_back();
540     }
541 
542     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
543     // on the overall stack usage of deeply-recursing constexpr evaluations.
544     // (We should cache this map rather than recomputing it repeatedly.)
545     // But let's try this and see how it goes; we can look into caching the map
546     // as a later change.
547 
548     /// LambdaCaptureFields - Mapping from captured variables/this to
549     /// corresponding data members in the closure class.
550     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
551     FieldDecl *LambdaThisCaptureField;
552 
553     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
554                    const FunctionDecl *Callee, const LValue *This,
555                    APValue *Arguments);
556     ~CallStackFrame();
557 
558     // Return the temporary for Key whose version number is Version.
559     APValue *getTemporary(const void *Key, unsigned Version) {
560       MapKeyTy KV(Key, Version);
561       auto LB = Temporaries.lower_bound(KV);
562       if (LB != Temporaries.end() && LB->first == KV)
563         return &LB->second;
564       // Pair (Key,Version) wasn't found in the map. Check that no elements
565       // in the map have 'Key' as their key.
566       assert((LB == Temporaries.end() || LB->first.first != Key) &&
567              (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
568              "Element with key 'Key' found in map");
569       return nullptr;
570     }
571 
572     // Return the current temporary for Key in the map.
573     APValue *getCurrentTemporary(const void *Key) {
574       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
575       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
576         return &std::prev(UB)->second;
577       return nullptr;
578     }
579 
580     // Return the version number of the current temporary for Key.
581     unsigned getCurrentTemporaryVersion(const void *Key) const {
582       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
583       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
584         return std::prev(UB)->first.second;
585       return 0;
586     }
587 
588     /// Allocate storage for an object of type T in this stack frame.
589     /// Populates LV with a handle to the created object. Key identifies
590     /// the temporary within the stack frame, and must not be reused without
591     /// bumping the temporary version number.
592     template<typename KeyT>
593     APValue &createTemporary(const KeyT *Key, QualType T,
594                              bool IsLifetimeExtended, LValue &LV);
595 
596     void describe(llvm::raw_ostream &OS) override;
597 
598     Frame *getCaller() const override { return Caller; }
599     SourceLocation getCallLocation() const override { return CallLoc; }
600     const FunctionDecl *getCallee() const override { return Callee; }
601 
602     bool isStdFunction() const {
603       for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
604         if (DC->isStdNamespace())
605           return true;
606       return false;
607     }
608   };
609 
610   /// Temporarily override 'this'.
611   class ThisOverrideRAII {
612   public:
613     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
614         : Frame(Frame), OldThis(Frame.This) {
615       if (Enable)
616         Frame.This = NewThis;
617     }
618     ~ThisOverrideRAII() {
619       Frame.This = OldThis;
620     }
621   private:
622     CallStackFrame &Frame;
623     const LValue *OldThis;
624   };
625 }
626 
627 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
628                               const LValue &This, QualType ThisType);
629 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
630                               APValue::LValueBase LVBase, APValue &Value,
631                               QualType T);
632 
633 namespace {
634   /// A cleanup, and a flag indicating whether it is lifetime-extended.
635   class Cleanup {
636     llvm::PointerIntPair<APValue*, 1, bool> Value;
637     APValue::LValueBase Base;
638     QualType T;
639 
640   public:
641     Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
642             bool IsLifetimeExtended)
643         : Value(Val, IsLifetimeExtended), Base(Base), T(T) {}
644 
645     bool isLifetimeExtended() const { return Value.getInt(); }
646     bool endLifetime(EvalInfo &Info, bool RunDestructors) {
647       if (RunDestructors) {
648         SourceLocation Loc;
649         if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
650           Loc = VD->getLocation();
651         else if (const Expr *E = Base.dyn_cast<const Expr*>())
652           Loc = E->getExprLoc();
653         return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
654       }
655       *Value.getPointer() = APValue();
656       return true;
657     }
658 
659     bool hasSideEffect() {
660       return T.isDestructedType();
661     }
662   };
663 
664   /// A reference to an object whose construction we are currently evaluating.
665   struct ObjectUnderConstruction {
666     APValue::LValueBase Base;
667     ArrayRef<APValue::LValuePathEntry> Path;
668     friend bool operator==(const ObjectUnderConstruction &LHS,
669                            const ObjectUnderConstruction &RHS) {
670       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
671     }
672     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
673       return llvm::hash_combine(Obj.Base, Obj.Path);
674     }
675   };
676   enum class ConstructionPhase {
677     None,
678     Bases,
679     AfterBases,
680     AfterFields,
681     Destroying,
682     DestroyingBases
683   };
684 }
685 
686 namespace llvm {
687 template<> struct DenseMapInfo<ObjectUnderConstruction> {
688   using Base = DenseMapInfo<APValue::LValueBase>;
689   static ObjectUnderConstruction getEmptyKey() {
690     return {Base::getEmptyKey(), {}}; }
691   static ObjectUnderConstruction getTombstoneKey() {
692     return {Base::getTombstoneKey(), {}};
693   }
694   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
695     return hash_value(Object);
696   }
697   static bool isEqual(const ObjectUnderConstruction &LHS,
698                       const ObjectUnderConstruction &RHS) {
699     return LHS == RHS;
700   }
701 };
702 }
703 
704 namespace {
705   /// A dynamically-allocated heap object.
706   struct DynAlloc {
707     /// The value of this heap-allocated object.
708     APValue Value;
709     /// The allocating expression; used for diagnostics. Either a CXXNewExpr
710     /// or a CallExpr (the latter is for direct calls to operator new inside
711     /// std::allocator<T>::allocate).
712     const Expr *AllocExpr = nullptr;
713 
714     enum Kind {
715       New,
716       ArrayNew,
717       StdAllocator
718     };
719 
720     /// Get the kind of the allocation. This must match between allocation
721     /// and deallocation.
722     Kind getKind() const {
723       if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
724         return NE->isArray() ? ArrayNew : New;
725       assert(isa<CallExpr>(AllocExpr));
726       return StdAllocator;
727     }
728   };
729 
730   struct DynAllocOrder {
731     bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
732       return L.getIndex() < R.getIndex();
733     }
734   };
735 
736   /// EvalInfo - This is a private struct used by the evaluator to capture
737   /// information about a subexpression as it is folded.  It retains information
738   /// about the AST context, but also maintains information about the folded
739   /// expression.
740   ///
741   /// If an expression could be evaluated, it is still possible it is not a C
742   /// "integer constant expression" or constant expression.  If not, this struct
743   /// captures information about how and why not.
744   ///
745   /// One bit of information passed *into* the request for constant folding
746   /// indicates whether the subexpression is "evaluated" or not according to C
747   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
748   /// evaluate the expression regardless of what the RHS is, but C only allows
749   /// certain things in certain situations.
750   class EvalInfo : public interp::State {
751   public:
752     ASTContext &Ctx;
753 
754     /// EvalStatus - Contains information about the evaluation.
755     Expr::EvalStatus &EvalStatus;
756 
757     /// CurrentCall - The top of the constexpr call stack.
758     CallStackFrame *CurrentCall;
759 
760     /// CallStackDepth - The number of calls in the call stack right now.
761     unsigned CallStackDepth;
762 
763     /// NextCallIndex - The next call index to assign.
764     unsigned NextCallIndex;
765 
766     /// StepsLeft - The remaining number of evaluation steps we're permitted
767     /// to perform. This is essentially a limit for the number of statements
768     /// we will evaluate.
769     unsigned StepsLeft;
770 
771     /// Enable the experimental new constant interpreter. If an expression is
772     /// not supported by the interpreter, an error is triggered.
773     bool EnableNewConstInterp;
774 
775     /// BottomFrame - The frame in which evaluation started. This must be
776     /// initialized after CurrentCall and CallStackDepth.
777     CallStackFrame BottomFrame;
778 
779     /// A stack of values whose lifetimes end at the end of some surrounding
780     /// evaluation frame.
781     llvm::SmallVector<Cleanup, 16> CleanupStack;
782 
783     /// EvaluatingDecl - This is the declaration whose initializer is being
784     /// evaluated, if any.
785     APValue::LValueBase EvaluatingDecl;
786 
787     enum class EvaluatingDeclKind {
788       None,
789       /// We're evaluating the construction of EvaluatingDecl.
790       Ctor,
791       /// We're evaluating the destruction of EvaluatingDecl.
792       Dtor,
793     };
794     EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
795 
796     /// EvaluatingDeclValue - This is the value being constructed for the
797     /// declaration whose initializer is being evaluated, if any.
798     APValue *EvaluatingDeclValue;
799 
800     /// Set of objects that are currently being constructed.
801     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
802         ObjectsUnderConstruction;
803 
804     /// Current heap allocations, along with the location where each was
805     /// allocated. We use std::map here because we need stable addresses
806     /// for the stored APValues.
807     std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
808 
809     /// The number of heap allocations performed so far in this evaluation.
810     unsigned NumHeapAllocs = 0;
811 
812     struct EvaluatingConstructorRAII {
813       EvalInfo &EI;
814       ObjectUnderConstruction Object;
815       bool DidInsert;
816       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
817                                 bool HasBases)
818           : EI(EI), Object(Object) {
819         DidInsert =
820             EI.ObjectsUnderConstruction
821                 .insert({Object, HasBases ? ConstructionPhase::Bases
822                                           : ConstructionPhase::AfterBases})
823                 .second;
824       }
825       void finishedConstructingBases() {
826         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
827       }
828       void finishedConstructingFields() {
829         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
830       }
831       ~EvaluatingConstructorRAII() {
832         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
833       }
834     };
835 
836     struct EvaluatingDestructorRAII {
837       EvalInfo &EI;
838       ObjectUnderConstruction Object;
839       bool DidInsert;
840       EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
841           : EI(EI), Object(Object) {
842         DidInsert = EI.ObjectsUnderConstruction
843                         .insert({Object, ConstructionPhase::Destroying})
844                         .second;
845       }
846       void startedDestroyingBases() {
847         EI.ObjectsUnderConstruction[Object] =
848             ConstructionPhase::DestroyingBases;
849       }
850       ~EvaluatingDestructorRAII() {
851         if (DidInsert)
852           EI.ObjectsUnderConstruction.erase(Object);
853       }
854     };
855 
856     ConstructionPhase
857     isEvaluatingCtorDtor(APValue::LValueBase Base,
858                          ArrayRef<APValue::LValuePathEntry> Path) {
859       return ObjectsUnderConstruction.lookup({Base, Path});
860     }
861 
862     /// If we're currently speculatively evaluating, the outermost call stack
863     /// depth at which we can mutate state, otherwise 0.
864     unsigned SpeculativeEvaluationDepth = 0;
865 
866     /// The current array initialization index, if we're performing array
867     /// initialization.
868     uint64_t ArrayInitIndex = -1;
869 
870     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
871     /// notes attached to it will also be stored, otherwise they will not be.
872     bool HasActiveDiagnostic;
873 
874     /// Have we emitted a diagnostic explaining why we couldn't constant
875     /// fold (not just why it's not strictly a constant expression)?
876     bool HasFoldFailureDiagnostic;
877 
878     /// Whether or not we're in a context where the front end requires a
879     /// constant value.
880     bool InConstantContext;
881 
882     /// Whether we're checking that an expression is a potential constant
883     /// expression. If so, do not fail on constructs that could become constant
884     /// later on (such as a use of an undefined global).
885     bool CheckingPotentialConstantExpression = false;
886 
887     /// Whether we're checking for an expression that has undefined behavior.
888     /// If so, we will produce warnings if we encounter an operation that is
889     /// always undefined.
890     bool CheckingForUndefinedBehavior = false;
891 
892     enum EvaluationMode {
893       /// Evaluate as a constant expression. Stop if we find that the expression
894       /// is not a constant expression.
895       EM_ConstantExpression,
896 
897       /// Evaluate as a constant expression. Stop if we find that the expression
898       /// is not a constant expression. Some expressions can be retried in the
899       /// optimizer if we don't constant fold them here, but in an unevaluated
900       /// context we try to fold them immediately since the optimizer never
901       /// gets a chance to look at it.
902       EM_ConstantExpressionUnevaluated,
903 
904       /// Fold the expression to a constant. Stop if we hit a side-effect that
905       /// we can't model.
906       EM_ConstantFold,
907 
908       /// Evaluate in any way we know how. Don't worry about side-effects that
909       /// can't be modeled.
910       EM_IgnoreSideEffects,
911     } EvalMode;
912 
913     /// Are we checking whether the expression is a potential constant
914     /// expression?
915     bool checkingPotentialConstantExpression() const override  {
916       return CheckingPotentialConstantExpression;
917     }
918 
919     /// Are we checking an expression for overflow?
920     // FIXME: We should check for any kind of undefined or suspicious behavior
921     // in such constructs, not just overflow.
922     bool checkingForUndefinedBehavior() const override {
923       return CheckingForUndefinedBehavior;
924     }
925 
926     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
927         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
928           CallStackDepth(0), NextCallIndex(1),
929           StepsLeft(C.getLangOpts().ConstexprStepLimit),
930           EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
931           BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
932           EvaluatingDecl((const ValueDecl *)nullptr),
933           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
934           HasFoldFailureDiagnostic(false), InConstantContext(false),
935           EvalMode(Mode) {}
936 
937     ~EvalInfo() {
938       discardCleanups();
939     }
940 
941     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
942                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
943       EvaluatingDecl = Base;
944       IsEvaluatingDecl = EDK;
945       EvaluatingDeclValue = &Value;
946     }
947 
948     bool CheckCallLimit(SourceLocation Loc) {
949       // Don't perform any constexpr calls (other than the call we're checking)
950       // when checking a potential constant expression.
951       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
952         return false;
953       if (NextCallIndex == 0) {
954         // NextCallIndex has wrapped around.
955         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
956         return false;
957       }
958       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
959         return true;
960       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
961         << getLangOpts().ConstexprCallDepth;
962       return false;
963     }
964 
965     std::pair<CallStackFrame *, unsigned>
966     getCallFrameAndDepth(unsigned CallIndex) {
967       assert(CallIndex && "no call index in getCallFrameAndDepth");
968       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
969       // be null in this loop.
970       unsigned Depth = CallStackDepth;
971       CallStackFrame *Frame = CurrentCall;
972       while (Frame->Index > CallIndex) {
973         Frame = Frame->Caller;
974         --Depth;
975       }
976       if (Frame->Index == CallIndex)
977         return {Frame, Depth};
978       return {nullptr, 0};
979     }
980 
981     bool nextStep(const Stmt *S) {
982       if (!StepsLeft) {
983         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
984         return false;
985       }
986       --StepsLeft;
987       return true;
988     }
989 
990     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
991 
992     Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
993       Optional<DynAlloc*> Result;
994       auto It = HeapAllocs.find(DA);
995       if (It != HeapAllocs.end())
996         Result = &It->second;
997       return Result;
998     }
999 
1000     /// Information about a stack frame for std::allocator<T>::[de]allocate.
1001     struct StdAllocatorCaller {
1002       unsigned FrameIndex;
1003       QualType ElemType;
1004       explicit operator bool() const { return FrameIndex != 0; };
1005     };
1006 
1007     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1008       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1009            Call = Call->Caller) {
1010         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1011         if (!MD)
1012           continue;
1013         const IdentifierInfo *FnII = MD->getIdentifier();
1014         if (!FnII || !FnII->isStr(FnName))
1015           continue;
1016 
1017         const auto *CTSD =
1018             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1019         if (!CTSD)
1020           continue;
1021 
1022         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1023         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1024         if (CTSD->isInStdNamespace() && ClassII &&
1025             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1026             TAL[0].getKind() == TemplateArgument::Type)
1027           return {Call->Index, TAL[0].getAsType()};
1028       }
1029 
1030       return {};
1031     }
1032 
1033     void performLifetimeExtension() {
1034       // Disable the cleanups for lifetime-extended temporaries.
1035       CleanupStack.erase(
1036           std::remove_if(CleanupStack.begin(), CleanupStack.end(),
1037                          [](Cleanup &C) { return C.isLifetimeExtended(); }),
1038           CleanupStack.end());
1039      }
1040 
1041     /// Throw away any remaining cleanups at the end of evaluation. If any
1042     /// cleanups would have had a side-effect, note that as an unmodeled
1043     /// side-effect and return false. Otherwise, return true.
1044     bool discardCleanups() {
1045       for (Cleanup &C : CleanupStack) {
1046         if (C.hasSideEffect() && !noteSideEffect()) {
1047           CleanupStack.clear();
1048           return false;
1049         }
1050       }
1051       CleanupStack.clear();
1052       return true;
1053     }
1054 
1055   private:
1056     interp::Frame *getCurrentFrame() override { return CurrentCall; }
1057     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1058 
1059     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1060     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1061 
1062     void setFoldFailureDiagnostic(bool Flag) override {
1063       HasFoldFailureDiagnostic = Flag;
1064     }
1065 
1066     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1067 
1068     ASTContext &getCtx() const override { return Ctx; }
1069 
1070     // If we have a prior diagnostic, it will be noting that the expression
1071     // isn't a constant expression. This diagnostic is more important,
1072     // unless we require this evaluation to produce a constant expression.
1073     //
1074     // FIXME: We might want to show both diagnostics to the user in
1075     // EM_ConstantFold mode.
1076     bool hasPriorDiagnostic() override {
1077       if (!EvalStatus.Diag->empty()) {
1078         switch (EvalMode) {
1079         case EM_ConstantFold:
1080         case EM_IgnoreSideEffects:
1081           if (!HasFoldFailureDiagnostic)
1082             break;
1083           // We've already failed to fold something. Keep that diagnostic.
1084           LLVM_FALLTHROUGH;
1085         case EM_ConstantExpression:
1086         case EM_ConstantExpressionUnevaluated:
1087           setActiveDiagnostic(false);
1088           return true;
1089         }
1090       }
1091       return false;
1092     }
1093 
1094     unsigned getCallStackDepth() override { return CallStackDepth; }
1095 
1096   public:
1097     /// Should we continue evaluation after encountering a side-effect that we
1098     /// couldn't model?
1099     bool keepEvaluatingAfterSideEffect() {
1100       switch (EvalMode) {
1101       case EM_IgnoreSideEffects:
1102         return true;
1103 
1104       case EM_ConstantExpression:
1105       case EM_ConstantExpressionUnevaluated:
1106       case EM_ConstantFold:
1107         // By default, assume any side effect might be valid in some other
1108         // evaluation of this expression from a different context.
1109         return checkingPotentialConstantExpression() ||
1110                checkingForUndefinedBehavior();
1111       }
1112       llvm_unreachable("Missed EvalMode case");
1113     }
1114 
1115     /// Note that we have had a side-effect, and determine whether we should
1116     /// keep evaluating.
1117     bool noteSideEffect() {
1118       EvalStatus.HasSideEffects = true;
1119       return keepEvaluatingAfterSideEffect();
1120     }
1121 
1122     /// Should we continue evaluation after encountering undefined behavior?
1123     bool keepEvaluatingAfterUndefinedBehavior() {
1124       switch (EvalMode) {
1125       case EM_IgnoreSideEffects:
1126       case EM_ConstantFold:
1127         return true;
1128 
1129       case EM_ConstantExpression:
1130       case EM_ConstantExpressionUnevaluated:
1131         return checkingForUndefinedBehavior();
1132       }
1133       llvm_unreachable("Missed EvalMode case");
1134     }
1135 
1136     /// Note that we hit something that was technically undefined behavior, but
1137     /// that we can evaluate past it (such as signed overflow or floating-point
1138     /// division by zero.)
1139     bool noteUndefinedBehavior() override {
1140       EvalStatus.HasUndefinedBehavior = true;
1141       return keepEvaluatingAfterUndefinedBehavior();
1142     }
1143 
1144     /// Should we continue evaluation as much as possible after encountering a
1145     /// construct which can't be reduced to a value?
1146     bool keepEvaluatingAfterFailure() const override {
1147       if (!StepsLeft)
1148         return false;
1149 
1150       switch (EvalMode) {
1151       case EM_ConstantExpression:
1152       case EM_ConstantExpressionUnevaluated:
1153       case EM_ConstantFold:
1154       case EM_IgnoreSideEffects:
1155         return checkingPotentialConstantExpression() ||
1156                checkingForUndefinedBehavior();
1157       }
1158       llvm_unreachable("Missed EvalMode case");
1159     }
1160 
1161     /// Notes that we failed to evaluate an expression that other expressions
1162     /// directly depend on, and determine if we should keep evaluating. This
1163     /// should only be called if we actually intend to keep evaluating.
1164     ///
1165     /// Call noteSideEffect() instead if we may be able to ignore the value that
1166     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1167     ///
1168     /// (Foo(), 1)      // use noteSideEffect
1169     /// (Foo() || true) // use noteSideEffect
1170     /// Foo() + 1       // use noteFailure
1171     LLVM_NODISCARD bool noteFailure() {
1172       // Failure when evaluating some expression often means there is some
1173       // subexpression whose evaluation was skipped. Therefore, (because we
1174       // don't track whether we skipped an expression when unwinding after an
1175       // evaluation failure) every evaluation failure that bubbles up from a
1176       // subexpression implies that a side-effect has potentially happened. We
1177       // skip setting the HasSideEffects flag to true until we decide to
1178       // continue evaluating after that point, which happens here.
1179       bool KeepGoing = keepEvaluatingAfterFailure();
1180       EvalStatus.HasSideEffects |= KeepGoing;
1181       return KeepGoing;
1182     }
1183 
1184     class ArrayInitLoopIndex {
1185       EvalInfo &Info;
1186       uint64_t OuterIndex;
1187 
1188     public:
1189       ArrayInitLoopIndex(EvalInfo &Info)
1190           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1191         Info.ArrayInitIndex = 0;
1192       }
1193       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1194 
1195       operator uint64_t&() { return Info.ArrayInitIndex; }
1196     };
1197   };
1198 
1199   /// Object used to treat all foldable expressions as constant expressions.
1200   struct FoldConstant {
1201     EvalInfo &Info;
1202     bool Enabled;
1203     bool HadNoPriorDiags;
1204     EvalInfo::EvaluationMode OldMode;
1205 
1206     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1207       : Info(Info),
1208         Enabled(Enabled),
1209         HadNoPriorDiags(Info.EvalStatus.Diag &&
1210                         Info.EvalStatus.Diag->empty() &&
1211                         !Info.EvalStatus.HasSideEffects),
1212         OldMode(Info.EvalMode) {
1213       if (Enabled)
1214         Info.EvalMode = EvalInfo::EM_ConstantFold;
1215     }
1216     void keepDiagnostics() { Enabled = false; }
1217     ~FoldConstant() {
1218       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1219           !Info.EvalStatus.HasSideEffects)
1220         Info.EvalStatus.Diag->clear();
1221       Info.EvalMode = OldMode;
1222     }
1223   };
1224 
1225   /// RAII object used to set the current evaluation mode to ignore
1226   /// side-effects.
1227   struct IgnoreSideEffectsRAII {
1228     EvalInfo &Info;
1229     EvalInfo::EvaluationMode OldMode;
1230     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1231         : Info(Info), OldMode(Info.EvalMode) {
1232       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1233     }
1234 
1235     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1236   };
1237 
1238   /// RAII object used to optionally suppress diagnostics and side-effects from
1239   /// a speculative evaluation.
1240   class SpeculativeEvaluationRAII {
1241     EvalInfo *Info = nullptr;
1242     Expr::EvalStatus OldStatus;
1243     unsigned OldSpeculativeEvaluationDepth;
1244 
1245     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1246       Info = Other.Info;
1247       OldStatus = Other.OldStatus;
1248       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1249       Other.Info = nullptr;
1250     }
1251 
1252     void maybeRestoreState() {
1253       if (!Info)
1254         return;
1255 
1256       Info->EvalStatus = OldStatus;
1257       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1258     }
1259 
1260   public:
1261     SpeculativeEvaluationRAII() = default;
1262 
1263     SpeculativeEvaluationRAII(
1264         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1265         : Info(&Info), OldStatus(Info.EvalStatus),
1266           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1267       Info.EvalStatus.Diag = NewDiag;
1268       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1269     }
1270 
1271     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1272     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1273       moveFromAndCancel(std::move(Other));
1274     }
1275 
1276     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1277       maybeRestoreState();
1278       moveFromAndCancel(std::move(Other));
1279       return *this;
1280     }
1281 
1282     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1283   };
1284 
1285   /// RAII object wrapping a full-expression or block scope, and handling
1286   /// the ending of the lifetime of temporaries created within it.
1287   template<bool IsFullExpression>
1288   class ScopeRAII {
1289     EvalInfo &Info;
1290     unsigned OldStackSize;
1291   public:
1292     ScopeRAII(EvalInfo &Info)
1293         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1294       // Push a new temporary version. This is needed to distinguish between
1295       // temporaries created in different iterations of a loop.
1296       Info.CurrentCall->pushTempVersion();
1297     }
1298     bool destroy(bool RunDestructors = true) {
1299       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1300       OldStackSize = -1U;
1301       return OK;
1302     }
1303     ~ScopeRAII() {
1304       if (OldStackSize != -1U)
1305         destroy(false);
1306       // Body moved to a static method to encourage the compiler to inline away
1307       // instances of this class.
1308       Info.CurrentCall->popTempVersion();
1309     }
1310   private:
1311     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1312                         unsigned OldStackSize) {
1313       assert(OldStackSize <= Info.CleanupStack.size() &&
1314              "running cleanups out of order?");
1315 
1316       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1317       // for a full-expression scope.
1318       bool Success = true;
1319       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1320         if (!(IsFullExpression &&
1321               Info.CleanupStack[I - 1].isLifetimeExtended())) {
1322           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1323             Success = false;
1324             break;
1325           }
1326         }
1327       }
1328 
1329       // Compact lifetime-extended cleanups.
1330       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1331       if (IsFullExpression)
1332         NewEnd =
1333             std::remove_if(NewEnd, Info.CleanupStack.end(),
1334                            [](Cleanup &C) { return !C.isLifetimeExtended(); });
1335       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1336       return Success;
1337     }
1338   };
1339   typedef ScopeRAII<false> BlockScopeRAII;
1340   typedef ScopeRAII<true> FullExpressionRAII;
1341 }
1342 
1343 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1344                                          CheckSubobjectKind CSK) {
1345   if (Invalid)
1346     return false;
1347   if (isOnePastTheEnd()) {
1348     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1349       << CSK;
1350     setInvalid();
1351     return false;
1352   }
1353   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1354   // must actually be at least one array element; even a VLA cannot have a
1355   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1356   return true;
1357 }
1358 
1359 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1360                                                                 const Expr *E) {
1361   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1362   // Do not set the designator as invalid: we can represent this situation,
1363   // and correct handling of __builtin_object_size requires us to do so.
1364 }
1365 
1366 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1367                                                     const Expr *E,
1368                                                     const APSInt &N) {
1369   // If we're complaining, we must be able to statically determine the size of
1370   // the most derived array.
1371   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1372     Info.CCEDiag(E, diag::note_constexpr_array_index)
1373       << N << /*array*/ 0
1374       << static_cast<unsigned>(getMostDerivedArraySize());
1375   else
1376     Info.CCEDiag(E, diag::note_constexpr_array_index)
1377       << N << /*non-array*/ 1;
1378   setInvalid();
1379 }
1380 
1381 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1382                                const FunctionDecl *Callee, const LValue *This,
1383                                APValue *Arguments)
1384     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1385       Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1386   Info.CurrentCall = this;
1387   ++Info.CallStackDepth;
1388 }
1389 
1390 CallStackFrame::~CallStackFrame() {
1391   assert(Info.CurrentCall == this && "calls retired out of order");
1392   --Info.CallStackDepth;
1393   Info.CurrentCall = Caller;
1394 }
1395 
1396 static bool isRead(AccessKinds AK) {
1397   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1398 }
1399 
1400 static bool isModification(AccessKinds AK) {
1401   switch (AK) {
1402   case AK_Read:
1403   case AK_ReadObjectRepresentation:
1404   case AK_MemberCall:
1405   case AK_DynamicCast:
1406   case AK_TypeId:
1407     return false;
1408   case AK_Assign:
1409   case AK_Increment:
1410   case AK_Decrement:
1411   case AK_Construct:
1412   case AK_Destroy:
1413     return true;
1414   }
1415   llvm_unreachable("unknown access kind");
1416 }
1417 
1418 static bool isAnyAccess(AccessKinds AK) {
1419   return isRead(AK) || isModification(AK);
1420 }
1421 
1422 /// Is this an access per the C++ definition?
1423 static bool isFormalAccess(AccessKinds AK) {
1424   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1425 }
1426 
1427 /// Is this kind of axcess valid on an indeterminate object value?
1428 static bool isValidIndeterminateAccess(AccessKinds AK) {
1429   switch (AK) {
1430   case AK_Read:
1431   case AK_Increment:
1432   case AK_Decrement:
1433     // These need the object's value.
1434     return false;
1435 
1436   case AK_ReadObjectRepresentation:
1437   case AK_Assign:
1438   case AK_Construct:
1439   case AK_Destroy:
1440     // Construction and destruction don't need the value.
1441     return true;
1442 
1443   case AK_MemberCall:
1444   case AK_DynamicCast:
1445   case AK_TypeId:
1446     // These aren't really meaningful on scalars.
1447     return true;
1448   }
1449   llvm_unreachable("unknown access kind");
1450 }
1451 
1452 namespace {
1453   struct ComplexValue {
1454   private:
1455     bool IsInt;
1456 
1457   public:
1458     APSInt IntReal, IntImag;
1459     APFloat FloatReal, FloatImag;
1460 
1461     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1462 
1463     void makeComplexFloat() { IsInt = false; }
1464     bool isComplexFloat() const { return !IsInt; }
1465     APFloat &getComplexFloatReal() { return FloatReal; }
1466     APFloat &getComplexFloatImag() { return FloatImag; }
1467 
1468     void makeComplexInt() { IsInt = true; }
1469     bool isComplexInt() const { return IsInt; }
1470     APSInt &getComplexIntReal() { return IntReal; }
1471     APSInt &getComplexIntImag() { return IntImag; }
1472 
1473     void moveInto(APValue &v) const {
1474       if (isComplexFloat())
1475         v = APValue(FloatReal, FloatImag);
1476       else
1477         v = APValue(IntReal, IntImag);
1478     }
1479     void setFrom(const APValue &v) {
1480       assert(v.isComplexFloat() || v.isComplexInt());
1481       if (v.isComplexFloat()) {
1482         makeComplexFloat();
1483         FloatReal = v.getComplexFloatReal();
1484         FloatImag = v.getComplexFloatImag();
1485       } else {
1486         makeComplexInt();
1487         IntReal = v.getComplexIntReal();
1488         IntImag = v.getComplexIntImag();
1489       }
1490     }
1491   };
1492 
1493   struct LValue {
1494     APValue::LValueBase Base;
1495     CharUnits Offset;
1496     SubobjectDesignator Designator;
1497     bool IsNullPtr : 1;
1498     bool InvalidBase : 1;
1499 
1500     const APValue::LValueBase getLValueBase() const { return Base; }
1501     CharUnits &getLValueOffset() { return Offset; }
1502     const CharUnits &getLValueOffset() const { return Offset; }
1503     SubobjectDesignator &getLValueDesignator() { return Designator; }
1504     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1505     bool isNullPointer() const { return IsNullPtr;}
1506 
1507     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1508     unsigned getLValueVersion() const { return Base.getVersion(); }
1509 
1510     void moveInto(APValue &V) const {
1511       if (Designator.Invalid)
1512         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1513       else {
1514         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1515         V = APValue(Base, Offset, Designator.Entries,
1516                     Designator.IsOnePastTheEnd, IsNullPtr);
1517       }
1518     }
1519     void setFrom(ASTContext &Ctx, const APValue &V) {
1520       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1521       Base = V.getLValueBase();
1522       Offset = V.getLValueOffset();
1523       InvalidBase = false;
1524       Designator = SubobjectDesignator(Ctx, V);
1525       IsNullPtr = V.isNullPointer();
1526     }
1527 
1528     void set(APValue::LValueBase B, bool BInvalid = false) {
1529 #ifndef NDEBUG
1530       // We only allow a few types of invalid bases. Enforce that here.
1531       if (BInvalid) {
1532         const auto *E = B.get<const Expr *>();
1533         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1534                "Unexpected type of invalid base");
1535       }
1536 #endif
1537 
1538       Base = B;
1539       Offset = CharUnits::fromQuantity(0);
1540       InvalidBase = BInvalid;
1541       Designator = SubobjectDesignator(getType(B));
1542       IsNullPtr = false;
1543     }
1544 
1545     void setNull(ASTContext &Ctx, QualType PointerTy) {
1546       Base = (Expr *)nullptr;
1547       Offset =
1548           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1549       InvalidBase = false;
1550       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1551       IsNullPtr = true;
1552     }
1553 
1554     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1555       set(B, true);
1556     }
1557 
1558     std::string toString(ASTContext &Ctx, QualType T) const {
1559       APValue Printable;
1560       moveInto(Printable);
1561       return Printable.getAsString(Ctx, T);
1562     }
1563 
1564   private:
1565     // Check that this LValue is not based on a null pointer. If it is, produce
1566     // a diagnostic and mark the designator as invalid.
1567     template <typename GenDiagType>
1568     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1569       if (Designator.Invalid)
1570         return false;
1571       if (IsNullPtr) {
1572         GenDiag();
1573         Designator.setInvalid();
1574         return false;
1575       }
1576       return true;
1577     }
1578 
1579   public:
1580     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1581                           CheckSubobjectKind CSK) {
1582       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1583         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1584       });
1585     }
1586 
1587     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1588                                        AccessKinds AK) {
1589       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1590         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1591       });
1592     }
1593 
1594     // Check this LValue refers to an object. If not, set the designator to be
1595     // invalid and emit a diagnostic.
1596     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1597       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1598              Designator.checkSubobject(Info, E, CSK);
1599     }
1600 
1601     void addDecl(EvalInfo &Info, const Expr *E,
1602                  const Decl *D, bool Virtual = false) {
1603       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1604         Designator.addDeclUnchecked(D, Virtual);
1605     }
1606     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1607       if (!Designator.Entries.empty()) {
1608         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1609         Designator.setInvalid();
1610         return;
1611       }
1612       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1613         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1614         Designator.FirstEntryIsAnUnsizedArray = true;
1615         Designator.addUnsizedArrayUnchecked(ElemTy);
1616       }
1617     }
1618     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1619       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1620         Designator.addArrayUnchecked(CAT);
1621     }
1622     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1623       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1624         Designator.addComplexUnchecked(EltTy, Imag);
1625     }
1626     void clearIsNullPointer() {
1627       IsNullPtr = false;
1628     }
1629     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1630                               const APSInt &Index, CharUnits ElementSize) {
1631       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1632       // but we're not required to diagnose it and it's valid in C++.)
1633       if (!Index)
1634         return;
1635 
1636       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1637       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1638       // offsets.
1639       uint64_t Offset64 = Offset.getQuantity();
1640       uint64_t ElemSize64 = ElementSize.getQuantity();
1641       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1642       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1643 
1644       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1645         Designator.adjustIndex(Info, E, Index);
1646       clearIsNullPointer();
1647     }
1648     void adjustOffset(CharUnits N) {
1649       Offset += N;
1650       if (N.getQuantity())
1651         clearIsNullPointer();
1652     }
1653   };
1654 
1655   struct MemberPtr {
1656     MemberPtr() {}
1657     explicit MemberPtr(const ValueDecl *Decl) :
1658       DeclAndIsDerivedMember(Decl, false), Path() {}
1659 
1660     /// The member or (direct or indirect) field referred to by this member
1661     /// pointer, or 0 if this is a null member pointer.
1662     const ValueDecl *getDecl() const {
1663       return DeclAndIsDerivedMember.getPointer();
1664     }
1665     /// Is this actually a member of some type derived from the relevant class?
1666     bool isDerivedMember() const {
1667       return DeclAndIsDerivedMember.getInt();
1668     }
1669     /// Get the class which the declaration actually lives in.
1670     const CXXRecordDecl *getContainingRecord() const {
1671       return cast<CXXRecordDecl>(
1672           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1673     }
1674 
1675     void moveInto(APValue &V) const {
1676       V = APValue(getDecl(), isDerivedMember(), Path);
1677     }
1678     void setFrom(const APValue &V) {
1679       assert(V.isMemberPointer());
1680       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1681       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1682       Path.clear();
1683       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1684       Path.insert(Path.end(), P.begin(), P.end());
1685     }
1686 
1687     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1688     /// whether the member is a member of some class derived from the class type
1689     /// of the member pointer.
1690     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1691     /// Path - The path of base/derived classes from the member declaration's
1692     /// class (exclusive) to the class type of the member pointer (inclusive).
1693     SmallVector<const CXXRecordDecl*, 4> Path;
1694 
1695     /// Perform a cast towards the class of the Decl (either up or down the
1696     /// hierarchy).
1697     bool castBack(const CXXRecordDecl *Class) {
1698       assert(!Path.empty());
1699       const CXXRecordDecl *Expected;
1700       if (Path.size() >= 2)
1701         Expected = Path[Path.size() - 2];
1702       else
1703         Expected = getContainingRecord();
1704       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1705         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1706         // if B does not contain the original member and is not a base or
1707         // derived class of the class containing the original member, the result
1708         // of the cast is undefined.
1709         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1710         // (D::*). We consider that to be a language defect.
1711         return false;
1712       }
1713       Path.pop_back();
1714       return true;
1715     }
1716     /// Perform a base-to-derived member pointer cast.
1717     bool castToDerived(const CXXRecordDecl *Derived) {
1718       if (!getDecl())
1719         return true;
1720       if (!isDerivedMember()) {
1721         Path.push_back(Derived);
1722         return true;
1723       }
1724       if (!castBack(Derived))
1725         return false;
1726       if (Path.empty())
1727         DeclAndIsDerivedMember.setInt(false);
1728       return true;
1729     }
1730     /// Perform a derived-to-base member pointer cast.
1731     bool castToBase(const CXXRecordDecl *Base) {
1732       if (!getDecl())
1733         return true;
1734       if (Path.empty())
1735         DeclAndIsDerivedMember.setInt(true);
1736       if (isDerivedMember()) {
1737         Path.push_back(Base);
1738         return true;
1739       }
1740       return castBack(Base);
1741     }
1742   };
1743 
1744   /// Compare two member pointers, which are assumed to be of the same type.
1745   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1746     if (!LHS.getDecl() || !RHS.getDecl())
1747       return !LHS.getDecl() && !RHS.getDecl();
1748     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1749       return false;
1750     return LHS.Path == RHS.Path;
1751   }
1752 }
1753 
1754 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1755 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1756                             const LValue &This, const Expr *E,
1757                             bool AllowNonLiteralTypes = false);
1758 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1759                            bool InvalidBaseOK = false);
1760 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1761                             bool InvalidBaseOK = false);
1762 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1763                                   EvalInfo &Info);
1764 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1765 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1766 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1767                                     EvalInfo &Info);
1768 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1769 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1770 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1771                            EvalInfo &Info);
1772 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1773 
1774 /// Evaluate an integer or fixed point expression into an APResult.
1775 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1776                                         EvalInfo &Info);
1777 
1778 /// Evaluate only a fixed point expression into an APResult.
1779 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1780                                EvalInfo &Info);
1781 
1782 //===----------------------------------------------------------------------===//
1783 // Misc utilities
1784 //===----------------------------------------------------------------------===//
1785 
1786 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1787 /// preserving its value (by extending by up to one bit as needed).
1788 static void negateAsSigned(APSInt &Int) {
1789   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1790     Int = Int.extend(Int.getBitWidth() + 1);
1791     Int.setIsSigned(true);
1792   }
1793   Int = -Int;
1794 }
1795 
1796 template<typename KeyT>
1797 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1798                                          bool IsLifetimeExtended, LValue &LV) {
1799   unsigned Version = getTempVersion();
1800   APValue::LValueBase Base(Key, Index, Version);
1801   LV.set(Base);
1802   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1803   assert(Result.isAbsent() && "temporary created multiple times");
1804 
1805   // If we're creating a temporary immediately in the operand of a speculative
1806   // evaluation, don't register a cleanup to be run outside the speculative
1807   // evaluation context, since we won't actually be able to initialize this
1808   // object.
1809   if (Index <= Info.SpeculativeEvaluationDepth) {
1810     if (T.isDestructedType())
1811       Info.noteSideEffect();
1812   } else {
1813     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, IsLifetimeExtended));
1814   }
1815   return Result;
1816 }
1817 
1818 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1819   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1820     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1821     return nullptr;
1822   }
1823 
1824   DynamicAllocLValue DA(NumHeapAllocs++);
1825   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1826   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1827                                    std::forward_as_tuple(DA), std::tuple<>());
1828   assert(Result.second && "reused a heap alloc index?");
1829   Result.first->second.AllocExpr = E;
1830   return &Result.first->second.Value;
1831 }
1832 
1833 /// Produce a string describing the given constexpr call.
1834 void CallStackFrame::describe(raw_ostream &Out) {
1835   unsigned ArgIndex = 0;
1836   bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1837                       !isa<CXXConstructorDecl>(Callee) &&
1838                       cast<CXXMethodDecl>(Callee)->isInstance();
1839 
1840   if (!IsMemberCall)
1841     Out << *Callee << '(';
1842 
1843   if (This && IsMemberCall) {
1844     APValue Val;
1845     This->moveInto(Val);
1846     Val.printPretty(Out, Info.Ctx,
1847                     This->Designator.MostDerivedType);
1848     // FIXME: Add parens around Val if needed.
1849     Out << "->" << *Callee << '(';
1850     IsMemberCall = false;
1851   }
1852 
1853   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1854        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1855     if (ArgIndex > (unsigned)IsMemberCall)
1856       Out << ", ";
1857 
1858     const ParmVarDecl *Param = *I;
1859     const APValue &Arg = Arguments[ArgIndex];
1860     Arg.printPretty(Out, Info.Ctx, Param->getType());
1861 
1862     if (ArgIndex == 0 && IsMemberCall)
1863       Out << "->" << *Callee << '(';
1864   }
1865 
1866   Out << ')';
1867 }
1868 
1869 /// Evaluate an expression to see if it had side-effects, and discard its
1870 /// result.
1871 /// \return \c true if the caller should keep evaluating.
1872 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1873   APValue Scratch;
1874   if (!Evaluate(Scratch, Info, E))
1875     // We don't need the value, but we might have skipped a side effect here.
1876     return Info.noteSideEffect();
1877   return true;
1878 }
1879 
1880 /// Should this call expression be treated as a string literal?
1881 static bool IsStringLiteralCall(const CallExpr *E) {
1882   unsigned Builtin = E->getBuiltinCallee();
1883   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1884           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1885 }
1886 
1887 static bool IsGlobalLValue(APValue::LValueBase B) {
1888   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1889   // constant expression of pointer type that evaluates to...
1890 
1891   // ... a null pointer value, or a prvalue core constant expression of type
1892   // std::nullptr_t.
1893   if (!B) return true;
1894 
1895   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1896     // ... the address of an object with static storage duration,
1897     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1898       return VD->hasGlobalStorage();
1899     // ... the address of a function,
1900     // ... the address of a GUID [MS extension],
1901     return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D);
1902   }
1903 
1904   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1905     return true;
1906 
1907   const Expr *E = B.get<const Expr*>();
1908   switch (E->getStmtClass()) {
1909   default:
1910     return false;
1911   case Expr::CompoundLiteralExprClass: {
1912     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1913     return CLE->isFileScope() && CLE->isLValue();
1914   }
1915   case Expr::MaterializeTemporaryExprClass:
1916     // A materialized temporary might have been lifetime-extended to static
1917     // storage duration.
1918     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1919   // A string literal has static storage duration.
1920   case Expr::StringLiteralClass:
1921   case Expr::PredefinedExprClass:
1922   case Expr::ObjCStringLiteralClass:
1923   case Expr::ObjCEncodeExprClass:
1924     return true;
1925   case Expr::ObjCBoxedExprClass:
1926     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
1927   case Expr::CallExprClass:
1928     return IsStringLiteralCall(cast<CallExpr>(E));
1929   // For GCC compatibility, &&label has static storage duration.
1930   case Expr::AddrLabelExprClass:
1931     return true;
1932   // A Block literal expression may be used as the initialization value for
1933   // Block variables at global or local static scope.
1934   case Expr::BlockExprClass:
1935     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1936   case Expr::ImplicitValueInitExprClass:
1937     // FIXME:
1938     // We can never form an lvalue with an implicit value initialization as its
1939     // base through expression evaluation, so these only appear in one case: the
1940     // implicit variable declaration we invent when checking whether a constexpr
1941     // constructor can produce a constant expression. We must assume that such
1942     // an expression might be a global lvalue.
1943     return true;
1944   }
1945 }
1946 
1947 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1948   return LVal.Base.dyn_cast<const ValueDecl*>();
1949 }
1950 
1951 static bool IsLiteralLValue(const LValue &Value) {
1952   if (Value.getLValueCallIndex())
1953     return false;
1954   const Expr *E = Value.Base.dyn_cast<const Expr*>();
1955   return E && !isa<MaterializeTemporaryExpr>(E);
1956 }
1957 
1958 static bool IsWeakLValue(const LValue &Value) {
1959   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1960   return Decl && Decl->isWeak();
1961 }
1962 
1963 static bool isZeroSized(const LValue &Value) {
1964   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1965   if (Decl && isa<VarDecl>(Decl)) {
1966     QualType Ty = Decl->getType();
1967     if (Ty->isArrayType())
1968       return Ty->isIncompleteType() ||
1969              Decl->getASTContext().getTypeSize(Ty) == 0;
1970   }
1971   return false;
1972 }
1973 
1974 static bool HasSameBase(const LValue &A, const LValue &B) {
1975   if (!A.getLValueBase())
1976     return !B.getLValueBase();
1977   if (!B.getLValueBase())
1978     return false;
1979 
1980   if (A.getLValueBase().getOpaqueValue() !=
1981       B.getLValueBase().getOpaqueValue())
1982     return false;
1983 
1984   return A.getLValueCallIndex() == B.getLValueCallIndex() &&
1985          A.getLValueVersion() == B.getLValueVersion();
1986 }
1987 
1988 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1989   assert(Base && "no location for a null lvalue");
1990   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1991   if (VD)
1992     Info.Note(VD->getLocation(), diag::note_declared_at);
1993   else if (const Expr *E = Base.dyn_cast<const Expr*>())
1994     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
1995   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
1996     // FIXME: Produce a note for dangling pointers too.
1997     if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
1998       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
1999                 diag::note_constexpr_dynamic_alloc_here);
2000   }
2001   // We have no information to show for a typeid(T) object.
2002 }
2003 
2004 enum class CheckEvaluationResultKind {
2005   ConstantExpression,
2006   FullyInitialized,
2007 };
2008 
2009 /// Materialized temporaries that we've already checked to determine if they're
2010 /// initializsed by a constant expression.
2011 using CheckedTemporaries =
2012     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2013 
2014 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2015                                   EvalInfo &Info, SourceLocation DiagLoc,
2016                                   QualType Type, const APValue &Value,
2017                                   Expr::ConstExprUsage Usage,
2018                                   SourceLocation SubobjectLoc,
2019                                   CheckedTemporaries &CheckedTemps);
2020 
2021 /// Check that this reference or pointer core constant expression is a valid
2022 /// value for an address or reference constant expression. Return true if we
2023 /// can fold this expression, whether or not it's a constant expression.
2024 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2025                                           QualType Type, const LValue &LVal,
2026                                           Expr::ConstExprUsage Usage,
2027                                           CheckedTemporaries &CheckedTemps) {
2028   bool IsReferenceType = Type->isReferenceType();
2029 
2030   APValue::LValueBase Base = LVal.getLValueBase();
2031   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2032 
2033   if (auto *VD = LVal.getLValueBase().dyn_cast<const ValueDecl *>()) {
2034     if (auto *FD = dyn_cast<FunctionDecl>(VD)) {
2035       if (FD->isConsteval()) {
2036         Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2037             << !Type->isAnyPointerType();
2038         Info.Note(FD->getLocation(), diag::note_declared_at);
2039         return false;
2040       }
2041     }
2042   }
2043 
2044   // Check that the object is a global. Note that the fake 'this' object we
2045   // manufacture when checking potential constant expressions is conservatively
2046   // assumed to be global here.
2047   if (!IsGlobalLValue(Base)) {
2048     if (Info.getLangOpts().CPlusPlus11) {
2049       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2050       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2051         << IsReferenceType << !Designator.Entries.empty()
2052         << !!VD << VD;
2053 
2054       auto *VarD = dyn_cast_or_null<VarDecl>(VD);
2055       if (VarD && VarD->isConstexpr()) {
2056         // Non-static local constexpr variables have unintuitive semantics:
2057         //   constexpr int a = 1;
2058         //   constexpr const int *p = &a;
2059         // ... is invalid because the address of 'a' is not constant. Suggest
2060         // adding a 'static' in this case.
2061         Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2062             << VarD
2063             << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2064       } else {
2065         NoteLValueLocation(Info, Base);
2066       }
2067     } else {
2068       Info.FFDiag(Loc);
2069     }
2070     // Don't allow references to temporaries to escape.
2071     return false;
2072   }
2073   assert((Info.checkingPotentialConstantExpression() ||
2074           LVal.getLValueCallIndex() == 0) &&
2075          "have call index for global lvalue");
2076 
2077   if (Base.is<DynamicAllocLValue>()) {
2078     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2079         << IsReferenceType << !Designator.Entries.empty();
2080     NoteLValueLocation(Info, Base);
2081     return false;
2082   }
2083 
2084   if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
2085     if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
2086       // Check if this is a thread-local variable.
2087       if (Var->getTLSKind())
2088         // FIXME: Diagnostic!
2089         return false;
2090 
2091       // A dllimport variable never acts like a constant.
2092       if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
2093         // FIXME: Diagnostic!
2094         return false;
2095     }
2096     if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
2097       // __declspec(dllimport) must be handled very carefully:
2098       // We must never initialize an expression with the thunk in C++.
2099       // Doing otherwise would allow the same id-expression to yield
2100       // different addresses for the same function in different translation
2101       // units.  However, this means that we must dynamically initialize the
2102       // expression with the contents of the import address table at runtime.
2103       //
2104       // The C language has no notion of ODR; furthermore, it has no notion of
2105       // dynamic initialization.  This means that we are permitted to
2106       // perform initialization with the address of the thunk.
2107       if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
2108           FD->hasAttr<DLLImportAttr>())
2109         // FIXME: Diagnostic!
2110         return false;
2111     }
2112   } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(
2113                  Base.dyn_cast<const Expr *>())) {
2114     if (CheckedTemps.insert(MTE).second) {
2115       QualType TempType = getType(Base);
2116       if (TempType.isDestructedType()) {
2117         Info.FFDiag(MTE->getExprLoc(),
2118                     diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor)
2119             << TempType;
2120         return false;
2121       }
2122 
2123       APValue *V = MTE->getOrCreateValue(false);
2124       assert(V && "evasluation result refers to uninitialised temporary");
2125       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2126                                  Info, MTE->getExprLoc(), TempType, *V,
2127                                  Usage, SourceLocation(), CheckedTemps))
2128         return false;
2129     }
2130   }
2131 
2132   // Allow address constant expressions to be past-the-end pointers. This is
2133   // an extension: the standard requires them to point to an object.
2134   if (!IsReferenceType)
2135     return true;
2136 
2137   // A reference constant expression must refer to an object.
2138   if (!Base) {
2139     // FIXME: diagnostic
2140     Info.CCEDiag(Loc);
2141     return true;
2142   }
2143 
2144   // Does this refer one past the end of some object?
2145   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2146     const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2147     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2148       << !Designator.Entries.empty() << !!VD << VD;
2149     NoteLValueLocation(Info, Base);
2150   }
2151 
2152   return true;
2153 }
2154 
2155 /// Member pointers are constant expressions unless they point to a
2156 /// non-virtual dllimport member function.
2157 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2158                                                  SourceLocation Loc,
2159                                                  QualType Type,
2160                                                  const APValue &Value,
2161                                                  Expr::ConstExprUsage Usage) {
2162   const ValueDecl *Member = Value.getMemberPointerDecl();
2163   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2164   if (!FD)
2165     return true;
2166   if (FD->isConsteval()) {
2167     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2168     Info.Note(FD->getLocation(), diag::note_declared_at);
2169     return false;
2170   }
2171   return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
2172          !FD->hasAttr<DLLImportAttr>();
2173 }
2174 
2175 /// Check that this core constant expression is of literal type, and if not,
2176 /// produce an appropriate diagnostic.
2177 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2178                              const LValue *This = nullptr) {
2179   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
2180     return true;
2181 
2182   // C++1y: A constant initializer for an object o [...] may also invoke
2183   // constexpr constructors for o and its subobjects even if those objects
2184   // are of non-literal class types.
2185   //
2186   // C++11 missed this detail for aggregates, so classes like this:
2187   //   struct foo_t { union { int i; volatile int j; } u; };
2188   // are not (obviously) initializable like so:
2189   //   __attribute__((__require_constant_initialization__))
2190   //   static const foo_t x = {{0}};
2191   // because "i" is a subobject with non-literal initialization (due to the
2192   // volatile member of the union). See:
2193   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2194   // Therefore, we use the C++1y behavior.
2195   if (This && Info.EvaluatingDecl == This->getLValueBase())
2196     return true;
2197 
2198   // Prvalue constant expressions must be of literal types.
2199   if (Info.getLangOpts().CPlusPlus11)
2200     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2201       << E->getType();
2202   else
2203     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2204   return false;
2205 }
2206 
2207 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2208                                   EvalInfo &Info, SourceLocation DiagLoc,
2209                                   QualType Type, const APValue &Value,
2210                                   Expr::ConstExprUsage Usage,
2211                                   SourceLocation SubobjectLoc,
2212                                   CheckedTemporaries &CheckedTemps) {
2213   if (!Value.hasValue()) {
2214     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2215       << true << Type;
2216     if (SubobjectLoc.isValid())
2217       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2218     return false;
2219   }
2220 
2221   // We allow _Atomic(T) to be initialized from anything that T can be
2222   // initialized from.
2223   if (const AtomicType *AT = Type->getAs<AtomicType>())
2224     Type = AT->getValueType();
2225 
2226   // Core issue 1454: For a literal constant expression of array or class type,
2227   // each subobject of its value shall have been initialized by a constant
2228   // expression.
2229   if (Value.isArray()) {
2230     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2231     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2232       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2233                                  Value.getArrayInitializedElt(I), Usage,
2234                                  SubobjectLoc, CheckedTemps))
2235         return false;
2236     }
2237     if (!Value.hasArrayFiller())
2238       return true;
2239     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2240                                  Value.getArrayFiller(), Usage, SubobjectLoc,
2241                                  CheckedTemps);
2242   }
2243   if (Value.isUnion() && Value.getUnionField()) {
2244     return CheckEvaluationResult(
2245         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2246         Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(),
2247         CheckedTemps);
2248   }
2249   if (Value.isStruct()) {
2250     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2251     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2252       unsigned BaseIndex = 0;
2253       for (const CXXBaseSpecifier &BS : CD->bases()) {
2254         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2255                                    Value.getStructBase(BaseIndex), Usage,
2256                                    BS.getBeginLoc(), CheckedTemps))
2257           return false;
2258         ++BaseIndex;
2259       }
2260     }
2261     for (const auto *I : RD->fields()) {
2262       if (I->isUnnamedBitfield())
2263         continue;
2264 
2265       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2266                                  Value.getStructField(I->getFieldIndex()),
2267                                  Usage, I->getLocation(), CheckedTemps))
2268         return false;
2269     }
2270   }
2271 
2272   if (Value.isLValue() &&
2273       CERK == CheckEvaluationResultKind::ConstantExpression) {
2274     LValue LVal;
2275     LVal.setFrom(Info.Ctx, Value);
2276     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage,
2277                                          CheckedTemps);
2278   }
2279 
2280   if (Value.isMemberPointer() &&
2281       CERK == CheckEvaluationResultKind::ConstantExpression)
2282     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
2283 
2284   // Everything else is fine.
2285   return true;
2286 }
2287 
2288 /// Check that this core constant expression value is a valid value for a
2289 /// constant expression. If not, report an appropriate diagnostic. Does not
2290 /// check that the expression is of literal type.
2291 static bool
2292 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2293                         const APValue &Value,
2294                         Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
2295   // Nothing to check for a constant expression of type 'cv void'.
2296   if (Type->isVoidType())
2297     return true;
2298 
2299   CheckedTemporaries CheckedTemps;
2300   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2301                                Info, DiagLoc, Type, Value, Usage,
2302                                SourceLocation(), CheckedTemps);
2303 }
2304 
2305 /// Check that this evaluated value is fully-initialized and can be loaded by
2306 /// an lvalue-to-rvalue conversion.
2307 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2308                                   QualType Type, const APValue &Value) {
2309   CheckedTemporaries CheckedTemps;
2310   return CheckEvaluationResult(
2311       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2312       Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps);
2313 }
2314 
2315 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2316 /// "the allocated storage is deallocated within the evaluation".
2317 static bool CheckMemoryLeaks(EvalInfo &Info) {
2318   if (!Info.HeapAllocs.empty()) {
2319     // We can still fold to a constant despite a compile-time memory leak,
2320     // so long as the heap allocation isn't referenced in the result (we check
2321     // that in CheckConstantExpression).
2322     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2323                  diag::note_constexpr_memory_leak)
2324         << unsigned(Info.HeapAllocs.size() - 1);
2325   }
2326   return true;
2327 }
2328 
2329 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2330   // A null base expression indicates a null pointer.  These are always
2331   // evaluatable, and they are false unless the offset is zero.
2332   if (!Value.getLValueBase()) {
2333     Result = !Value.getLValueOffset().isZero();
2334     return true;
2335   }
2336 
2337   // We have a non-null base.  These are generally known to be true, but if it's
2338   // a weak declaration it can be null at runtime.
2339   Result = true;
2340   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2341   return !Decl || !Decl->isWeak();
2342 }
2343 
2344 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2345   switch (Val.getKind()) {
2346   case APValue::None:
2347   case APValue::Indeterminate:
2348     return false;
2349   case APValue::Int:
2350     Result = Val.getInt().getBoolValue();
2351     return true;
2352   case APValue::FixedPoint:
2353     Result = Val.getFixedPoint().getBoolValue();
2354     return true;
2355   case APValue::Float:
2356     Result = !Val.getFloat().isZero();
2357     return true;
2358   case APValue::ComplexInt:
2359     Result = Val.getComplexIntReal().getBoolValue() ||
2360              Val.getComplexIntImag().getBoolValue();
2361     return true;
2362   case APValue::ComplexFloat:
2363     Result = !Val.getComplexFloatReal().isZero() ||
2364              !Val.getComplexFloatImag().isZero();
2365     return true;
2366   case APValue::LValue:
2367     return EvalPointerValueAsBool(Val, Result);
2368   case APValue::MemberPointer:
2369     Result = Val.getMemberPointerDecl();
2370     return true;
2371   case APValue::Vector:
2372   case APValue::Array:
2373   case APValue::Struct:
2374   case APValue::Union:
2375   case APValue::AddrLabelDiff:
2376     return false;
2377   }
2378 
2379   llvm_unreachable("unknown APValue kind");
2380 }
2381 
2382 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2383                                        EvalInfo &Info) {
2384   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2385   APValue Val;
2386   if (!Evaluate(Val, Info, E))
2387     return false;
2388   return HandleConversionToBool(Val, Result);
2389 }
2390 
2391 template<typename T>
2392 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2393                            const T &SrcValue, QualType DestType) {
2394   Info.CCEDiag(E, diag::note_constexpr_overflow)
2395     << SrcValue << DestType;
2396   return Info.noteUndefinedBehavior();
2397 }
2398 
2399 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2400                                  QualType SrcType, const APFloat &Value,
2401                                  QualType DestType, APSInt &Result) {
2402   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2403   // Determine whether we are converting to unsigned or signed.
2404   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2405 
2406   Result = APSInt(DestWidth, !DestSigned);
2407   bool ignored;
2408   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2409       & APFloat::opInvalidOp)
2410     return HandleOverflow(Info, E, Value, DestType);
2411   return true;
2412 }
2413 
2414 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2415                                    QualType SrcType, QualType DestType,
2416                                    APFloat &Result) {
2417   APFloat Value = Result;
2418   bool ignored;
2419   Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2420                  APFloat::rmNearestTiesToEven, &ignored);
2421   return true;
2422 }
2423 
2424 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2425                                  QualType DestType, QualType SrcType,
2426                                  const APSInt &Value) {
2427   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2428   // Figure out if this is a truncate, extend or noop cast.
2429   // If the input is signed, do a sign extend, noop, or truncate.
2430   APSInt Result = Value.extOrTrunc(DestWidth);
2431   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2432   if (DestType->isBooleanType())
2433     Result = Value.getBoolValue();
2434   return Result;
2435 }
2436 
2437 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2438                                  QualType SrcType, const APSInt &Value,
2439                                  QualType DestType, APFloat &Result) {
2440   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2441   Result.convertFromAPInt(Value, Value.isSigned(),
2442                           APFloat::rmNearestTiesToEven);
2443   return true;
2444 }
2445 
2446 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2447                                   APValue &Value, const FieldDecl *FD) {
2448   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2449 
2450   if (!Value.isInt()) {
2451     // Trying to store a pointer-cast-to-integer into a bitfield.
2452     // FIXME: In this case, we should provide the diagnostic for casting
2453     // a pointer to an integer.
2454     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2455     Info.FFDiag(E);
2456     return false;
2457   }
2458 
2459   APSInt &Int = Value.getInt();
2460   unsigned OldBitWidth = Int.getBitWidth();
2461   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2462   if (NewBitWidth < OldBitWidth)
2463     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2464   return true;
2465 }
2466 
2467 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2468                                   llvm::APInt &Res) {
2469   APValue SVal;
2470   if (!Evaluate(SVal, Info, E))
2471     return false;
2472   if (SVal.isInt()) {
2473     Res = SVal.getInt();
2474     return true;
2475   }
2476   if (SVal.isFloat()) {
2477     Res = SVal.getFloat().bitcastToAPInt();
2478     return true;
2479   }
2480   if (SVal.isVector()) {
2481     QualType VecTy = E->getType();
2482     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2483     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2484     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2485     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2486     Res = llvm::APInt::getNullValue(VecSize);
2487     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2488       APValue &Elt = SVal.getVectorElt(i);
2489       llvm::APInt EltAsInt;
2490       if (Elt.isInt()) {
2491         EltAsInt = Elt.getInt();
2492       } else if (Elt.isFloat()) {
2493         EltAsInt = Elt.getFloat().bitcastToAPInt();
2494       } else {
2495         // Don't try to handle vectors of anything other than int or float
2496         // (not sure if it's possible to hit this case).
2497         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2498         return false;
2499       }
2500       unsigned BaseEltSize = EltAsInt.getBitWidth();
2501       if (BigEndian)
2502         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2503       else
2504         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2505     }
2506     return true;
2507   }
2508   // Give up if the input isn't an int, float, or vector.  For example, we
2509   // reject "(v4i16)(intptr_t)&a".
2510   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2511   return false;
2512 }
2513 
2514 /// Perform the given integer operation, which is known to need at most BitWidth
2515 /// bits, and check for overflow in the original type (if that type was not an
2516 /// unsigned type).
2517 template<typename Operation>
2518 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2519                                  const APSInt &LHS, const APSInt &RHS,
2520                                  unsigned BitWidth, Operation Op,
2521                                  APSInt &Result) {
2522   if (LHS.isUnsigned()) {
2523     Result = Op(LHS, RHS);
2524     return true;
2525   }
2526 
2527   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2528   Result = Value.trunc(LHS.getBitWidth());
2529   if (Result.extend(BitWidth) != Value) {
2530     if (Info.checkingForUndefinedBehavior())
2531       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2532                                        diag::warn_integer_constant_overflow)
2533           << Result.toString(10) << E->getType();
2534     else
2535       return HandleOverflow(Info, E, Value, E->getType());
2536   }
2537   return true;
2538 }
2539 
2540 /// Perform the given binary integer operation.
2541 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2542                               BinaryOperatorKind Opcode, APSInt RHS,
2543                               APSInt &Result) {
2544   switch (Opcode) {
2545   default:
2546     Info.FFDiag(E);
2547     return false;
2548   case BO_Mul:
2549     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2550                                 std::multiplies<APSInt>(), Result);
2551   case BO_Add:
2552     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2553                                 std::plus<APSInt>(), Result);
2554   case BO_Sub:
2555     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2556                                 std::minus<APSInt>(), Result);
2557   case BO_And: Result = LHS & RHS; return true;
2558   case BO_Xor: Result = LHS ^ RHS; return true;
2559   case BO_Or:  Result = LHS | RHS; return true;
2560   case BO_Div:
2561   case BO_Rem:
2562     if (RHS == 0) {
2563       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2564       return false;
2565     }
2566     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2567     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2568     // this operation and gives the two's complement result.
2569     if (RHS.isNegative() && RHS.isAllOnesValue() &&
2570         LHS.isSigned() && LHS.isMinSignedValue())
2571       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2572                             E->getType());
2573     return true;
2574   case BO_Shl: {
2575     if (Info.getLangOpts().OpenCL)
2576       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2577       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2578                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2579                     RHS.isUnsigned());
2580     else if (RHS.isSigned() && RHS.isNegative()) {
2581       // During constant-folding, a negative shift is an opposite shift. Such
2582       // a shift is not a constant expression.
2583       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2584       RHS = -RHS;
2585       goto shift_right;
2586     }
2587   shift_left:
2588     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2589     // the shifted type.
2590     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2591     if (SA != RHS) {
2592       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2593         << RHS << E->getType() << LHS.getBitWidth();
2594     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2595       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2596       // operand, and must not overflow the corresponding unsigned type.
2597       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2598       // E1 x 2^E2 module 2^N.
2599       if (LHS.isNegative())
2600         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2601       else if (LHS.countLeadingZeros() < SA)
2602         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2603     }
2604     Result = LHS << SA;
2605     return true;
2606   }
2607   case BO_Shr: {
2608     if (Info.getLangOpts().OpenCL)
2609       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2610       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2611                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2612                     RHS.isUnsigned());
2613     else if (RHS.isSigned() && RHS.isNegative()) {
2614       // During constant-folding, a negative shift is an opposite shift. Such a
2615       // shift is not a constant expression.
2616       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2617       RHS = -RHS;
2618       goto shift_left;
2619     }
2620   shift_right:
2621     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2622     // shifted type.
2623     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2624     if (SA != RHS)
2625       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2626         << RHS << E->getType() << LHS.getBitWidth();
2627     Result = LHS >> SA;
2628     return true;
2629   }
2630 
2631   case BO_LT: Result = LHS < RHS; return true;
2632   case BO_GT: Result = LHS > RHS; return true;
2633   case BO_LE: Result = LHS <= RHS; return true;
2634   case BO_GE: Result = LHS >= RHS; return true;
2635   case BO_EQ: Result = LHS == RHS; return true;
2636   case BO_NE: Result = LHS != RHS; return true;
2637   case BO_Cmp:
2638     llvm_unreachable("BO_Cmp should be handled elsewhere");
2639   }
2640 }
2641 
2642 /// Perform the given binary floating-point operation, in-place, on LHS.
2643 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2644                                   APFloat &LHS, BinaryOperatorKind Opcode,
2645                                   const APFloat &RHS) {
2646   switch (Opcode) {
2647   default:
2648     Info.FFDiag(E);
2649     return false;
2650   case BO_Mul:
2651     LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2652     break;
2653   case BO_Add:
2654     LHS.add(RHS, APFloat::rmNearestTiesToEven);
2655     break;
2656   case BO_Sub:
2657     LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2658     break;
2659   case BO_Div:
2660     // [expr.mul]p4:
2661     //   If the second operand of / or % is zero the behavior is undefined.
2662     if (RHS.isZero())
2663       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2664     LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2665     break;
2666   }
2667 
2668   // [expr.pre]p4:
2669   //   If during the evaluation of an expression, the result is not
2670   //   mathematically defined [...], the behavior is undefined.
2671   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2672   if (LHS.isNaN()) {
2673     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2674     return Info.noteUndefinedBehavior();
2675   }
2676   return true;
2677 }
2678 
2679 static bool handleLogicalOpForVector(const APInt &LHSValue,
2680                                      BinaryOperatorKind Opcode,
2681                                      const APInt &RHSValue, APInt &Result) {
2682   bool LHS = (LHSValue != 0);
2683   bool RHS = (RHSValue != 0);
2684 
2685   if (Opcode == BO_LAnd)
2686     Result = LHS && RHS;
2687   else
2688     Result = LHS || RHS;
2689   return true;
2690 }
2691 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2692                                      BinaryOperatorKind Opcode,
2693                                      const APFloat &RHSValue, APInt &Result) {
2694   bool LHS = !LHSValue.isZero();
2695   bool RHS = !RHSValue.isZero();
2696 
2697   if (Opcode == BO_LAnd)
2698     Result = LHS && RHS;
2699   else
2700     Result = LHS || RHS;
2701   return true;
2702 }
2703 
2704 static bool handleLogicalOpForVector(const APValue &LHSValue,
2705                                      BinaryOperatorKind Opcode,
2706                                      const APValue &RHSValue, APInt &Result) {
2707   // The result is always an int type, however operands match the first.
2708   if (LHSValue.getKind() == APValue::Int)
2709     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2710                                     RHSValue.getInt(), Result);
2711   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2712   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2713                                   RHSValue.getFloat(), Result);
2714 }
2715 
2716 template <typename APTy>
2717 static bool
2718 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2719                                const APTy &RHSValue, APInt &Result) {
2720   switch (Opcode) {
2721   default:
2722     llvm_unreachable("unsupported binary operator");
2723   case BO_EQ:
2724     Result = (LHSValue == RHSValue);
2725     break;
2726   case BO_NE:
2727     Result = (LHSValue != RHSValue);
2728     break;
2729   case BO_LT:
2730     Result = (LHSValue < RHSValue);
2731     break;
2732   case BO_GT:
2733     Result = (LHSValue > RHSValue);
2734     break;
2735   case BO_LE:
2736     Result = (LHSValue <= RHSValue);
2737     break;
2738   case BO_GE:
2739     Result = (LHSValue >= RHSValue);
2740     break;
2741   }
2742 
2743   return true;
2744 }
2745 
2746 static bool handleCompareOpForVector(const APValue &LHSValue,
2747                                      BinaryOperatorKind Opcode,
2748                                      const APValue &RHSValue, APInt &Result) {
2749   // The result is always an int type, however operands match the first.
2750   if (LHSValue.getKind() == APValue::Int)
2751     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2752                                           RHSValue.getInt(), Result);
2753   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2754   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2755                                         RHSValue.getFloat(), Result);
2756 }
2757 
2758 // Perform binary operations for vector types, in place on the LHS.
2759 static bool handleVectorVectorBinOp(EvalInfo &Info, const Expr *E,
2760                                     BinaryOperatorKind Opcode,
2761                                     APValue &LHSValue,
2762                                     const APValue &RHSValue) {
2763   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2764          "Operation not supported on vector types");
2765 
2766   const auto *VT = E->getType()->castAs<VectorType>();
2767   unsigned NumElements = VT->getNumElements();
2768   QualType EltTy = VT->getElementType();
2769 
2770   // In the cases (typically C as I've observed) where we aren't evaluating
2771   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2772   // just give up.
2773   if (!LHSValue.isVector()) {
2774     assert(LHSValue.isLValue() &&
2775            "A vector result that isn't a vector OR uncalculated LValue");
2776     Info.FFDiag(E);
2777     return false;
2778   }
2779 
2780   assert(LHSValue.getVectorLength() == NumElements &&
2781          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2782 
2783   SmallVector<APValue, 4> ResultElements;
2784 
2785   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
2786     APValue LHSElt = LHSValue.getVectorElt(EltNum);
2787     APValue RHSElt = RHSValue.getVectorElt(EltNum);
2788 
2789     if (EltTy->isIntegerType()) {
2790       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
2791                        EltTy->isUnsignedIntegerType()};
2792       bool Success = true;
2793 
2794       if (BinaryOperator::isLogicalOp(Opcode))
2795         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2796       else if (BinaryOperator::isComparisonOp(Opcode))
2797         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2798       else
2799         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
2800                                     RHSElt.getInt(), EltResult);
2801 
2802       if (!Success) {
2803         Info.FFDiag(E);
2804         return false;
2805       }
2806       ResultElements.emplace_back(EltResult);
2807 
2808     } else if (EltTy->isFloatingType()) {
2809       assert(LHSElt.getKind() == APValue::Float &&
2810              RHSElt.getKind() == APValue::Float &&
2811              "Mismatched LHS/RHS/Result Type");
2812       APFloat LHSFloat = LHSElt.getFloat();
2813 
2814       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
2815                                  RHSElt.getFloat())) {
2816         Info.FFDiag(E);
2817         return false;
2818       }
2819 
2820       ResultElements.emplace_back(LHSFloat);
2821     }
2822   }
2823 
2824   LHSValue = APValue(ResultElements.data(), ResultElements.size());
2825   return true;
2826 }
2827 
2828 /// Cast an lvalue referring to a base subobject to a derived class, by
2829 /// truncating the lvalue's path to the given length.
2830 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2831                                const RecordDecl *TruncatedType,
2832                                unsigned TruncatedElements) {
2833   SubobjectDesignator &D = Result.Designator;
2834 
2835   // Check we actually point to a derived class object.
2836   if (TruncatedElements == D.Entries.size())
2837     return true;
2838   assert(TruncatedElements >= D.MostDerivedPathLength &&
2839          "not casting to a derived class");
2840   if (!Result.checkSubobject(Info, E, CSK_Derived))
2841     return false;
2842 
2843   // Truncate the path to the subobject, and remove any derived-to-base offsets.
2844   const RecordDecl *RD = TruncatedType;
2845   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2846     if (RD->isInvalidDecl()) return false;
2847     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2848     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2849     if (isVirtualBaseClass(D.Entries[I]))
2850       Result.Offset -= Layout.getVBaseClassOffset(Base);
2851     else
2852       Result.Offset -= Layout.getBaseClassOffset(Base);
2853     RD = Base;
2854   }
2855   D.Entries.resize(TruncatedElements);
2856   return true;
2857 }
2858 
2859 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2860                                    const CXXRecordDecl *Derived,
2861                                    const CXXRecordDecl *Base,
2862                                    const ASTRecordLayout *RL = nullptr) {
2863   if (!RL) {
2864     if (Derived->isInvalidDecl()) return false;
2865     RL = &Info.Ctx.getASTRecordLayout(Derived);
2866   }
2867 
2868   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2869   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2870   return true;
2871 }
2872 
2873 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2874                              const CXXRecordDecl *DerivedDecl,
2875                              const CXXBaseSpecifier *Base) {
2876   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2877 
2878   if (!Base->isVirtual())
2879     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2880 
2881   SubobjectDesignator &D = Obj.Designator;
2882   if (D.Invalid)
2883     return false;
2884 
2885   // Extract most-derived object and corresponding type.
2886   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2887   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2888     return false;
2889 
2890   // Find the virtual base class.
2891   if (DerivedDecl->isInvalidDecl()) return false;
2892   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2893   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2894   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2895   return true;
2896 }
2897 
2898 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2899                                  QualType Type, LValue &Result) {
2900   for (CastExpr::path_const_iterator PathI = E->path_begin(),
2901                                      PathE = E->path_end();
2902        PathI != PathE; ++PathI) {
2903     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2904                           *PathI))
2905       return false;
2906     Type = (*PathI)->getType();
2907   }
2908   return true;
2909 }
2910 
2911 /// Cast an lvalue referring to a derived class to a known base subobject.
2912 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2913                             const CXXRecordDecl *DerivedRD,
2914                             const CXXRecordDecl *BaseRD) {
2915   CXXBasePaths Paths(/*FindAmbiguities=*/false,
2916                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
2917   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2918     llvm_unreachable("Class must be derived from the passed in base class!");
2919 
2920   for (CXXBasePathElement &Elem : Paths.front())
2921     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2922       return false;
2923   return true;
2924 }
2925 
2926 /// Update LVal to refer to the given field, which must be a member of the type
2927 /// currently described by LVal.
2928 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2929                                const FieldDecl *FD,
2930                                const ASTRecordLayout *RL = nullptr) {
2931   if (!RL) {
2932     if (FD->getParent()->isInvalidDecl()) return false;
2933     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2934   }
2935 
2936   unsigned I = FD->getFieldIndex();
2937   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2938   LVal.addDecl(Info, E, FD);
2939   return true;
2940 }
2941 
2942 /// Update LVal to refer to the given indirect field.
2943 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2944                                        LValue &LVal,
2945                                        const IndirectFieldDecl *IFD) {
2946   for (const auto *C : IFD->chain())
2947     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2948       return false;
2949   return true;
2950 }
2951 
2952 /// Get the size of the given type in char units.
2953 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2954                          QualType Type, CharUnits &Size) {
2955   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2956   // extension.
2957   if (Type->isVoidType() || Type->isFunctionType()) {
2958     Size = CharUnits::One();
2959     return true;
2960   }
2961 
2962   if (Type->isDependentType()) {
2963     Info.FFDiag(Loc);
2964     return false;
2965   }
2966 
2967   if (!Type->isConstantSizeType()) {
2968     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2969     // FIXME: Better diagnostic.
2970     Info.FFDiag(Loc);
2971     return false;
2972   }
2973 
2974   Size = Info.Ctx.getTypeSizeInChars(Type);
2975   return true;
2976 }
2977 
2978 /// Update a pointer value to model pointer arithmetic.
2979 /// \param Info - Information about the ongoing evaluation.
2980 /// \param E - The expression being evaluated, for diagnostic purposes.
2981 /// \param LVal - The pointer value to be updated.
2982 /// \param EltTy - The pointee type represented by LVal.
2983 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2984 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2985                                         LValue &LVal, QualType EltTy,
2986                                         APSInt Adjustment) {
2987   CharUnits SizeOfPointee;
2988   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2989     return false;
2990 
2991   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2992   return true;
2993 }
2994 
2995 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2996                                         LValue &LVal, QualType EltTy,
2997                                         int64_t Adjustment) {
2998   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2999                                      APSInt::get(Adjustment));
3000 }
3001 
3002 /// Update an lvalue to refer to a component of a complex number.
3003 /// \param Info - Information about the ongoing evaluation.
3004 /// \param LVal - The lvalue to be updated.
3005 /// \param EltTy - The complex number's component type.
3006 /// \param Imag - False for the real component, true for the imaginary.
3007 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3008                                        LValue &LVal, QualType EltTy,
3009                                        bool Imag) {
3010   if (Imag) {
3011     CharUnits SizeOfComponent;
3012     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3013       return false;
3014     LVal.Offset += SizeOfComponent;
3015   }
3016   LVal.addComplex(Info, E, EltTy, Imag);
3017   return true;
3018 }
3019 
3020 /// Try to evaluate the initializer for a variable declaration.
3021 ///
3022 /// \param Info   Information about the ongoing evaluation.
3023 /// \param E      An expression to be used when printing diagnostics.
3024 /// \param VD     The variable whose initializer should be obtained.
3025 /// \param Frame  The frame in which the variable was created. Must be null
3026 ///               if this variable is not local to the evaluation.
3027 /// \param Result Filled in with a pointer to the value of the variable.
3028 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3029                                 const VarDecl *VD, CallStackFrame *Frame,
3030                                 APValue *&Result, const LValue *LVal) {
3031 
3032   // If this is a parameter to an active constexpr function call, perform
3033   // argument substitution.
3034   if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
3035     // Assume arguments of a potential constant expression are unknown
3036     // constant expressions.
3037     if (Info.checkingPotentialConstantExpression())
3038       return false;
3039     if (!Frame || !Frame->Arguments) {
3040       Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown) << VD;
3041       return false;
3042     }
3043     Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
3044     return true;
3045   }
3046 
3047   // If this is a local variable, dig out its value.
3048   if (Frame) {
3049     Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
3050                   : Frame->getCurrentTemporary(VD);
3051     if (!Result) {
3052       // Assume variables referenced within a lambda's call operator that were
3053       // not declared within the call operator are captures and during checking
3054       // of a potential constant expression, assume they are unknown constant
3055       // expressions.
3056       assert(isLambdaCallOperator(Frame->Callee) &&
3057              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3058              "missing value for local variable");
3059       if (Info.checkingPotentialConstantExpression())
3060         return false;
3061       // FIXME: implement capture evaluation during constant expr evaluation.
3062       Info.FFDiag(E->getBeginLoc(),
3063                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3064           << "captures not currently allowed";
3065       return false;
3066     }
3067     return true;
3068   }
3069 
3070   // Dig out the initializer, and use the declaration which it's attached to.
3071   // FIXME: We should eventually check whether the variable has a reachable
3072   // initializing declaration.
3073   const Expr *Init = VD->getAnyInitializer(VD);
3074   if (!Init) {
3075     // Don't diagnose during potential constant expression checking; an
3076     // initializer might be added later.
3077     if (!Info.checkingPotentialConstantExpression()) {
3078       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3079         << VD;
3080       Info.Note(VD->getLocation(), diag::note_declared_at);
3081     }
3082     return false;
3083   }
3084 
3085   if (Init->isValueDependent()) {
3086     // The DeclRefExpr is not value-dependent, but the variable it refers to
3087     // has a value-dependent initializer. This should only happen in
3088     // constant-folding cases, where the variable is not actually of a suitable
3089     // type for use in a constant expression (otherwise the DeclRefExpr would
3090     // have been value-dependent too), so diagnose that.
3091     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3092     if (!Info.checkingPotentialConstantExpression()) {
3093       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3094                          ? diag::note_constexpr_ltor_non_constexpr
3095                          : diag::note_constexpr_ltor_non_integral, 1)
3096           << VD << VD->getType();
3097       Info.Note(VD->getLocation(), diag::note_declared_at);
3098     }
3099     return false;
3100   }
3101 
3102   // If we're currently evaluating the initializer of this declaration, use that
3103   // in-flight value.
3104   if (declaresSameEntity(Info.EvaluatingDecl.dyn_cast<const ValueDecl *>(),
3105                          VD)) {
3106     Result = Info.EvaluatingDeclValue;
3107     return true;
3108   }
3109 
3110   // Check that we can fold the initializer. In C++, we will have already done
3111   // this in the cases where it matters for conformance.
3112   SmallVector<PartialDiagnosticAt, 8> Notes;
3113   if (!VD->evaluateValue(Notes)) {
3114     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
3115               Notes.size() + 1) << VD;
3116     Info.Note(VD->getLocation(), diag::note_declared_at);
3117     Info.addNotes(Notes);
3118     return false;
3119   }
3120 
3121   // Check that the variable is actually usable in constant expressions.
3122   if (!VD->checkInitIsICE()) {
3123     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
3124                  Notes.size() + 1) << VD;
3125     Info.Note(VD->getLocation(), diag::note_declared_at);
3126     Info.addNotes(Notes);
3127   }
3128 
3129   // Never use the initializer of a weak variable, not even for constant
3130   // folding. We can't be sure that this is the definition that will be used.
3131   if (VD->isWeak()) {
3132     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3133     Info.Note(VD->getLocation(), diag::note_declared_at);
3134     return false;
3135   }
3136 
3137   Result = VD->getEvaluatedValue();
3138   return true;
3139 }
3140 
3141 static bool IsConstNonVolatile(QualType T) {
3142   Qualifiers Quals = T.getQualifiers();
3143   return Quals.hasConst() && !Quals.hasVolatile();
3144 }
3145 
3146 /// Get the base index of the given base class within an APValue representing
3147 /// the given derived class.
3148 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3149                              const CXXRecordDecl *Base) {
3150   Base = Base->getCanonicalDecl();
3151   unsigned Index = 0;
3152   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3153          E = Derived->bases_end(); I != E; ++I, ++Index) {
3154     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3155       return Index;
3156   }
3157 
3158   llvm_unreachable("base class missing from derived class's bases list");
3159 }
3160 
3161 /// Extract the value of a character from a string literal.
3162 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3163                                             uint64_t Index) {
3164   assert(!isa<SourceLocExpr>(Lit) &&
3165          "SourceLocExpr should have already been converted to a StringLiteral");
3166 
3167   // FIXME: Support MakeStringConstant
3168   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3169     std::string Str;
3170     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3171     assert(Index <= Str.size() && "Index too large");
3172     return APSInt::getUnsigned(Str.c_str()[Index]);
3173   }
3174 
3175   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3176     Lit = PE->getFunctionName();
3177   const StringLiteral *S = cast<StringLiteral>(Lit);
3178   const ConstantArrayType *CAT =
3179       Info.Ctx.getAsConstantArrayType(S->getType());
3180   assert(CAT && "string literal isn't an array");
3181   QualType CharType = CAT->getElementType();
3182   assert(CharType->isIntegerType() && "unexpected character type");
3183 
3184   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3185                CharType->isUnsignedIntegerType());
3186   if (Index < S->getLength())
3187     Value = S->getCodeUnit(Index);
3188   return Value;
3189 }
3190 
3191 // Expand a string literal into an array of characters.
3192 //
3193 // FIXME: This is inefficient; we should probably introduce something similar
3194 // to the LLVM ConstantDataArray to make this cheaper.
3195 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3196                                 APValue &Result,
3197                                 QualType AllocType = QualType()) {
3198   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3199       AllocType.isNull() ? S->getType() : AllocType);
3200   assert(CAT && "string literal isn't an array");
3201   QualType CharType = CAT->getElementType();
3202   assert(CharType->isIntegerType() && "unexpected character type");
3203 
3204   unsigned Elts = CAT->getSize().getZExtValue();
3205   Result = APValue(APValue::UninitArray(),
3206                    std::min(S->getLength(), Elts), Elts);
3207   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3208                CharType->isUnsignedIntegerType());
3209   if (Result.hasArrayFiller())
3210     Result.getArrayFiller() = APValue(Value);
3211   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3212     Value = S->getCodeUnit(I);
3213     Result.getArrayInitializedElt(I) = APValue(Value);
3214   }
3215 }
3216 
3217 // Expand an array so that it has more than Index filled elements.
3218 static void expandArray(APValue &Array, unsigned Index) {
3219   unsigned Size = Array.getArraySize();
3220   assert(Index < Size);
3221 
3222   // Always at least double the number of elements for which we store a value.
3223   unsigned OldElts = Array.getArrayInitializedElts();
3224   unsigned NewElts = std::max(Index+1, OldElts * 2);
3225   NewElts = std::min(Size, std::max(NewElts, 8u));
3226 
3227   // Copy the data across.
3228   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3229   for (unsigned I = 0; I != OldElts; ++I)
3230     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3231   for (unsigned I = OldElts; I != NewElts; ++I)
3232     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3233   if (NewValue.hasArrayFiller())
3234     NewValue.getArrayFiller() = Array.getArrayFiller();
3235   Array.swap(NewValue);
3236 }
3237 
3238 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3239 /// conversion. If it's of class type, we may assume that the copy operation
3240 /// is trivial. Note that this is never true for a union type with fields
3241 /// (because the copy always "reads" the active member) and always true for
3242 /// a non-class type.
3243 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3244 static bool isReadByLvalueToRvalueConversion(QualType T) {
3245   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3246   return !RD || isReadByLvalueToRvalueConversion(RD);
3247 }
3248 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3249   // FIXME: A trivial copy of a union copies the object representation, even if
3250   // the union is empty.
3251   if (RD->isUnion())
3252     return !RD->field_empty();
3253   if (RD->isEmpty())
3254     return false;
3255 
3256   for (auto *Field : RD->fields())
3257     if (!Field->isUnnamedBitfield() &&
3258         isReadByLvalueToRvalueConversion(Field->getType()))
3259       return true;
3260 
3261   for (auto &BaseSpec : RD->bases())
3262     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3263       return true;
3264 
3265   return false;
3266 }
3267 
3268 /// Diagnose an attempt to read from any unreadable field within the specified
3269 /// type, which might be a class type.
3270 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3271                                   QualType T) {
3272   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3273   if (!RD)
3274     return false;
3275 
3276   if (!RD->hasMutableFields())
3277     return false;
3278 
3279   for (auto *Field : RD->fields()) {
3280     // If we're actually going to read this field in some way, then it can't
3281     // be mutable. If we're in a union, then assigning to a mutable field
3282     // (even an empty one) can change the active member, so that's not OK.
3283     // FIXME: Add core issue number for the union case.
3284     if (Field->isMutable() &&
3285         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3286       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3287       Info.Note(Field->getLocation(), diag::note_declared_at);
3288       return true;
3289     }
3290 
3291     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3292       return true;
3293   }
3294 
3295   for (auto &BaseSpec : RD->bases())
3296     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3297       return true;
3298 
3299   // All mutable fields were empty, and thus not actually read.
3300   return false;
3301 }
3302 
3303 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3304                                         APValue::LValueBase Base,
3305                                         bool MutableSubobject = false) {
3306   // A temporary we created.
3307   if (Base.getCallIndex())
3308     return true;
3309 
3310   auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3311   if (!Evaluating)
3312     return false;
3313 
3314   auto *BaseD = Base.dyn_cast<const ValueDecl*>();
3315 
3316   switch (Info.IsEvaluatingDecl) {
3317   case EvalInfo::EvaluatingDeclKind::None:
3318     return false;
3319 
3320   case EvalInfo::EvaluatingDeclKind::Ctor:
3321     // The variable whose initializer we're evaluating.
3322     if (BaseD)
3323       return declaresSameEntity(Evaluating, BaseD);
3324 
3325     // A temporary lifetime-extended by the variable whose initializer we're
3326     // evaluating.
3327     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3328       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3329         return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating);
3330     return false;
3331 
3332   case EvalInfo::EvaluatingDeclKind::Dtor:
3333     // C++2a [expr.const]p6:
3334     //   [during constant destruction] the lifetime of a and its non-mutable
3335     //   subobjects (but not its mutable subobjects) [are] considered to start
3336     //   within e.
3337     //
3338     // FIXME: We can meaningfully extend this to cover non-const objects, but
3339     // we will need special handling: we should be able to access only
3340     // subobjects of such objects that are themselves declared const.
3341     if (!BaseD ||
3342         !(BaseD->getType().isConstQualified() ||
3343           BaseD->getType()->isReferenceType()) ||
3344         MutableSubobject)
3345       return false;
3346     return declaresSameEntity(Evaluating, BaseD);
3347   }
3348 
3349   llvm_unreachable("unknown evaluating decl kind");
3350 }
3351 
3352 namespace {
3353 /// A handle to a complete object (an object that is not a subobject of
3354 /// another object).
3355 struct CompleteObject {
3356   /// The identity of the object.
3357   APValue::LValueBase Base;
3358   /// The value of the complete object.
3359   APValue *Value;
3360   /// The type of the complete object.
3361   QualType Type;
3362 
3363   CompleteObject() : Value(nullptr) {}
3364   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3365       : Base(Base), Value(Value), Type(Type) {}
3366 
3367   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3368     // If this isn't a "real" access (eg, if it's just accessing the type
3369     // info), allow it. We assume the type doesn't change dynamically for
3370     // subobjects of constexpr objects (even though we'd hit UB here if it
3371     // did). FIXME: Is this right?
3372     if (!isAnyAccess(AK))
3373       return true;
3374 
3375     // In C++14 onwards, it is permitted to read a mutable member whose
3376     // lifetime began within the evaluation.
3377     // FIXME: Should we also allow this in C++11?
3378     if (!Info.getLangOpts().CPlusPlus14)
3379       return false;
3380     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3381   }
3382 
3383   explicit operator bool() const { return !Type.isNull(); }
3384 };
3385 } // end anonymous namespace
3386 
3387 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3388                                  bool IsMutable = false) {
3389   // C++ [basic.type.qualifier]p1:
3390   // - A const object is an object of type const T or a non-mutable subobject
3391   //   of a const object.
3392   if (ObjType.isConstQualified() && !IsMutable)
3393     SubobjType.addConst();
3394   // - A volatile object is an object of type const T or a subobject of a
3395   //   volatile object.
3396   if (ObjType.isVolatileQualified())
3397     SubobjType.addVolatile();
3398   return SubobjType;
3399 }
3400 
3401 /// Find the designated sub-object of an rvalue.
3402 template<typename SubobjectHandler>
3403 typename SubobjectHandler::result_type
3404 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3405               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3406   if (Sub.Invalid)
3407     // A diagnostic will have already been produced.
3408     return handler.failed();
3409   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3410     if (Info.getLangOpts().CPlusPlus11)
3411       Info.FFDiag(E, Sub.isOnePastTheEnd()
3412                          ? diag::note_constexpr_access_past_end
3413                          : diag::note_constexpr_access_unsized_array)
3414           << handler.AccessKind;
3415     else
3416       Info.FFDiag(E);
3417     return handler.failed();
3418   }
3419 
3420   APValue *O = Obj.Value;
3421   QualType ObjType = Obj.Type;
3422   const FieldDecl *LastField = nullptr;
3423   const FieldDecl *VolatileField = nullptr;
3424 
3425   // Walk the designator's path to find the subobject.
3426   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3427     // Reading an indeterminate value is undefined, but assigning over one is OK.
3428     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3429         (O->isIndeterminate() &&
3430          !isValidIndeterminateAccess(handler.AccessKind))) {
3431       if (!Info.checkingPotentialConstantExpression())
3432         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3433             << handler.AccessKind << O->isIndeterminate();
3434       return handler.failed();
3435     }
3436 
3437     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3438     //    const and volatile semantics are not applied on an object under
3439     //    {con,de}struction.
3440     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3441         ObjType->isRecordType() &&
3442         Info.isEvaluatingCtorDtor(
3443             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3444                                          Sub.Entries.begin() + I)) !=
3445                           ConstructionPhase::None) {
3446       ObjType = Info.Ctx.getCanonicalType(ObjType);
3447       ObjType.removeLocalConst();
3448       ObjType.removeLocalVolatile();
3449     }
3450 
3451     // If this is our last pass, check that the final object type is OK.
3452     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3453       // Accesses to volatile objects are prohibited.
3454       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3455         if (Info.getLangOpts().CPlusPlus) {
3456           int DiagKind;
3457           SourceLocation Loc;
3458           const NamedDecl *Decl = nullptr;
3459           if (VolatileField) {
3460             DiagKind = 2;
3461             Loc = VolatileField->getLocation();
3462             Decl = VolatileField;
3463           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3464             DiagKind = 1;
3465             Loc = VD->getLocation();
3466             Decl = VD;
3467           } else {
3468             DiagKind = 0;
3469             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3470               Loc = E->getExprLoc();
3471           }
3472           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3473               << handler.AccessKind << DiagKind << Decl;
3474           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3475         } else {
3476           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3477         }
3478         return handler.failed();
3479       }
3480 
3481       // If we are reading an object of class type, there may still be more
3482       // things we need to check: if there are any mutable subobjects, we
3483       // cannot perform this read. (This only happens when performing a trivial
3484       // copy or assignment.)
3485       if (ObjType->isRecordType() &&
3486           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3487           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3488         return handler.failed();
3489     }
3490 
3491     if (I == N) {
3492       if (!handler.found(*O, ObjType))
3493         return false;
3494 
3495       // If we modified a bit-field, truncate it to the right width.
3496       if (isModification(handler.AccessKind) &&
3497           LastField && LastField->isBitField() &&
3498           !truncateBitfieldValue(Info, E, *O, LastField))
3499         return false;
3500 
3501       return true;
3502     }
3503 
3504     LastField = nullptr;
3505     if (ObjType->isArrayType()) {
3506       // Next subobject is an array element.
3507       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3508       assert(CAT && "vla in literal type?");
3509       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3510       if (CAT->getSize().ule(Index)) {
3511         // Note, it should not be possible to form a pointer with a valid
3512         // designator which points more than one past the end of the array.
3513         if (Info.getLangOpts().CPlusPlus11)
3514           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3515             << handler.AccessKind;
3516         else
3517           Info.FFDiag(E);
3518         return handler.failed();
3519       }
3520 
3521       ObjType = CAT->getElementType();
3522 
3523       if (O->getArrayInitializedElts() > Index)
3524         O = &O->getArrayInitializedElt(Index);
3525       else if (!isRead(handler.AccessKind)) {
3526         expandArray(*O, Index);
3527         O = &O->getArrayInitializedElt(Index);
3528       } else
3529         O = &O->getArrayFiller();
3530     } else if (ObjType->isAnyComplexType()) {
3531       // Next subobject is a complex number.
3532       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3533       if (Index > 1) {
3534         if (Info.getLangOpts().CPlusPlus11)
3535           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3536             << handler.AccessKind;
3537         else
3538           Info.FFDiag(E);
3539         return handler.failed();
3540       }
3541 
3542       ObjType = getSubobjectType(
3543           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3544 
3545       assert(I == N - 1 && "extracting subobject of scalar?");
3546       if (O->isComplexInt()) {
3547         return handler.found(Index ? O->getComplexIntImag()
3548                                    : O->getComplexIntReal(), ObjType);
3549       } else {
3550         assert(O->isComplexFloat());
3551         return handler.found(Index ? O->getComplexFloatImag()
3552                                    : O->getComplexFloatReal(), ObjType);
3553       }
3554     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3555       if (Field->isMutable() &&
3556           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3557         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3558           << handler.AccessKind << Field;
3559         Info.Note(Field->getLocation(), diag::note_declared_at);
3560         return handler.failed();
3561       }
3562 
3563       // Next subobject is a class, struct or union field.
3564       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3565       if (RD->isUnion()) {
3566         const FieldDecl *UnionField = O->getUnionField();
3567         if (!UnionField ||
3568             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3569           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3570             // Placement new onto an inactive union member makes it active.
3571             O->setUnion(Field, APValue());
3572           } else {
3573             // FIXME: If O->getUnionValue() is absent, report that there's no
3574             // active union member rather than reporting the prior active union
3575             // member. We'll need to fix nullptr_t to not use APValue() as its
3576             // representation first.
3577             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3578                 << handler.AccessKind << Field << !UnionField << UnionField;
3579             return handler.failed();
3580           }
3581         }
3582         O = &O->getUnionValue();
3583       } else
3584         O = &O->getStructField(Field->getFieldIndex());
3585 
3586       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3587       LastField = Field;
3588       if (Field->getType().isVolatileQualified())
3589         VolatileField = Field;
3590     } else {
3591       // Next subobject is a base class.
3592       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3593       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3594       O = &O->getStructBase(getBaseIndex(Derived, Base));
3595 
3596       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3597     }
3598   }
3599 }
3600 
3601 namespace {
3602 struct ExtractSubobjectHandler {
3603   EvalInfo &Info;
3604   const Expr *E;
3605   APValue &Result;
3606   const AccessKinds AccessKind;
3607 
3608   typedef bool result_type;
3609   bool failed() { return false; }
3610   bool found(APValue &Subobj, QualType SubobjType) {
3611     Result = Subobj;
3612     if (AccessKind == AK_ReadObjectRepresentation)
3613       return true;
3614     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3615   }
3616   bool found(APSInt &Value, QualType SubobjType) {
3617     Result = APValue(Value);
3618     return true;
3619   }
3620   bool found(APFloat &Value, QualType SubobjType) {
3621     Result = APValue(Value);
3622     return true;
3623   }
3624 };
3625 } // end anonymous namespace
3626 
3627 /// Extract the designated sub-object of an rvalue.
3628 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3629                              const CompleteObject &Obj,
3630                              const SubobjectDesignator &Sub, APValue &Result,
3631                              AccessKinds AK = AK_Read) {
3632   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3633   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3634   return findSubobject(Info, E, Obj, Sub, Handler);
3635 }
3636 
3637 namespace {
3638 struct ModifySubobjectHandler {
3639   EvalInfo &Info;
3640   APValue &NewVal;
3641   const Expr *E;
3642 
3643   typedef bool result_type;
3644   static const AccessKinds AccessKind = AK_Assign;
3645 
3646   bool checkConst(QualType QT) {
3647     // Assigning to a const object has undefined behavior.
3648     if (QT.isConstQualified()) {
3649       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3650       return false;
3651     }
3652     return true;
3653   }
3654 
3655   bool failed() { return false; }
3656   bool found(APValue &Subobj, QualType SubobjType) {
3657     if (!checkConst(SubobjType))
3658       return false;
3659     // We've been given ownership of NewVal, so just swap it in.
3660     Subobj.swap(NewVal);
3661     return true;
3662   }
3663   bool found(APSInt &Value, QualType SubobjType) {
3664     if (!checkConst(SubobjType))
3665       return false;
3666     if (!NewVal.isInt()) {
3667       // Maybe trying to write a cast pointer value into a complex?
3668       Info.FFDiag(E);
3669       return false;
3670     }
3671     Value = NewVal.getInt();
3672     return true;
3673   }
3674   bool found(APFloat &Value, QualType SubobjType) {
3675     if (!checkConst(SubobjType))
3676       return false;
3677     Value = NewVal.getFloat();
3678     return true;
3679   }
3680 };
3681 } // end anonymous namespace
3682 
3683 const AccessKinds ModifySubobjectHandler::AccessKind;
3684 
3685 /// Update the designated sub-object of an rvalue to the given value.
3686 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3687                             const CompleteObject &Obj,
3688                             const SubobjectDesignator &Sub,
3689                             APValue &NewVal) {
3690   ModifySubobjectHandler Handler = { Info, NewVal, E };
3691   return findSubobject(Info, E, Obj, Sub, Handler);
3692 }
3693 
3694 /// Find the position where two subobject designators diverge, or equivalently
3695 /// the length of the common initial subsequence.
3696 static unsigned FindDesignatorMismatch(QualType ObjType,
3697                                        const SubobjectDesignator &A,
3698                                        const SubobjectDesignator &B,
3699                                        bool &WasArrayIndex) {
3700   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3701   for (/**/; I != N; ++I) {
3702     if (!ObjType.isNull() &&
3703         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3704       // Next subobject is an array element.
3705       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3706         WasArrayIndex = true;
3707         return I;
3708       }
3709       if (ObjType->isAnyComplexType())
3710         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3711       else
3712         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3713     } else {
3714       if (A.Entries[I].getAsBaseOrMember() !=
3715           B.Entries[I].getAsBaseOrMember()) {
3716         WasArrayIndex = false;
3717         return I;
3718       }
3719       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3720         // Next subobject is a field.
3721         ObjType = FD->getType();
3722       else
3723         // Next subobject is a base class.
3724         ObjType = QualType();
3725     }
3726   }
3727   WasArrayIndex = false;
3728   return I;
3729 }
3730 
3731 /// Determine whether the given subobject designators refer to elements of the
3732 /// same array object.
3733 static bool AreElementsOfSameArray(QualType ObjType,
3734                                    const SubobjectDesignator &A,
3735                                    const SubobjectDesignator &B) {
3736   if (A.Entries.size() != B.Entries.size())
3737     return false;
3738 
3739   bool IsArray = A.MostDerivedIsArrayElement;
3740   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3741     // A is a subobject of the array element.
3742     return false;
3743 
3744   // If A (and B) designates an array element, the last entry will be the array
3745   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3746   // of length 1' case, and the entire path must match.
3747   bool WasArrayIndex;
3748   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3749   return CommonLength >= A.Entries.size() - IsArray;
3750 }
3751 
3752 /// Find the complete object to which an LValue refers.
3753 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3754                                          AccessKinds AK, const LValue &LVal,
3755                                          QualType LValType) {
3756   if (LVal.InvalidBase) {
3757     Info.FFDiag(E);
3758     return CompleteObject();
3759   }
3760 
3761   if (!LVal.Base) {
3762     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3763     return CompleteObject();
3764   }
3765 
3766   CallStackFrame *Frame = nullptr;
3767   unsigned Depth = 0;
3768   if (LVal.getLValueCallIndex()) {
3769     std::tie(Frame, Depth) =
3770         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3771     if (!Frame) {
3772       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3773         << AK << LVal.Base.is<const ValueDecl*>();
3774       NoteLValueLocation(Info, LVal.Base);
3775       return CompleteObject();
3776     }
3777   }
3778 
3779   bool IsAccess = isAnyAccess(AK);
3780 
3781   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3782   // is not a constant expression (even if the object is non-volatile). We also
3783   // apply this rule to C++98, in order to conform to the expected 'volatile'
3784   // semantics.
3785   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3786     if (Info.getLangOpts().CPlusPlus)
3787       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3788         << AK << LValType;
3789     else
3790       Info.FFDiag(E);
3791     return CompleteObject();
3792   }
3793 
3794   // Compute value storage location and type of base object.
3795   APValue *BaseVal = nullptr;
3796   QualType BaseType = getType(LVal.Base);
3797 
3798   if (const ConstantExpr *CE =
3799           dyn_cast_or_null<ConstantExpr>(LVal.Base.dyn_cast<const Expr *>())) {
3800     /// Nested immediate invocation have been previously removed so if we found
3801     /// a ConstantExpr it can only be the EvaluatingDecl.
3802     assert(CE->isImmediateInvocation() && CE == Info.EvaluatingDecl);
3803     (void)CE;
3804     BaseVal = Info.EvaluatingDeclValue;
3805   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
3806     // Allow reading from a GUID declaration.
3807     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
3808       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       }
3813       APValue &V = GD->getAsAPValue();
3814       if (V.isAbsent()) {
3815         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
3816             << GD->getType();
3817         return CompleteObject();
3818       }
3819       return CompleteObject(LVal.Base, &V, GD->getType());
3820     }
3821 
3822     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3823     // In C++11, constexpr, non-volatile variables initialized with constant
3824     // expressions are constant expressions too. Inside constexpr functions,
3825     // parameters are constant expressions even if they're non-const.
3826     // In C++1y, objects local to a constant expression (those with a Frame) are
3827     // both readable and writable inside constant expressions.
3828     // In C, such things can also be folded, although they are not ICEs.
3829     const VarDecl *VD = dyn_cast<VarDecl>(D);
3830     if (VD) {
3831       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3832         VD = VDef;
3833     }
3834     if (!VD || VD->isInvalidDecl()) {
3835       Info.FFDiag(E);
3836       return CompleteObject();
3837     }
3838 
3839     // In OpenCL if a variable is in constant address space it is a const value.
3840     bool IsConstant = BaseType.isConstQualified() ||
3841                       (Info.getLangOpts().OpenCL &&
3842                        BaseType.getAddressSpace() == LangAS::opencl_constant);
3843 
3844     // Unless we're looking at a local variable or argument in a constexpr call,
3845     // the variable we're reading must be const.
3846     if (!Frame) {
3847       if (Info.getLangOpts().CPlusPlus14 &&
3848           lifetimeStartedInEvaluation(Info, LVal.Base)) {
3849         // OK, we can read and modify an object if we're in the process of
3850         // evaluating its initializer, because its lifetime began in this
3851         // evaluation.
3852       } else if (isModification(AK)) {
3853         // All the remaining cases do not permit modification of the object.
3854         Info.FFDiag(E, diag::note_constexpr_modify_global);
3855         return CompleteObject();
3856       } else if (VD->isConstexpr()) {
3857         // OK, we can read this variable.
3858       } else if (BaseType->isIntegralOrEnumerationType()) {
3859         // In OpenCL if a variable is in constant address space it is a const
3860         // value.
3861         if (!IsConstant) {
3862           if (!IsAccess)
3863             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3864           if (Info.getLangOpts().CPlusPlus) {
3865             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3866             Info.Note(VD->getLocation(), diag::note_declared_at);
3867           } else {
3868             Info.FFDiag(E);
3869           }
3870           return CompleteObject();
3871         }
3872       } else if (!IsAccess) {
3873         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3874       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
3875                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
3876         // This variable might end up being constexpr. Don't diagnose it yet.
3877       } else if (IsConstant) {
3878         // Keep evaluating to see what we can do. In particular, we support
3879         // folding of const floating-point types, in order to make static const
3880         // data members of such types (supported as an extension) more useful.
3881         if (Info.getLangOpts().CPlusPlus) {
3882           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
3883                               ? diag::note_constexpr_ltor_non_constexpr
3884                               : diag::note_constexpr_ltor_non_integral, 1)
3885               << VD << BaseType;
3886           Info.Note(VD->getLocation(), diag::note_declared_at);
3887         } else {
3888           Info.CCEDiag(E);
3889         }
3890       } else {
3891         // Never allow reading a non-const value.
3892         if (Info.getLangOpts().CPlusPlus) {
3893           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3894                              ? diag::note_constexpr_ltor_non_constexpr
3895                              : diag::note_constexpr_ltor_non_integral, 1)
3896               << VD << BaseType;
3897           Info.Note(VD->getLocation(), diag::note_declared_at);
3898         } else {
3899           Info.FFDiag(E);
3900         }
3901         return CompleteObject();
3902       }
3903     }
3904 
3905     if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
3906       return CompleteObject();
3907   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
3908     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
3909     if (!Alloc) {
3910       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
3911       return CompleteObject();
3912     }
3913     return CompleteObject(LVal.Base, &(*Alloc)->Value,
3914                           LVal.Base.getDynamicAllocType());
3915   } else {
3916     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3917 
3918     if (!Frame) {
3919       if (const MaterializeTemporaryExpr *MTE =
3920               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
3921         assert(MTE->getStorageDuration() == SD_Static &&
3922                "should have a frame for a non-global materialized temporary");
3923 
3924         // Per C++1y [expr.const]p2:
3925         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3926         //   - a [...] glvalue of integral or enumeration type that refers to
3927         //     a non-volatile const object [...]
3928         //   [...]
3929         //   - a [...] glvalue of literal type that refers to a non-volatile
3930         //     object whose lifetime began within the evaluation of e.
3931         //
3932         // C++11 misses the 'began within the evaluation of e' check and
3933         // instead allows all temporaries, including things like:
3934         //   int &&r = 1;
3935         //   int x = ++r;
3936         //   constexpr int k = r;
3937         // Therefore we use the C++14 rules in C++11 too.
3938         //
3939         // Note that temporaries whose lifetimes began while evaluating a
3940         // variable's constructor are not usable while evaluating the
3941         // corresponding destructor, not even if they're of const-qualified
3942         // types.
3943         if (!(BaseType.isConstQualified() &&
3944               BaseType->isIntegralOrEnumerationType()) &&
3945             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
3946           if (!IsAccess)
3947             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3948           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3949           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3950           return CompleteObject();
3951         }
3952 
3953         BaseVal = MTE->getOrCreateValue(false);
3954         assert(BaseVal && "got reference to unevaluated temporary");
3955       } else {
3956         if (!IsAccess)
3957           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3958         APValue Val;
3959         LVal.moveInto(Val);
3960         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3961             << AK
3962             << Val.getAsString(Info.Ctx,
3963                                Info.Ctx.getLValueReferenceType(LValType));
3964         NoteLValueLocation(Info, LVal.Base);
3965         return CompleteObject();
3966       }
3967     } else {
3968       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
3969       assert(BaseVal && "missing value for temporary");
3970     }
3971   }
3972 
3973   // In C++14, we can't safely access any mutable state when we might be
3974   // evaluating after an unmodeled side effect.
3975   //
3976   // FIXME: Not all local state is mutable. Allow local constant subobjects
3977   // to be read here (but take care with 'mutable' fields).
3978   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3979        Info.EvalStatus.HasSideEffects) ||
3980       (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
3981     return CompleteObject();
3982 
3983   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
3984 }
3985 
3986 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
3987 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3988 /// glvalue referred to by an entity of reference type.
3989 ///
3990 /// \param Info - Information about the ongoing evaluation.
3991 /// \param Conv - The expression for which we are performing the conversion.
3992 ///               Used for diagnostics.
3993 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3994 ///               case of a non-class type).
3995 /// \param LVal - The glvalue on which we are attempting to perform this action.
3996 /// \param RVal - The produced value will be placed here.
3997 /// \param WantObjectRepresentation - If true, we're looking for the object
3998 ///               representation rather than the value, and in particular,
3999 ///               there is no requirement that the result be fully initialized.
4000 static bool
4001 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4002                                const LValue &LVal, APValue &RVal,
4003                                bool WantObjectRepresentation = false) {
4004   if (LVal.Designator.Invalid)
4005     return false;
4006 
4007   // Check for special cases where there is no existing APValue to look at.
4008   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4009 
4010   AccessKinds AK =
4011       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4012 
4013   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4014     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4015       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4016       // initializer until now for such expressions. Such an expression can't be
4017       // an ICE in C, so this only matters for fold.
4018       if (Type.isVolatileQualified()) {
4019         Info.FFDiag(Conv);
4020         return false;
4021       }
4022       APValue Lit;
4023       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4024         return false;
4025       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4026       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4027     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4028       // Special-case character extraction so we don't have to construct an
4029       // APValue for the whole string.
4030       assert(LVal.Designator.Entries.size() <= 1 &&
4031              "Can only read characters from string literals");
4032       if (LVal.Designator.Entries.empty()) {
4033         // Fail for now for LValue to RValue conversion of an array.
4034         // (This shouldn't show up in C/C++, but it could be triggered by a
4035         // weird EvaluateAsRValue call from a tool.)
4036         Info.FFDiag(Conv);
4037         return false;
4038       }
4039       if (LVal.Designator.isOnePastTheEnd()) {
4040         if (Info.getLangOpts().CPlusPlus11)
4041           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4042         else
4043           Info.FFDiag(Conv);
4044         return false;
4045       }
4046       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4047       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4048       return true;
4049     }
4050   }
4051 
4052   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4053   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4054 }
4055 
4056 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4057 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4058                              QualType LValType, APValue &Val) {
4059   if (LVal.Designator.Invalid)
4060     return false;
4061 
4062   if (!Info.getLangOpts().CPlusPlus14) {
4063     Info.FFDiag(E);
4064     return false;
4065   }
4066 
4067   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4068   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4069 }
4070 
4071 namespace {
4072 struct CompoundAssignSubobjectHandler {
4073   EvalInfo &Info;
4074   const Expr *E;
4075   QualType PromotedLHSType;
4076   BinaryOperatorKind Opcode;
4077   const APValue &RHS;
4078 
4079   static const AccessKinds AccessKind = AK_Assign;
4080 
4081   typedef bool result_type;
4082 
4083   bool checkConst(QualType QT) {
4084     // Assigning to a const object has undefined behavior.
4085     if (QT.isConstQualified()) {
4086       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4087       return false;
4088     }
4089     return true;
4090   }
4091 
4092   bool failed() { return false; }
4093   bool found(APValue &Subobj, QualType SubobjType) {
4094     switch (Subobj.getKind()) {
4095     case APValue::Int:
4096       return found(Subobj.getInt(), SubobjType);
4097     case APValue::Float:
4098       return found(Subobj.getFloat(), SubobjType);
4099     case APValue::ComplexInt:
4100     case APValue::ComplexFloat:
4101       // FIXME: Implement complex compound assignment.
4102       Info.FFDiag(E);
4103       return false;
4104     case APValue::LValue:
4105       return foundPointer(Subobj, SubobjType);
4106     case APValue::Vector:
4107       return foundVector(Subobj, SubobjType);
4108     default:
4109       // FIXME: can this happen?
4110       Info.FFDiag(E);
4111       return false;
4112     }
4113   }
4114 
4115   bool foundVector(APValue &Value, QualType SubobjType) {
4116     if (!checkConst(SubobjType))
4117       return false;
4118 
4119     if (!SubobjType->isVectorType()) {
4120       Info.FFDiag(E);
4121       return false;
4122     }
4123     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4124   }
4125 
4126   bool found(APSInt &Value, QualType SubobjType) {
4127     if (!checkConst(SubobjType))
4128       return false;
4129 
4130     if (!SubobjType->isIntegerType()) {
4131       // We don't support compound assignment on integer-cast-to-pointer
4132       // values.
4133       Info.FFDiag(E);
4134       return false;
4135     }
4136 
4137     if (RHS.isInt()) {
4138       APSInt LHS =
4139           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4140       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4141         return false;
4142       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4143       return true;
4144     } else if (RHS.isFloat()) {
4145       APFloat FValue(0.0);
4146       return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
4147                                   FValue) &&
4148              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4149              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4150                                   Value);
4151     }
4152 
4153     Info.FFDiag(E);
4154     return false;
4155   }
4156   bool found(APFloat &Value, QualType SubobjType) {
4157     return checkConst(SubobjType) &&
4158            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4159                                   Value) &&
4160            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4161            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4162   }
4163   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4164     if (!checkConst(SubobjType))
4165       return false;
4166 
4167     QualType PointeeType;
4168     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4169       PointeeType = PT->getPointeeType();
4170 
4171     if (PointeeType.isNull() || !RHS.isInt() ||
4172         (Opcode != BO_Add && Opcode != BO_Sub)) {
4173       Info.FFDiag(E);
4174       return false;
4175     }
4176 
4177     APSInt Offset = RHS.getInt();
4178     if (Opcode == BO_Sub)
4179       negateAsSigned(Offset);
4180 
4181     LValue LVal;
4182     LVal.setFrom(Info.Ctx, Subobj);
4183     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4184       return false;
4185     LVal.moveInto(Subobj);
4186     return true;
4187   }
4188 };
4189 } // end anonymous namespace
4190 
4191 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4192 
4193 /// Perform a compound assignment of LVal <op>= RVal.
4194 static bool handleCompoundAssignment(
4195     EvalInfo &Info, const Expr *E,
4196     const LValue &LVal, QualType LValType, QualType PromotedLValType,
4197     BinaryOperatorKind Opcode, const APValue &RVal) {
4198   if (LVal.Designator.Invalid)
4199     return false;
4200 
4201   if (!Info.getLangOpts().CPlusPlus14) {
4202     Info.FFDiag(E);
4203     return false;
4204   }
4205 
4206   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4207   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4208                                              RVal };
4209   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4210 }
4211 
4212 namespace {
4213 struct IncDecSubobjectHandler {
4214   EvalInfo &Info;
4215   const UnaryOperator *E;
4216   AccessKinds AccessKind;
4217   APValue *Old;
4218 
4219   typedef bool result_type;
4220 
4221   bool checkConst(QualType QT) {
4222     // Assigning to a const object has undefined behavior.
4223     if (QT.isConstQualified()) {
4224       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4225       return false;
4226     }
4227     return true;
4228   }
4229 
4230   bool failed() { return false; }
4231   bool found(APValue &Subobj, QualType SubobjType) {
4232     // Stash the old value. Also clear Old, so we don't clobber it later
4233     // if we're post-incrementing a complex.
4234     if (Old) {
4235       *Old = Subobj;
4236       Old = nullptr;
4237     }
4238 
4239     switch (Subobj.getKind()) {
4240     case APValue::Int:
4241       return found(Subobj.getInt(), SubobjType);
4242     case APValue::Float:
4243       return found(Subobj.getFloat(), SubobjType);
4244     case APValue::ComplexInt:
4245       return found(Subobj.getComplexIntReal(),
4246                    SubobjType->castAs<ComplexType>()->getElementType()
4247                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4248     case APValue::ComplexFloat:
4249       return found(Subobj.getComplexFloatReal(),
4250                    SubobjType->castAs<ComplexType>()->getElementType()
4251                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4252     case APValue::LValue:
4253       return foundPointer(Subobj, SubobjType);
4254     default:
4255       // FIXME: can this happen?
4256       Info.FFDiag(E);
4257       return false;
4258     }
4259   }
4260   bool found(APSInt &Value, QualType SubobjType) {
4261     if (!checkConst(SubobjType))
4262       return false;
4263 
4264     if (!SubobjType->isIntegerType()) {
4265       // We don't support increment / decrement on integer-cast-to-pointer
4266       // values.
4267       Info.FFDiag(E);
4268       return false;
4269     }
4270 
4271     if (Old) *Old = APValue(Value);
4272 
4273     // bool arithmetic promotes to int, and the conversion back to bool
4274     // doesn't reduce mod 2^n, so special-case it.
4275     if (SubobjType->isBooleanType()) {
4276       if (AccessKind == AK_Increment)
4277         Value = 1;
4278       else
4279         Value = !Value;
4280       return true;
4281     }
4282 
4283     bool WasNegative = Value.isNegative();
4284     if (AccessKind == AK_Increment) {
4285       ++Value;
4286 
4287       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4288         APSInt ActualValue(Value, /*IsUnsigned*/true);
4289         return HandleOverflow(Info, E, ActualValue, SubobjType);
4290       }
4291     } else {
4292       --Value;
4293 
4294       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4295         unsigned BitWidth = Value.getBitWidth();
4296         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4297         ActualValue.setBit(BitWidth);
4298         return HandleOverflow(Info, E, ActualValue, SubobjType);
4299       }
4300     }
4301     return true;
4302   }
4303   bool found(APFloat &Value, QualType SubobjType) {
4304     if (!checkConst(SubobjType))
4305       return false;
4306 
4307     if (Old) *Old = APValue(Value);
4308 
4309     APFloat One(Value.getSemantics(), 1);
4310     if (AccessKind == AK_Increment)
4311       Value.add(One, APFloat::rmNearestTiesToEven);
4312     else
4313       Value.subtract(One, APFloat::rmNearestTiesToEven);
4314     return true;
4315   }
4316   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4317     if (!checkConst(SubobjType))
4318       return false;
4319 
4320     QualType PointeeType;
4321     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4322       PointeeType = PT->getPointeeType();
4323     else {
4324       Info.FFDiag(E);
4325       return false;
4326     }
4327 
4328     LValue LVal;
4329     LVal.setFrom(Info.Ctx, Subobj);
4330     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4331                                      AccessKind == AK_Increment ? 1 : -1))
4332       return false;
4333     LVal.moveInto(Subobj);
4334     return true;
4335   }
4336 };
4337 } // end anonymous namespace
4338 
4339 /// Perform an increment or decrement on LVal.
4340 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4341                          QualType LValType, bool IsIncrement, APValue *Old) {
4342   if (LVal.Designator.Invalid)
4343     return false;
4344 
4345   if (!Info.getLangOpts().CPlusPlus14) {
4346     Info.FFDiag(E);
4347     return false;
4348   }
4349 
4350   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4351   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4352   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4353   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4354 }
4355 
4356 /// Build an lvalue for the object argument of a member function call.
4357 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4358                                    LValue &This) {
4359   if (Object->getType()->isPointerType() && Object->isRValue())
4360     return EvaluatePointer(Object, This, Info);
4361 
4362   if (Object->isGLValue())
4363     return EvaluateLValue(Object, This, Info);
4364 
4365   if (Object->getType()->isLiteralType(Info.Ctx))
4366     return EvaluateTemporary(Object, This, Info);
4367 
4368   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4369   return false;
4370 }
4371 
4372 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4373 /// lvalue referring to the result.
4374 ///
4375 /// \param Info - Information about the ongoing evaluation.
4376 /// \param LV - An lvalue referring to the base of the member pointer.
4377 /// \param RHS - The member pointer expression.
4378 /// \param IncludeMember - Specifies whether the member itself is included in
4379 ///        the resulting LValue subobject designator. This is not possible when
4380 ///        creating a bound member function.
4381 /// \return The field or method declaration to which the member pointer refers,
4382 ///         or 0 if evaluation fails.
4383 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4384                                                   QualType LVType,
4385                                                   LValue &LV,
4386                                                   const Expr *RHS,
4387                                                   bool IncludeMember = true) {
4388   MemberPtr MemPtr;
4389   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4390     return nullptr;
4391 
4392   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4393   // member value, the behavior is undefined.
4394   if (!MemPtr.getDecl()) {
4395     // FIXME: Specific diagnostic.
4396     Info.FFDiag(RHS);
4397     return nullptr;
4398   }
4399 
4400   if (MemPtr.isDerivedMember()) {
4401     // This is a member of some derived class. Truncate LV appropriately.
4402     // The end of the derived-to-base path for the base object must match the
4403     // derived-to-base path for the member pointer.
4404     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4405         LV.Designator.Entries.size()) {
4406       Info.FFDiag(RHS);
4407       return nullptr;
4408     }
4409     unsigned PathLengthToMember =
4410         LV.Designator.Entries.size() - MemPtr.Path.size();
4411     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4412       const CXXRecordDecl *LVDecl = getAsBaseClass(
4413           LV.Designator.Entries[PathLengthToMember + I]);
4414       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4415       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4416         Info.FFDiag(RHS);
4417         return nullptr;
4418       }
4419     }
4420 
4421     // Truncate the lvalue to the appropriate derived class.
4422     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4423                             PathLengthToMember))
4424       return nullptr;
4425   } else if (!MemPtr.Path.empty()) {
4426     // Extend the LValue path with the member pointer's path.
4427     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4428                                   MemPtr.Path.size() + IncludeMember);
4429 
4430     // Walk down to the appropriate base class.
4431     if (const PointerType *PT = LVType->getAs<PointerType>())
4432       LVType = PT->getPointeeType();
4433     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4434     assert(RD && "member pointer access on non-class-type expression");
4435     // The first class in the path is that of the lvalue.
4436     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4437       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4438       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4439         return nullptr;
4440       RD = Base;
4441     }
4442     // Finally cast to the class containing the member.
4443     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4444                                 MemPtr.getContainingRecord()))
4445       return nullptr;
4446   }
4447 
4448   // Add the member. Note that we cannot build bound member functions here.
4449   if (IncludeMember) {
4450     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4451       if (!HandleLValueMember(Info, RHS, LV, FD))
4452         return nullptr;
4453     } else if (const IndirectFieldDecl *IFD =
4454                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4455       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4456         return nullptr;
4457     } else {
4458       llvm_unreachable("can't construct reference to bound member function");
4459     }
4460   }
4461 
4462   return MemPtr.getDecl();
4463 }
4464 
4465 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4466                                                   const BinaryOperator *BO,
4467                                                   LValue &LV,
4468                                                   bool IncludeMember = true) {
4469   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4470 
4471   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4472     if (Info.noteFailure()) {
4473       MemberPtr MemPtr;
4474       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4475     }
4476     return nullptr;
4477   }
4478 
4479   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4480                                    BO->getRHS(), IncludeMember);
4481 }
4482 
4483 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4484 /// the provided lvalue, which currently refers to the base object.
4485 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4486                                     LValue &Result) {
4487   SubobjectDesignator &D = Result.Designator;
4488   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4489     return false;
4490 
4491   QualType TargetQT = E->getType();
4492   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4493     TargetQT = PT->getPointeeType();
4494 
4495   // Check this cast lands within the final derived-to-base subobject path.
4496   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4497     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4498       << D.MostDerivedType << TargetQT;
4499     return false;
4500   }
4501 
4502   // Check the type of the final cast. We don't need to check the path,
4503   // since a cast can only be formed if the path is unique.
4504   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4505   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4506   const CXXRecordDecl *FinalType;
4507   if (NewEntriesSize == D.MostDerivedPathLength)
4508     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4509   else
4510     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4511   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4512     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4513       << D.MostDerivedType << TargetQT;
4514     return false;
4515   }
4516 
4517   // Truncate the lvalue to the appropriate derived class.
4518   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4519 }
4520 
4521 /// Get the value to use for a default-initialized object of type T.
4522 /// Return false if it encounters something invalid.
4523 static bool getDefaultInitValue(QualType T, APValue &Result) {
4524   bool Success = true;
4525   if (auto *RD = T->getAsCXXRecordDecl()) {
4526     if (RD->isInvalidDecl()) {
4527       Result = APValue();
4528       return false;
4529     }
4530     if (RD->isUnion()) {
4531       Result = APValue((const FieldDecl *)nullptr);
4532       return true;
4533     }
4534     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4535                      std::distance(RD->field_begin(), RD->field_end()));
4536 
4537     unsigned Index = 0;
4538     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4539                                                   End = RD->bases_end();
4540          I != End; ++I, ++Index)
4541       Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4542 
4543     for (const auto *I : RD->fields()) {
4544       if (I->isUnnamedBitfield())
4545         continue;
4546       Success &= getDefaultInitValue(I->getType(),
4547                                      Result.getStructField(I->getFieldIndex()));
4548     }
4549     return Success;
4550   }
4551 
4552   if (auto *AT =
4553           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4554     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4555     if (Result.hasArrayFiller())
4556       Success &=
4557           getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4558 
4559     return Success;
4560   }
4561 
4562   Result = APValue::IndeterminateValue();
4563   return true;
4564 }
4565 
4566 namespace {
4567 enum EvalStmtResult {
4568   /// Evaluation failed.
4569   ESR_Failed,
4570   /// Hit a 'return' statement.
4571   ESR_Returned,
4572   /// Evaluation succeeded.
4573   ESR_Succeeded,
4574   /// Hit a 'continue' statement.
4575   ESR_Continue,
4576   /// Hit a 'break' statement.
4577   ESR_Break,
4578   /// Still scanning for 'case' or 'default' statement.
4579   ESR_CaseNotFound
4580 };
4581 }
4582 
4583 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4584   // We don't need to evaluate the initializer for a static local.
4585   if (!VD->hasLocalStorage())
4586     return true;
4587 
4588   LValue Result;
4589   APValue &Val =
4590       Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result);
4591 
4592   const Expr *InitE = VD->getInit();
4593   if (!InitE)
4594     return getDefaultInitValue(VD->getType(), Val);
4595 
4596   if (InitE->isValueDependent())
4597     return false;
4598 
4599   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4600     // Wipe out any partially-computed value, to allow tracking that this
4601     // evaluation failed.
4602     Val = APValue();
4603     return false;
4604   }
4605 
4606   return true;
4607 }
4608 
4609 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4610   bool OK = true;
4611 
4612   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4613     OK &= EvaluateVarDecl(Info, VD);
4614 
4615   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4616     for (auto *BD : DD->bindings())
4617       if (auto *VD = BD->getHoldingVar())
4618         OK &= EvaluateDecl(Info, VD);
4619 
4620   return OK;
4621 }
4622 
4623 
4624 /// Evaluate a condition (either a variable declaration or an expression).
4625 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4626                          const Expr *Cond, bool &Result) {
4627   FullExpressionRAII Scope(Info);
4628   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4629     return false;
4630   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4631     return false;
4632   return Scope.destroy();
4633 }
4634 
4635 namespace {
4636 /// A location where the result (returned value) of evaluating a
4637 /// statement should be stored.
4638 struct StmtResult {
4639   /// The APValue that should be filled in with the returned value.
4640   APValue &Value;
4641   /// The location containing the result, if any (used to support RVO).
4642   const LValue *Slot;
4643 };
4644 
4645 struct TempVersionRAII {
4646   CallStackFrame &Frame;
4647 
4648   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4649     Frame.pushTempVersion();
4650   }
4651 
4652   ~TempVersionRAII() {
4653     Frame.popTempVersion();
4654   }
4655 };
4656 
4657 }
4658 
4659 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4660                                    const Stmt *S,
4661                                    const SwitchCase *SC = nullptr);
4662 
4663 /// Evaluate the body of a loop, and translate the result as appropriate.
4664 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4665                                        const Stmt *Body,
4666                                        const SwitchCase *Case = nullptr) {
4667   BlockScopeRAII Scope(Info);
4668 
4669   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4670   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4671     ESR = ESR_Failed;
4672 
4673   switch (ESR) {
4674   case ESR_Break:
4675     return ESR_Succeeded;
4676   case ESR_Succeeded:
4677   case ESR_Continue:
4678     return ESR_Continue;
4679   case ESR_Failed:
4680   case ESR_Returned:
4681   case ESR_CaseNotFound:
4682     return ESR;
4683   }
4684   llvm_unreachable("Invalid EvalStmtResult!");
4685 }
4686 
4687 /// Evaluate a switch statement.
4688 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4689                                      const SwitchStmt *SS) {
4690   BlockScopeRAII Scope(Info);
4691 
4692   // Evaluate the switch condition.
4693   APSInt Value;
4694   {
4695     if (const Stmt *Init = SS->getInit()) {
4696       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4697       if (ESR != ESR_Succeeded) {
4698         if (ESR != ESR_Failed && !Scope.destroy())
4699           ESR = ESR_Failed;
4700         return ESR;
4701       }
4702     }
4703 
4704     FullExpressionRAII CondScope(Info);
4705     if (SS->getConditionVariable() &&
4706         !EvaluateDecl(Info, SS->getConditionVariable()))
4707       return ESR_Failed;
4708     if (!EvaluateInteger(SS->getCond(), Value, Info))
4709       return ESR_Failed;
4710     if (!CondScope.destroy())
4711       return ESR_Failed;
4712   }
4713 
4714   // Find the switch case corresponding to the value of the condition.
4715   // FIXME: Cache this lookup.
4716   const SwitchCase *Found = nullptr;
4717   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4718        SC = SC->getNextSwitchCase()) {
4719     if (isa<DefaultStmt>(SC)) {
4720       Found = SC;
4721       continue;
4722     }
4723 
4724     const CaseStmt *CS = cast<CaseStmt>(SC);
4725     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4726     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4727                               : LHS;
4728     if (LHS <= Value && Value <= RHS) {
4729       Found = SC;
4730       break;
4731     }
4732   }
4733 
4734   if (!Found)
4735     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4736 
4737   // Search the switch body for the switch case and evaluate it from there.
4738   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4739   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4740     return ESR_Failed;
4741 
4742   switch (ESR) {
4743   case ESR_Break:
4744     return ESR_Succeeded;
4745   case ESR_Succeeded:
4746   case ESR_Continue:
4747   case ESR_Failed:
4748   case ESR_Returned:
4749     return ESR;
4750   case ESR_CaseNotFound:
4751     // This can only happen if the switch case is nested within a statement
4752     // expression. We have no intention of supporting that.
4753     Info.FFDiag(Found->getBeginLoc(),
4754                 diag::note_constexpr_stmt_expr_unsupported);
4755     return ESR_Failed;
4756   }
4757   llvm_unreachable("Invalid EvalStmtResult!");
4758 }
4759 
4760 // Evaluate a statement.
4761 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4762                                    const Stmt *S, const SwitchCase *Case) {
4763   if (!Info.nextStep(S))
4764     return ESR_Failed;
4765 
4766   // If we're hunting down a 'case' or 'default' label, recurse through
4767   // substatements until we hit the label.
4768   if (Case) {
4769     switch (S->getStmtClass()) {
4770     case Stmt::CompoundStmtClass:
4771       // FIXME: Precompute which substatement of a compound statement we
4772       // would jump to, and go straight there rather than performing a
4773       // linear scan each time.
4774     case Stmt::LabelStmtClass:
4775     case Stmt::AttributedStmtClass:
4776     case Stmt::DoStmtClass:
4777       break;
4778 
4779     case Stmt::CaseStmtClass:
4780     case Stmt::DefaultStmtClass:
4781       if (Case == S)
4782         Case = nullptr;
4783       break;
4784 
4785     case Stmt::IfStmtClass: {
4786       // FIXME: Precompute which side of an 'if' we would jump to, and go
4787       // straight there rather than scanning both sides.
4788       const IfStmt *IS = cast<IfStmt>(S);
4789 
4790       // Wrap the evaluation in a block scope, in case it's a DeclStmt
4791       // preceded by our switch label.
4792       BlockScopeRAII Scope(Info);
4793 
4794       // Step into the init statement in case it brings an (uninitialized)
4795       // variable into scope.
4796       if (const Stmt *Init = IS->getInit()) {
4797         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4798         if (ESR != ESR_CaseNotFound) {
4799           assert(ESR != ESR_Succeeded);
4800           return ESR;
4801         }
4802       }
4803 
4804       // Condition variable must be initialized if it exists.
4805       // FIXME: We can skip evaluating the body if there's a condition
4806       // variable, as there can't be any case labels within it.
4807       // (The same is true for 'for' statements.)
4808 
4809       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4810       if (ESR == ESR_Failed)
4811         return ESR;
4812       if (ESR != ESR_CaseNotFound)
4813         return Scope.destroy() ? ESR : ESR_Failed;
4814       if (!IS->getElse())
4815         return ESR_CaseNotFound;
4816 
4817       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
4818       if (ESR == ESR_Failed)
4819         return ESR;
4820       if (ESR != ESR_CaseNotFound)
4821         return Scope.destroy() ? ESR : ESR_Failed;
4822       return ESR_CaseNotFound;
4823     }
4824 
4825     case Stmt::WhileStmtClass: {
4826       EvalStmtResult ESR =
4827           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4828       if (ESR != ESR_Continue)
4829         return ESR;
4830       break;
4831     }
4832 
4833     case Stmt::ForStmtClass: {
4834       const ForStmt *FS = cast<ForStmt>(S);
4835       BlockScopeRAII Scope(Info);
4836 
4837       // Step into the init statement in case it brings an (uninitialized)
4838       // variable into scope.
4839       if (const Stmt *Init = FS->getInit()) {
4840         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4841         if (ESR != ESR_CaseNotFound) {
4842           assert(ESR != ESR_Succeeded);
4843           return ESR;
4844         }
4845       }
4846 
4847       EvalStmtResult ESR =
4848           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4849       if (ESR != ESR_Continue)
4850         return ESR;
4851       if (FS->getInc()) {
4852         FullExpressionRAII IncScope(Info);
4853         if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
4854           return ESR_Failed;
4855       }
4856       break;
4857     }
4858 
4859     case Stmt::DeclStmtClass: {
4860       // Start the lifetime of any uninitialized variables we encounter. They
4861       // might be used by the selected branch of the switch.
4862       const DeclStmt *DS = cast<DeclStmt>(S);
4863       for (const auto *D : DS->decls()) {
4864         if (const auto *VD = dyn_cast<VarDecl>(D)) {
4865           if (VD->hasLocalStorage() && !VD->getInit())
4866             if (!EvaluateVarDecl(Info, VD))
4867               return ESR_Failed;
4868           // FIXME: If the variable has initialization that can't be jumped
4869           // over, bail out of any immediately-surrounding compound-statement
4870           // too. There can't be any case labels here.
4871         }
4872       }
4873       return ESR_CaseNotFound;
4874     }
4875 
4876     default:
4877       return ESR_CaseNotFound;
4878     }
4879   }
4880 
4881   switch (S->getStmtClass()) {
4882   default:
4883     if (const Expr *E = dyn_cast<Expr>(S)) {
4884       // Don't bother evaluating beyond an expression-statement which couldn't
4885       // be evaluated.
4886       // FIXME: Do we need the FullExpressionRAII object here?
4887       // VisitExprWithCleanups should create one when necessary.
4888       FullExpressionRAII Scope(Info);
4889       if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
4890         return ESR_Failed;
4891       return ESR_Succeeded;
4892     }
4893 
4894     Info.FFDiag(S->getBeginLoc());
4895     return ESR_Failed;
4896 
4897   case Stmt::NullStmtClass:
4898     return ESR_Succeeded;
4899 
4900   case Stmt::DeclStmtClass: {
4901     const DeclStmt *DS = cast<DeclStmt>(S);
4902     for (const auto *D : DS->decls()) {
4903       // Each declaration initialization is its own full-expression.
4904       FullExpressionRAII Scope(Info);
4905       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
4906         return ESR_Failed;
4907       if (!Scope.destroy())
4908         return ESR_Failed;
4909     }
4910     return ESR_Succeeded;
4911   }
4912 
4913   case Stmt::ReturnStmtClass: {
4914     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
4915     FullExpressionRAII Scope(Info);
4916     if (RetExpr &&
4917         !(Result.Slot
4918               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4919               : Evaluate(Result.Value, Info, RetExpr)))
4920       return ESR_Failed;
4921     return Scope.destroy() ? ESR_Returned : ESR_Failed;
4922   }
4923 
4924   case Stmt::CompoundStmtClass: {
4925     BlockScopeRAII Scope(Info);
4926 
4927     const CompoundStmt *CS = cast<CompoundStmt>(S);
4928     for (const auto *BI : CS->body()) {
4929       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
4930       if (ESR == ESR_Succeeded)
4931         Case = nullptr;
4932       else if (ESR != ESR_CaseNotFound) {
4933         if (ESR != ESR_Failed && !Scope.destroy())
4934           return ESR_Failed;
4935         return ESR;
4936       }
4937     }
4938     if (Case)
4939       return ESR_CaseNotFound;
4940     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4941   }
4942 
4943   case Stmt::IfStmtClass: {
4944     const IfStmt *IS = cast<IfStmt>(S);
4945 
4946     // Evaluate the condition, as either a var decl or as an expression.
4947     BlockScopeRAII Scope(Info);
4948     if (const Stmt *Init = IS->getInit()) {
4949       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4950       if (ESR != ESR_Succeeded) {
4951         if (ESR != ESR_Failed && !Scope.destroy())
4952           return ESR_Failed;
4953         return ESR;
4954       }
4955     }
4956     bool Cond;
4957     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4958       return ESR_Failed;
4959 
4960     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4961       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4962       if (ESR != ESR_Succeeded) {
4963         if (ESR != ESR_Failed && !Scope.destroy())
4964           return ESR_Failed;
4965         return ESR;
4966       }
4967     }
4968     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4969   }
4970 
4971   case Stmt::WhileStmtClass: {
4972     const WhileStmt *WS = cast<WhileStmt>(S);
4973     while (true) {
4974       BlockScopeRAII Scope(Info);
4975       bool Continue;
4976       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4977                         Continue))
4978         return ESR_Failed;
4979       if (!Continue)
4980         break;
4981 
4982       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4983       if (ESR != ESR_Continue) {
4984         if (ESR != ESR_Failed && !Scope.destroy())
4985           return ESR_Failed;
4986         return ESR;
4987       }
4988       if (!Scope.destroy())
4989         return ESR_Failed;
4990     }
4991     return ESR_Succeeded;
4992   }
4993 
4994   case Stmt::DoStmtClass: {
4995     const DoStmt *DS = cast<DoStmt>(S);
4996     bool Continue;
4997     do {
4998       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4999       if (ESR != ESR_Continue)
5000         return ESR;
5001       Case = nullptr;
5002 
5003       FullExpressionRAII CondScope(Info);
5004       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5005           !CondScope.destroy())
5006         return ESR_Failed;
5007     } while (Continue);
5008     return ESR_Succeeded;
5009   }
5010 
5011   case Stmt::ForStmtClass: {
5012     const ForStmt *FS = cast<ForStmt>(S);
5013     BlockScopeRAII ForScope(Info);
5014     if (FS->getInit()) {
5015       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5016       if (ESR != ESR_Succeeded) {
5017         if (ESR != ESR_Failed && !ForScope.destroy())
5018           return ESR_Failed;
5019         return ESR;
5020       }
5021     }
5022     while (true) {
5023       BlockScopeRAII IterScope(Info);
5024       bool Continue = true;
5025       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5026                                          FS->getCond(), Continue))
5027         return ESR_Failed;
5028       if (!Continue)
5029         break;
5030 
5031       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5032       if (ESR != ESR_Continue) {
5033         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5034           return ESR_Failed;
5035         return ESR;
5036       }
5037 
5038       if (FS->getInc()) {
5039         FullExpressionRAII IncScope(Info);
5040         if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
5041           return ESR_Failed;
5042       }
5043 
5044       if (!IterScope.destroy())
5045         return ESR_Failed;
5046     }
5047     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5048   }
5049 
5050   case Stmt::CXXForRangeStmtClass: {
5051     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5052     BlockScopeRAII Scope(Info);
5053 
5054     // Evaluate the init-statement if present.
5055     if (FS->getInit()) {
5056       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5057       if (ESR != ESR_Succeeded) {
5058         if (ESR != ESR_Failed && !Scope.destroy())
5059           return ESR_Failed;
5060         return ESR;
5061       }
5062     }
5063 
5064     // Initialize the __range variable.
5065     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5066     if (ESR != ESR_Succeeded) {
5067       if (ESR != ESR_Failed && !Scope.destroy())
5068         return ESR_Failed;
5069       return ESR;
5070     }
5071 
5072     // Create the __begin and __end iterators.
5073     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5074     if (ESR != ESR_Succeeded) {
5075       if (ESR != ESR_Failed && !Scope.destroy())
5076         return ESR_Failed;
5077       return ESR;
5078     }
5079     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5080     if (ESR != ESR_Succeeded) {
5081       if (ESR != ESR_Failed && !Scope.destroy())
5082         return ESR_Failed;
5083       return ESR;
5084     }
5085 
5086     while (true) {
5087       // Condition: __begin != __end.
5088       {
5089         bool Continue = true;
5090         FullExpressionRAII CondExpr(Info);
5091         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5092           return ESR_Failed;
5093         if (!Continue)
5094           break;
5095       }
5096 
5097       // User's variable declaration, initialized by *__begin.
5098       BlockScopeRAII InnerScope(Info);
5099       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5100       if (ESR != ESR_Succeeded) {
5101         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5102           return ESR_Failed;
5103         return ESR;
5104       }
5105 
5106       // Loop body.
5107       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5108       if (ESR != ESR_Continue) {
5109         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5110           return ESR_Failed;
5111         return ESR;
5112       }
5113 
5114       // Increment: ++__begin
5115       if (!EvaluateIgnoredValue(Info, FS->getInc()))
5116         return ESR_Failed;
5117 
5118       if (!InnerScope.destroy())
5119         return ESR_Failed;
5120     }
5121 
5122     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5123   }
5124 
5125   case Stmt::SwitchStmtClass:
5126     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5127 
5128   case Stmt::ContinueStmtClass:
5129     return ESR_Continue;
5130 
5131   case Stmt::BreakStmtClass:
5132     return ESR_Break;
5133 
5134   case Stmt::LabelStmtClass:
5135     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5136 
5137   case Stmt::AttributedStmtClass:
5138     // As a general principle, C++11 attributes can be ignored without
5139     // any semantic impact.
5140     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5141                         Case);
5142 
5143   case Stmt::CaseStmtClass:
5144   case Stmt::DefaultStmtClass:
5145     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5146   case Stmt::CXXTryStmtClass:
5147     // Evaluate try blocks by evaluating all sub statements.
5148     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5149   }
5150 }
5151 
5152 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5153 /// default constructor. If so, we'll fold it whether or not it's marked as
5154 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5155 /// so we need special handling.
5156 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5157                                            const CXXConstructorDecl *CD,
5158                                            bool IsValueInitialization) {
5159   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5160     return false;
5161 
5162   // Value-initialization does not call a trivial default constructor, so such a
5163   // call is a core constant expression whether or not the constructor is
5164   // constexpr.
5165   if (!CD->isConstexpr() && !IsValueInitialization) {
5166     if (Info.getLangOpts().CPlusPlus11) {
5167       // FIXME: If DiagDecl is an implicitly-declared special member function,
5168       // we should be much more explicit about why it's not constexpr.
5169       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5170         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5171       Info.Note(CD->getLocation(), diag::note_declared_at);
5172     } else {
5173       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5174     }
5175   }
5176   return true;
5177 }
5178 
5179 /// CheckConstexprFunction - Check that a function can be called in a constant
5180 /// expression.
5181 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5182                                    const FunctionDecl *Declaration,
5183                                    const FunctionDecl *Definition,
5184                                    const Stmt *Body) {
5185   // Potential constant expressions can contain calls to declared, but not yet
5186   // defined, constexpr functions.
5187   if (Info.checkingPotentialConstantExpression() && !Definition &&
5188       Declaration->isConstexpr())
5189     return false;
5190 
5191   // Bail out if the function declaration itself is invalid.  We will
5192   // have produced a relevant diagnostic while parsing it, so just
5193   // note the problematic sub-expression.
5194   if (Declaration->isInvalidDecl()) {
5195     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5196     return false;
5197   }
5198 
5199   // DR1872: An instantiated virtual constexpr function can't be called in a
5200   // constant expression (prior to C++20). We can still constant-fold such a
5201   // call.
5202   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5203       cast<CXXMethodDecl>(Declaration)->isVirtual())
5204     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5205 
5206   if (Definition && Definition->isInvalidDecl()) {
5207     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5208     return false;
5209   }
5210 
5211   if (const auto *CtorDecl = dyn_cast_or_null<CXXConstructorDecl>(Definition)) {
5212     for (const auto *InitExpr : CtorDecl->inits()) {
5213       if (InitExpr->getInit() && InitExpr->getInit()->containsErrors())
5214         return false;
5215     }
5216   }
5217 
5218   // Can we evaluate this function call?
5219   if (Definition && Definition->isConstexpr() && Body)
5220     return true;
5221 
5222   if (Info.getLangOpts().CPlusPlus11) {
5223     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5224 
5225     // If this function is not constexpr because it is an inherited
5226     // non-constexpr constructor, diagnose that directly.
5227     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5228     if (CD && CD->isInheritingConstructor()) {
5229       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5230       if (!Inherited->isConstexpr())
5231         DiagDecl = CD = Inherited;
5232     }
5233 
5234     // FIXME: If DiagDecl is an implicitly-declared special member function
5235     // or an inheriting constructor, we should be much more explicit about why
5236     // it's not constexpr.
5237     if (CD && CD->isInheritingConstructor())
5238       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5239         << CD->getInheritedConstructor().getConstructor()->getParent();
5240     else
5241       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5242         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5243     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5244   } else {
5245     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5246   }
5247   return false;
5248 }
5249 
5250 namespace {
5251 struct CheckDynamicTypeHandler {
5252   AccessKinds AccessKind;
5253   typedef bool result_type;
5254   bool failed() { return false; }
5255   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5256   bool found(APSInt &Value, QualType SubobjType) { return true; }
5257   bool found(APFloat &Value, QualType SubobjType) { return true; }
5258 };
5259 } // end anonymous namespace
5260 
5261 /// Check that we can access the notional vptr of an object / determine its
5262 /// dynamic type.
5263 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5264                              AccessKinds AK, bool Polymorphic) {
5265   if (This.Designator.Invalid)
5266     return false;
5267 
5268   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5269 
5270   if (!Obj)
5271     return false;
5272 
5273   if (!Obj.Value) {
5274     // The object is not usable in constant expressions, so we can't inspect
5275     // its value to see if it's in-lifetime or what the active union members
5276     // are. We can still check for a one-past-the-end lvalue.
5277     if (This.Designator.isOnePastTheEnd() ||
5278         This.Designator.isMostDerivedAnUnsizedArray()) {
5279       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5280                          ? diag::note_constexpr_access_past_end
5281                          : diag::note_constexpr_access_unsized_array)
5282           << AK;
5283       return false;
5284     } else if (Polymorphic) {
5285       // Conservatively refuse to perform a polymorphic operation if we would
5286       // not be able to read a notional 'vptr' value.
5287       APValue Val;
5288       This.moveInto(Val);
5289       QualType StarThisType =
5290           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5291       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5292           << AK << Val.getAsString(Info.Ctx, StarThisType);
5293       return false;
5294     }
5295     return true;
5296   }
5297 
5298   CheckDynamicTypeHandler Handler{AK};
5299   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5300 }
5301 
5302 /// Check that the pointee of the 'this' pointer in a member function call is
5303 /// either within its lifetime or in its period of construction or destruction.
5304 static bool
5305 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5306                                      const LValue &This,
5307                                      const CXXMethodDecl *NamedMember) {
5308   return checkDynamicType(
5309       Info, E, This,
5310       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5311 }
5312 
5313 struct DynamicType {
5314   /// The dynamic class type of the object.
5315   const CXXRecordDecl *Type;
5316   /// The corresponding path length in the lvalue.
5317   unsigned PathLength;
5318 };
5319 
5320 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5321                                              unsigned PathLength) {
5322   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5323       Designator.Entries.size() && "invalid path length");
5324   return (PathLength == Designator.MostDerivedPathLength)
5325              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5326              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5327 }
5328 
5329 /// Determine the dynamic type of an object.
5330 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5331                                                 LValue &This, AccessKinds AK) {
5332   // If we don't have an lvalue denoting an object of class type, there is no
5333   // meaningful dynamic type. (We consider objects of non-class type to have no
5334   // dynamic type.)
5335   if (!checkDynamicType(Info, E, This, AK, true))
5336     return None;
5337 
5338   // Refuse to compute a dynamic type in the presence of virtual bases. This
5339   // shouldn't happen other than in constant-folding situations, since literal
5340   // types can't have virtual bases.
5341   //
5342   // Note that consumers of DynamicType assume that the type has no virtual
5343   // bases, and will need modifications if this restriction is relaxed.
5344   const CXXRecordDecl *Class =
5345       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5346   if (!Class || Class->getNumVBases()) {
5347     Info.FFDiag(E);
5348     return None;
5349   }
5350 
5351   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5352   // binary search here instead. But the overwhelmingly common case is that
5353   // we're not in the middle of a constructor, so it probably doesn't matter
5354   // in practice.
5355   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5356   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5357        PathLength <= Path.size(); ++PathLength) {
5358     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5359                                       Path.slice(0, PathLength))) {
5360     case ConstructionPhase::Bases:
5361     case ConstructionPhase::DestroyingBases:
5362       // We're constructing or destroying a base class. This is not the dynamic
5363       // type.
5364       break;
5365 
5366     case ConstructionPhase::None:
5367     case ConstructionPhase::AfterBases:
5368     case ConstructionPhase::AfterFields:
5369     case ConstructionPhase::Destroying:
5370       // We've finished constructing the base classes and not yet started
5371       // destroying them again, so this is the dynamic type.
5372       return DynamicType{getBaseClassType(This.Designator, PathLength),
5373                          PathLength};
5374     }
5375   }
5376 
5377   // CWG issue 1517: we're constructing a base class of the object described by
5378   // 'This', so that object has not yet begun its period of construction and
5379   // any polymorphic operation on it results in undefined behavior.
5380   Info.FFDiag(E);
5381   return None;
5382 }
5383 
5384 /// Perform virtual dispatch.
5385 static const CXXMethodDecl *HandleVirtualDispatch(
5386     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5387     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5388   Optional<DynamicType> DynType = ComputeDynamicType(
5389       Info, E, This,
5390       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5391   if (!DynType)
5392     return nullptr;
5393 
5394   // Find the final overrider. It must be declared in one of the classes on the
5395   // path from the dynamic type to the static type.
5396   // FIXME: If we ever allow literal types to have virtual base classes, that
5397   // won't be true.
5398   const CXXMethodDecl *Callee = Found;
5399   unsigned PathLength = DynType->PathLength;
5400   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5401     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5402     const CXXMethodDecl *Overrider =
5403         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5404     if (Overrider) {
5405       Callee = Overrider;
5406       break;
5407     }
5408   }
5409 
5410   // C++2a [class.abstract]p6:
5411   //   the effect of making a virtual call to a pure virtual function [...] is
5412   //   undefined
5413   if (Callee->isPure()) {
5414     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5415     Info.Note(Callee->getLocation(), diag::note_declared_at);
5416     return nullptr;
5417   }
5418 
5419   // If necessary, walk the rest of the path to determine the sequence of
5420   // covariant adjustment steps to apply.
5421   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5422                                        Found->getReturnType())) {
5423     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5424     for (unsigned CovariantPathLength = PathLength + 1;
5425          CovariantPathLength != This.Designator.Entries.size();
5426          ++CovariantPathLength) {
5427       const CXXRecordDecl *NextClass =
5428           getBaseClassType(This.Designator, CovariantPathLength);
5429       const CXXMethodDecl *Next =
5430           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5431       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5432                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5433         CovariantAdjustmentPath.push_back(Next->getReturnType());
5434     }
5435     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5436                                          CovariantAdjustmentPath.back()))
5437       CovariantAdjustmentPath.push_back(Found->getReturnType());
5438   }
5439 
5440   // Perform 'this' adjustment.
5441   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5442     return nullptr;
5443 
5444   return Callee;
5445 }
5446 
5447 /// Perform the adjustment from a value returned by a virtual function to
5448 /// a value of the statically expected type, which may be a pointer or
5449 /// reference to a base class of the returned type.
5450 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5451                                             APValue &Result,
5452                                             ArrayRef<QualType> Path) {
5453   assert(Result.isLValue() &&
5454          "unexpected kind of APValue for covariant return");
5455   if (Result.isNullPointer())
5456     return true;
5457 
5458   LValue LVal;
5459   LVal.setFrom(Info.Ctx, Result);
5460 
5461   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5462   for (unsigned I = 1; I != Path.size(); ++I) {
5463     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5464     assert(OldClass && NewClass && "unexpected kind of covariant return");
5465     if (OldClass != NewClass &&
5466         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5467       return false;
5468     OldClass = NewClass;
5469   }
5470 
5471   LVal.moveInto(Result);
5472   return true;
5473 }
5474 
5475 /// Determine whether \p Base, which is known to be a direct base class of
5476 /// \p Derived, is a public base class.
5477 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5478                               const CXXRecordDecl *Base) {
5479   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5480     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5481     if (BaseClass && declaresSameEntity(BaseClass, Base))
5482       return BaseSpec.getAccessSpecifier() == AS_public;
5483   }
5484   llvm_unreachable("Base is not a direct base of Derived");
5485 }
5486 
5487 /// Apply the given dynamic cast operation on the provided lvalue.
5488 ///
5489 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5490 /// to find a suitable target subobject.
5491 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5492                               LValue &Ptr) {
5493   // We can't do anything with a non-symbolic pointer value.
5494   SubobjectDesignator &D = Ptr.Designator;
5495   if (D.Invalid)
5496     return false;
5497 
5498   // C++ [expr.dynamic.cast]p6:
5499   //   If v is a null pointer value, the result is a null pointer value.
5500   if (Ptr.isNullPointer() && !E->isGLValue())
5501     return true;
5502 
5503   // For all the other cases, we need the pointer to point to an object within
5504   // its lifetime / period of construction / destruction, and we need to know
5505   // its dynamic type.
5506   Optional<DynamicType> DynType =
5507       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5508   if (!DynType)
5509     return false;
5510 
5511   // C++ [expr.dynamic.cast]p7:
5512   //   If T is "pointer to cv void", then the result is a pointer to the most
5513   //   derived object
5514   if (E->getType()->isVoidPointerType())
5515     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5516 
5517   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5518   assert(C && "dynamic_cast target is not void pointer nor class");
5519   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5520 
5521   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5522     // C++ [expr.dynamic.cast]p9:
5523     if (!E->isGLValue()) {
5524       //   The value of a failed cast to pointer type is the null pointer value
5525       //   of the required result type.
5526       Ptr.setNull(Info.Ctx, E->getType());
5527       return true;
5528     }
5529 
5530     //   A failed cast to reference type throws [...] std::bad_cast.
5531     unsigned DiagKind;
5532     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5533                    DynType->Type->isDerivedFrom(C)))
5534       DiagKind = 0;
5535     else if (!Paths || Paths->begin() == Paths->end())
5536       DiagKind = 1;
5537     else if (Paths->isAmbiguous(CQT))
5538       DiagKind = 2;
5539     else {
5540       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5541       DiagKind = 3;
5542     }
5543     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5544         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5545         << Info.Ctx.getRecordType(DynType->Type)
5546         << E->getType().getUnqualifiedType();
5547     return false;
5548   };
5549 
5550   // Runtime check, phase 1:
5551   //   Walk from the base subobject towards the derived object looking for the
5552   //   target type.
5553   for (int PathLength = Ptr.Designator.Entries.size();
5554        PathLength >= (int)DynType->PathLength; --PathLength) {
5555     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5556     if (declaresSameEntity(Class, C))
5557       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5558     // We can only walk across public inheritance edges.
5559     if (PathLength > (int)DynType->PathLength &&
5560         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5561                            Class))
5562       return RuntimeCheckFailed(nullptr);
5563   }
5564 
5565   // Runtime check, phase 2:
5566   //   Search the dynamic type for an unambiguous public base of type C.
5567   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5568                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5569   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5570       Paths.front().Access == AS_public) {
5571     // Downcast to the dynamic type...
5572     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5573       return false;
5574     // ... then upcast to the chosen base class subobject.
5575     for (CXXBasePathElement &Elem : Paths.front())
5576       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5577         return false;
5578     return true;
5579   }
5580 
5581   // Otherwise, the runtime check fails.
5582   return RuntimeCheckFailed(&Paths);
5583 }
5584 
5585 namespace {
5586 struct StartLifetimeOfUnionMemberHandler {
5587   EvalInfo &Info;
5588   const Expr *LHSExpr;
5589   const FieldDecl *Field;
5590   bool DuringInit;
5591   bool Failed = false;
5592   static const AccessKinds AccessKind = AK_Assign;
5593 
5594   typedef bool result_type;
5595   bool failed() { return Failed; }
5596   bool found(APValue &Subobj, QualType SubobjType) {
5597     // We are supposed to perform no initialization but begin the lifetime of
5598     // the object. We interpret that as meaning to do what default
5599     // initialization of the object would do if all constructors involved were
5600     // trivial:
5601     //  * All base, non-variant member, and array element subobjects' lifetimes
5602     //    begin
5603     //  * No variant members' lifetimes begin
5604     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5605     assert(SubobjType->isUnionType());
5606     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5607       // This union member is already active. If it's also in-lifetime, there's
5608       // nothing to do.
5609       if (Subobj.getUnionValue().hasValue())
5610         return true;
5611     } else if (DuringInit) {
5612       // We're currently in the process of initializing a different union
5613       // member.  If we carried on, that initialization would attempt to
5614       // store to an inactive union member, resulting in undefined behavior.
5615       Info.FFDiag(LHSExpr,
5616                   diag::note_constexpr_union_member_change_during_init);
5617       return false;
5618     }
5619     APValue Result;
5620     Failed = !getDefaultInitValue(Field->getType(), Result);
5621     Subobj.setUnion(Field, Result);
5622     return true;
5623   }
5624   bool found(APSInt &Value, QualType SubobjType) {
5625     llvm_unreachable("wrong value kind for union object");
5626   }
5627   bool found(APFloat &Value, QualType SubobjType) {
5628     llvm_unreachable("wrong value kind for union object");
5629   }
5630 };
5631 } // end anonymous namespace
5632 
5633 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5634 
5635 /// Handle a builtin simple-assignment or a call to a trivial assignment
5636 /// operator whose left-hand side might involve a union member access. If it
5637 /// does, implicitly start the lifetime of any accessed union elements per
5638 /// C++20 [class.union]5.
5639 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5640                                           const LValue &LHS) {
5641   if (LHS.InvalidBase || LHS.Designator.Invalid)
5642     return false;
5643 
5644   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5645   // C++ [class.union]p5:
5646   //   define the set S(E) of subexpressions of E as follows:
5647   unsigned PathLength = LHS.Designator.Entries.size();
5648   for (const Expr *E = LHSExpr; E != nullptr;) {
5649     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5650     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5651       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5652       // Note that we can't implicitly start the lifetime of a reference,
5653       // so we don't need to proceed any further if we reach one.
5654       if (!FD || FD->getType()->isReferenceType())
5655         break;
5656 
5657       //    ... and also contains A.B if B names a union member ...
5658       if (FD->getParent()->isUnion()) {
5659         //    ... of a non-class, non-array type, or of a class type with a
5660         //    trivial default constructor that is not deleted, or an array of
5661         //    such types.
5662         auto *RD =
5663             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5664         if (!RD || RD->hasTrivialDefaultConstructor())
5665           UnionPathLengths.push_back({PathLength - 1, FD});
5666       }
5667 
5668       E = ME->getBase();
5669       --PathLength;
5670       assert(declaresSameEntity(FD,
5671                                 LHS.Designator.Entries[PathLength]
5672                                     .getAsBaseOrMember().getPointer()));
5673 
5674       //   -- If E is of the form A[B] and is interpreted as a built-in array
5675       //      subscripting operator, S(E) is [S(the array operand, if any)].
5676     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5677       // Step over an ArrayToPointerDecay implicit cast.
5678       auto *Base = ASE->getBase()->IgnoreImplicit();
5679       if (!Base->getType()->isArrayType())
5680         break;
5681 
5682       E = Base;
5683       --PathLength;
5684 
5685     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5686       // Step over a derived-to-base conversion.
5687       E = ICE->getSubExpr();
5688       if (ICE->getCastKind() == CK_NoOp)
5689         continue;
5690       if (ICE->getCastKind() != CK_DerivedToBase &&
5691           ICE->getCastKind() != CK_UncheckedDerivedToBase)
5692         break;
5693       // Walk path backwards as we walk up from the base to the derived class.
5694       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5695         --PathLength;
5696         (void)Elt;
5697         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5698                                   LHS.Designator.Entries[PathLength]
5699                                       .getAsBaseOrMember().getPointer()));
5700       }
5701 
5702     //   -- Otherwise, S(E) is empty.
5703     } else {
5704       break;
5705     }
5706   }
5707 
5708   // Common case: no unions' lifetimes are started.
5709   if (UnionPathLengths.empty())
5710     return true;
5711 
5712   //   if modification of X [would access an inactive union member], an object
5713   //   of the type of X is implicitly created
5714   CompleteObject Obj =
5715       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5716   if (!Obj)
5717     return false;
5718   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5719            llvm::reverse(UnionPathLengths)) {
5720     // Form a designator for the union object.
5721     SubobjectDesignator D = LHS.Designator;
5722     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5723 
5724     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
5725                       ConstructionPhase::AfterBases;
5726     StartLifetimeOfUnionMemberHandler StartLifetime{
5727         Info, LHSExpr, LengthAndField.second, DuringInit};
5728     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5729       return false;
5730   }
5731 
5732   return true;
5733 }
5734 
5735 namespace {
5736 typedef SmallVector<APValue, 8> ArgVector;
5737 }
5738 
5739 /// EvaluateArgs - Evaluate the arguments to a function call.
5740 static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
5741                          EvalInfo &Info, const FunctionDecl *Callee) {
5742   bool Success = true;
5743   llvm::SmallBitVector ForbiddenNullArgs;
5744   if (Callee->hasAttr<NonNullAttr>()) {
5745     ForbiddenNullArgs.resize(Args.size());
5746     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5747       if (!Attr->args_size()) {
5748         ForbiddenNullArgs.set();
5749         break;
5750       } else
5751         for (auto Idx : Attr->args()) {
5752           unsigned ASTIdx = Idx.getASTIndex();
5753           if (ASTIdx >= Args.size())
5754             continue;
5755           ForbiddenNullArgs[ASTIdx] = 1;
5756         }
5757     }
5758   }
5759   // FIXME: This is the wrong evaluation order for an assignment operator
5760   // called via operator syntax.
5761   for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
5762     if (!Evaluate(ArgValues[Idx], Info, Args[Idx])) {
5763       // If we're checking for a potential constant expression, evaluate all
5764       // initializers even if some of them fail.
5765       if (!Info.noteFailure())
5766         return false;
5767       Success = false;
5768     } else if (!ForbiddenNullArgs.empty() &&
5769                ForbiddenNullArgs[Idx] &&
5770                ArgValues[Idx].isLValue() &&
5771                ArgValues[Idx].isNullPointer()) {
5772       Info.CCEDiag(Args[Idx], diag::note_non_null_attribute_failed);
5773       if (!Info.noteFailure())
5774         return false;
5775       Success = false;
5776     }
5777   }
5778   return Success;
5779 }
5780 
5781 /// Evaluate a function call.
5782 static bool HandleFunctionCall(SourceLocation CallLoc,
5783                                const FunctionDecl *Callee, const LValue *This,
5784                                ArrayRef<const Expr*> Args, const Stmt *Body,
5785                                EvalInfo &Info, APValue &Result,
5786                                const LValue *ResultSlot) {
5787   ArgVector ArgValues(Args.size());
5788   if (!EvaluateArgs(Args, ArgValues, Info, Callee))
5789     return false;
5790 
5791   if (!Info.CheckCallLimit(CallLoc))
5792     return false;
5793 
5794   CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
5795 
5796   // For a trivial copy or move assignment, perform an APValue copy. This is
5797   // essential for unions, where the operations performed by the assignment
5798   // operator cannot be represented as statements.
5799   //
5800   // Skip this for non-union classes with no fields; in that case, the defaulted
5801   // copy/move does not actually read the object.
5802   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
5803   if (MD && MD->isDefaulted() &&
5804       (MD->getParent()->isUnion() ||
5805        (MD->isTrivial() &&
5806         isReadByLvalueToRvalueConversion(MD->getParent())))) {
5807     assert(This &&
5808            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
5809     LValue RHS;
5810     RHS.setFrom(Info.Ctx, ArgValues[0]);
5811     APValue RHSValue;
5812     if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS,
5813                                         RHSValue, MD->getParent()->isUnion()))
5814       return false;
5815     if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() &&
5816         !HandleUnionActiveMemberChange(Info, Args[0], *This))
5817       return false;
5818     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
5819                           RHSValue))
5820       return false;
5821     This->moveInto(Result);
5822     return true;
5823   } else if (MD && isLambdaCallOperator(MD)) {
5824     // We're in a lambda; determine the lambda capture field maps unless we're
5825     // just constexpr checking a lambda's call operator. constexpr checking is
5826     // done before the captures have been added to the closure object (unless
5827     // we're inferring constexpr-ness), so we don't have access to them in this
5828     // case. But since we don't need the captures to constexpr check, we can
5829     // just ignore them.
5830     if (!Info.checkingPotentialConstantExpression())
5831       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5832                                         Frame.LambdaThisCaptureField);
5833   }
5834 
5835   StmtResult Ret = {Result, ResultSlot};
5836   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
5837   if (ESR == ESR_Succeeded) {
5838     if (Callee->getReturnType()->isVoidType())
5839       return true;
5840     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
5841   }
5842   return ESR == ESR_Returned;
5843 }
5844 
5845 /// Evaluate a constructor call.
5846 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5847                                   APValue *ArgValues,
5848                                   const CXXConstructorDecl *Definition,
5849                                   EvalInfo &Info, APValue &Result) {
5850   SourceLocation CallLoc = E->getExprLoc();
5851   if (!Info.CheckCallLimit(CallLoc))
5852     return false;
5853 
5854   const CXXRecordDecl *RD = Definition->getParent();
5855   if (RD->getNumVBases()) {
5856     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5857     return false;
5858   }
5859 
5860   EvalInfo::EvaluatingConstructorRAII EvalObj(
5861       Info,
5862       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5863       RD->getNumBases());
5864   CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
5865 
5866   // FIXME: Creating an APValue just to hold a nonexistent return value is
5867   // wasteful.
5868   APValue RetVal;
5869   StmtResult Ret = {RetVal, nullptr};
5870 
5871   // If it's a delegating constructor, delegate.
5872   if (Definition->isDelegatingConstructor()) {
5873     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
5874     {
5875       FullExpressionRAII InitScope(Info);
5876       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
5877           !InitScope.destroy())
5878         return false;
5879     }
5880     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5881   }
5882 
5883   // For a trivial copy or move constructor, perform an APValue copy. This is
5884   // essential for unions (or classes with anonymous union members), where the
5885   // operations performed by the constructor cannot be represented by
5886   // ctor-initializers.
5887   //
5888   // Skip this for empty non-union classes; we should not perform an
5889   // lvalue-to-rvalue conversion on them because their copy constructor does not
5890   // actually read them.
5891   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
5892       (Definition->getParent()->isUnion() ||
5893        (Definition->isTrivial() &&
5894         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
5895     LValue RHS;
5896     RHS.setFrom(Info.Ctx, ArgValues[0]);
5897     return handleLValueToRValueConversion(
5898         Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
5899         RHS, Result, Definition->getParent()->isUnion());
5900   }
5901 
5902   // Reserve space for the struct members.
5903   if (!Result.hasValue()) {
5904     if (!RD->isUnion())
5905       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5906                        std::distance(RD->field_begin(), RD->field_end()));
5907     else
5908       // A union starts with no active member.
5909       Result = APValue((const FieldDecl*)nullptr);
5910   }
5911 
5912   if (RD->isInvalidDecl()) return false;
5913   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5914 
5915   // A scope for temporaries lifetime-extended by reference members.
5916   BlockScopeRAII LifetimeExtendedScope(Info);
5917 
5918   bool Success = true;
5919   unsigned BasesSeen = 0;
5920 #ifndef NDEBUG
5921   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5922 #endif
5923   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
5924   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
5925     // We might be initializing the same field again if this is an indirect
5926     // field initialization.
5927     if (FieldIt == RD->field_end() ||
5928         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
5929       assert(Indirect && "fields out of order?");
5930       return;
5931     }
5932 
5933     // Default-initialize any fields with no explicit initializer.
5934     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
5935       assert(FieldIt != RD->field_end() && "missing field?");
5936       if (!FieldIt->isUnnamedBitfield())
5937         Success &= getDefaultInitValue(
5938             FieldIt->getType(),
5939             Result.getStructField(FieldIt->getFieldIndex()));
5940     }
5941     ++FieldIt;
5942   };
5943   for (const auto *I : Definition->inits()) {
5944     LValue Subobject = This;
5945     LValue SubobjectParent = This;
5946     APValue *Value = &Result;
5947 
5948     // Determine the subobject to initialize.
5949     FieldDecl *FD = nullptr;
5950     if (I->isBaseInitializer()) {
5951       QualType BaseType(I->getBaseClass(), 0);
5952 #ifndef NDEBUG
5953       // Non-virtual base classes are initialized in the order in the class
5954       // definition. We have already checked for virtual base classes.
5955       assert(!BaseIt->isVirtual() && "virtual base for literal type");
5956       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5957              "base class initializers not in expected order");
5958       ++BaseIt;
5959 #endif
5960       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
5961                                   BaseType->getAsCXXRecordDecl(), &Layout))
5962         return false;
5963       Value = &Result.getStructBase(BasesSeen++);
5964     } else if ((FD = I->getMember())) {
5965       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
5966         return false;
5967       if (RD->isUnion()) {
5968         Result = APValue(FD);
5969         Value = &Result.getUnionValue();
5970       } else {
5971         SkipToField(FD, false);
5972         Value = &Result.getStructField(FD->getFieldIndex());
5973       }
5974     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
5975       // Walk the indirect field decl's chain to find the object to initialize,
5976       // and make sure we've initialized every step along it.
5977       auto IndirectFieldChain = IFD->chain();
5978       for (auto *C : IndirectFieldChain) {
5979         FD = cast<FieldDecl>(C);
5980         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5981         // Switch the union field if it differs. This happens if we had
5982         // preceding zero-initialization, and we're now initializing a union
5983         // subobject other than the first.
5984         // FIXME: In this case, the values of the other subobjects are
5985         // specified, since zero-initialization sets all padding bits to zero.
5986         if (!Value->hasValue() ||
5987             (Value->isUnion() && Value->getUnionField() != FD)) {
5988           if (CD->isUnion())
5989             *Value = APValue(FD);
5990           else
5991             // FIXME: This immediately starts the lifetime of all members of
5992             // an anonymous struct. It would be preferable to strictly start
5993             // member lifetime in initialization order.
5994             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
5995         }
5996         // Store Subobject as its parent before updating it for the last element
5997         // in the chain.
5998         if (C == IndirectFieldChain.back())
5999           SubobjectParent = Subobject;
6000         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6001           return false;
6002         if (CD->isUnion())
6003           Value = &Value->getUnionValue();
6004         else {
6005           if (C == IndirectFieldChain.front() && !RD->isUnion())
6006             SkipToField(FD, true);
6007           Value = &Value->getStructField(FD->getFieldIndex());
6008         }
6009       }
6010     } else {
6011       llvm_unreachable("unknown base initializer kind");
6012     }
6013 
6014     // Need to override This for implicit field initializers as in this case
6015     // This refers to innermost anonymous struct/union containing initializer,
6016     // not to currently constructed class.
6017     const Expr *Init = I->getInit();
6018     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6019                                   isa<CXXDefaultInitExpr>(Init));
6020     FullExpressionRAII InitScope(Info);
6021     if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6022         (FD && FD->isBitField() &&
6023          !truncateBitfieldValue(Info, Init, *Value, FD))) {
6024       // If we're checking for a potential constant expression, evaluate all
6025       // initializers even if some of them fail.
6026       if (!Info.noteFailure())
6027         return false;
6028       Success = false;
6029     }
6030 
6031     // This is the point at which the dynamic type of the object becomes this
6032     // class type.
6033     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6034       EvalObj.finishedConstructingBases();
6035   }
6036 
6037   // Default-initialize any remaining fields.
6038   if (!RD->isUnion()) {
6039     for (; FieldIt != RD->field_end(); ++FieldIt) {
6040       if (!FieldIt->isUnnamedBitfield())
6041         Success &= getDefaultInitValue(
6042             FieldIt->getType(),
6043             Result.getStructField(FieldIt->getFieldIndex()));
6044     }
6045   }
6046 
6047   EvalObj.finishedConstructingFields();
6048 
6049   return Success &&
6050          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6051          LifetimeExtendedScope.destroy();
6052 }
6053 
6054 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6055                                   ArrayRef<const Expr*> Args,
6056                                   const CXXConstructorDecl *Definition,
6057                                   EvalInfo &Info, APValue &Result) {
6058   ArgVector ArgValues(Args.size());
6059   if (!EvaluateArgs(Args, ArgValues, Info, Definition))
6060     return false;
6061 
6062   return HandleConstructorCall(E, This, ArgValues.data(), Definition,
6063                                Info, Result);
6064 }
6065 
6066 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6067                                   const LValue &This, APValue &Value,
6068                                   QualType T) {
6069   // Objects can only be destroyed while they're within their lifetimes.
6070   // FIXME: We have no representation for whether an object of type nullptr_t
6071   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6072   // as indeterminate instead?
6073   if (Value.isAbsent() && !T->isNullPtrType()) {
6074     APValue Printable;
6075     This.moveInto(Printable);
6076     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6077       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6078     return false;
6079   }
6080 
6081   // Invent an expression for location purposes.
6082   // FIXME: We shouldn't need to do this.
6083   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue);
6084 
6085   // For arrays, destroy elements right-to-left.
6086   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6087     uint64_t Size = CAT->getSize().getZExtValue();
6088     QualType ElemT = CAT->getElementType();
6089 
6090     LValue ElemLV = This;
6091     ElemLV.addArray(Info, &LocE, CAT);
6092     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6093       return false;
6094 
6095     // Ensure that we have actual array elements available to destroy; the
6096     // destructors might mutate the value, so we can't run them on the array
6097     // filler.
6098     if (Size && Size > Value.getArrayInitializedElts())
6099       expandArray(Value, Value.getArraySize() - 1);
6100 
6101     for (; Size != 0; --Size) {
6102       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6103       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6104           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6105         return false;
6106     }
6107 
6108     // End the lifetime of this array now.
6109     Value = APValue();
6110     return true;
6111   }
6112 
6113   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6114   if (!RD) {
6115     if (T.isDestructedType()) {
6116       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6117       return false;
6118     }
6119 
6120     Value = APValue();
6121     return true;
6122   }
6123 
6124   if (RD->getNumVBases()) {
6125     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6126     return false;
6127   }
6128 
6129   const CXXDestructorDecl *DD = RD->getDestructor();
6130   if (!DD && !RD->hasTrivialDestructor()) {
6131     Info.FFDiag(CallLoc);
6132     return false;
6133   }
6134 
6135   if (!DD || DD->isTrivial() ||
6136       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6137     // A trivial destructor just ends the lifetime of the object. Check for
6138     // this case before checking for a body, because we might not bother
6139     // building a body for a trivial destructor. Note that it doesn't matter
6140     // whether the destructor is constexpr in this case; all trivial
6141     // destructors are constexpr.
6142     //
6143     // If an anonymous union would be destroyed, some enclosing destructor must
6144     // have been explicitly defined, and the anonymous union destruction should
6145     // have no effect.
6146     Value = APValue();
6147     return true;
6148   }
6149 
6150   if (!Info.CheckCallLimit(CallLoc))
6151     return false;
6152 
6153   const FunctionDecl *Definition = nullptr;
6154   const Stmt *Body = DD->getBody(Definition);
6155 
6156   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6157     return false;
6158 
6159   CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr);
6160 
6161   // We're now in the period of destruction of this object.
6162   unsigned BasesLeft = RD->getNumBases();
6163   EvalInfo::EvaluatingDestructorRAII EvalObj(
6164       Info,
6165       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6166   if (!EvalObj.DidInsert) {
6167     // C++2a [class.dtor]p19:
6168     //   the behavior is undefined if the destructor is invoked for an object
6169     //   whose lifetime has ended
6170     // (Note that formally the lifetime ends when the period of destruction
6171     // begins, even though certain uses of the object remain valid until the
6172     // period of destruction ends.)
6173     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6174     return false;
6175   }
6176 
6177   // FIXME: Creating an APValue just to hold a nonexistent return value is
6178   // wasteful.
6179   APValue RetVal;
6180   StmtResult Ret = {RetVal, nullptr};
6181   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6182     return false;
6183 
6184   // A union destructor does not implicitly destroy its members.
6185   if (RD->isUnion())
6186     return true;
6187 
6188   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6189 
6190   // We don't have a good way to iterate fields in reverse, so collect all the
6191   // fields first and then walk them backwards.
6192   SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
6193   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6194     if (FD->isUnnamedBitfield())
6195       continue;
6196 
6197     LValue Subobject = This;
6198     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6199       return false;
6200 
6201     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6202     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6203                                FD->getType()))
6204       return false;
6205   }
6206 
6207   if (BasesLeft != 0)
6208     EvalObj.startedDestroyingBases();
6209 
6210   // Destroy base classes in reverse order.
6211   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6212     --BasesLeft;
6213 
6214     QualType BaseType = Base.getType();
6215     LValue Subobject = This;
6216     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6217                                 BaseType->getAsCXXRecordDecl(), &Layout))
6218       return false;
6219 
6220     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6221     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6222                                BaseType))
6223       return false;
6224   }
6225   assert(BasesLeft == 0 && "NumBases was wrong?");
6226 
6227   // The period of destruction ends now. The object is gone.
6228   Value = APValue();
6229   return true;
6230 }
6231 
6232 namespace {
6233 struct DestroyObjectHandler {
6234   EvalInfo &Info;
6235   const Expr *E;
6236   const LValue &This;
6237   const AccessKinds AccessKind;
6238 
6239   typedef bool result_type;
6240   bool failed() { return false; }
6241   bool found(APValue &Subobj, QualType SubobjType) {
6242     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6243                                  SubobjType);
6244   }
6245   bool found(APSInt &Value, QualType SubobjType) {
6246     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6247     return false;
6248   }
6249   bool found(APFloat &Value, QualType SubobjType) {
6250     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6251     return false;
6252   }
6253 };
6254 }
6255 
6256 /// Perform a destructor or pseudo-destructor call on the given object, which
6257 /// might in general not be a complete object.
6258 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6259                               const LValue &This, QualType ThisType) {
6260   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6261   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6262   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6263 }
6264 
6265 /// Destroy and end the lifetime of the given complete object.
6266 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6267                               APValue::LValueBase LVBase, APValue &Value,
6268                               QualType T) {
6269   // If we've had an unmodeled side-effect, we can't rely on mutable state
6270   // (such as the object we're about to destroy) being correct.
6271   if (Info.EvalStatus.HasSideEffects)
6272     return false;
6273 
6274   LValue LV;
6275   LV.set({LVBase});
6276   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6277 }
6278 
6279 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6280 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6281                                   LValue &Result) {
6282   if (Info.checkingPotentialConstantExpression() ||
6283       Info.SpeculativeEvaluationDepth)
6284     return false;
6285 
6286   // This is permitted only within a call to std::allocator<T>::allocate.
6287   auto Caller = Info.getStdAllocatorCaller("allocate");
6288   if (!Caller) {
6289     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6290                                      ? diag::note_constexpr_new_untyped
6291                                      : diag::note_constexpr_new);
6292     return false;
6293   }
6294 
6295   QualType ElemType = Caller.ElemType;
6296   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6297     Info.FFDiag(E->getExprLoc(),
6298                 diag::note_constexpr_new_not_complete_object_type)
6299         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6300     return false;
6301   }
6302 
6303   APSInt ByteSize;
6304   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6305     return false;
6306   bool IsNothrow = false;
6307   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6308     EvaluateIgnoredValue(Info, E->getArg(I));
6309     IsNothrow |= E->getType()->isNothrowT();
6310   }
6311 
6312   CharUnits ElemSize;
6313   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6314     return false;
6315   APInt Size, Remainder;
6316   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6317   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6318   if (Remainder != 0) {
6319     // This likely indicates a bug in the implementation of 'std::allocator'.
6320     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6321         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6322     return false;
6323   }
6324 
6325   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6326     if (IsNothrow) {
6327       Result.setNull(Info.Ctx, E->getType());
6328       return true;
6329     }
6330 
6331     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6332     return false;
6333   }
6334 
6335   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6336                                                      ArrayType::Normal, 0);
6337   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6338   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6339   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6340   return true;
6341 }
6342 
6343 static bool hasVirtualDestructor(QualType T) {
6344   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6345     if (CXXDestructorDecl *DD = RD->getDestructor())
6346       return DD->isVirtual();
6347   return false;
6348 }
6349 
6350 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6351   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6352     if (CXXDestructorDecl *DD = RD->getDestructor())
6353       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6354   return nullptr;
6355 }
6356 
6357 /// Check that the given object is a suitable pointer to a heap allocation that
6358 /// still exists and is of the right kind for the purpose of a deletion.
6359 ///
6360 /// On success, returns the heap allocation to deallocate. On failure, produces
6361 /// a diagnostic and returns None.
6362 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6363                                             const LValue &Pointer,
6364                                             DynAlloc::Kind DeallocKind) {
6365   auto PointerAsString = [&] {
6366     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6367   };
6368 
6369   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6370   if (!DA) {
6371     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6372         << PointerAsString();
6373     if (Pointer.Base)
6374       NoteLValueLocation(Info, Pointer.Base);
6375     return None;
6376   }
6377 
6378   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6379   if (!Alloc) {
6380     Info.FFDiag(E, diag::note_constexpr_double_delete);
6381     return None;
6382   }
6383 
6384   QualType AllocType = Pointer.Base.getDynamicAllocType();
6385   if (DeallocKind != (*Alloc)->getKind()) {
6386     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6387         << DeallocKind << (*Alloc)->getKind() << AllocType;
6388     NoteLValueLocation(Info, Pointer.Base);
6389     return None;
6390   }
6391 
6392   bool Subobject = false;
6393   if (DeallocKind == DynAlloc::New) {
6394     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6395                 Pointer.Designator.isOnePastTheEnd();
6396   } else {
6397     Subobject = Pointer.Designator.Entries.size() != 1 ||
6398                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6399   }
6400   if (Subobject) {
6401     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6402         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6403     return None;
6404   }
6405 
6406   return Alloc;
6407 }
6408 
6409 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6410 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6411   if (Info.checkingPotentialConstantExpression() ||
6412       Info.SpeculativeEvaluationDepth)
6413     return false;
6414 
6415   // This is permitted only within a call to std::allocator<T>::deallocate.
6416   if (!Info.getStdAllocatorCaller("deallocate")) {
6417     Info.FFDiag(E->getExprLoc());
6418     return true;
6419   }
6420 
6421   LValue Pointer;
6422   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6423     return false;
6424   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6425     EvaluateIgnoredValue(Info, E->getArg(I));
6426 
6427   if (Pointer.Designator.Invalid)
6428     return false;
6429 
6430   // Deleting a null pointer has no effect.
6431   if (Pointer.isNullPointer())
6432     return true;
6433 
6434   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6435     return false;
6436 
6437   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6438   return true;
6439 }
6440 
6441 //===----------------------------------------------------------------------===//
6442 // Generic Evaluation
6443 //===----------------------------------------------------------------------===//
6444 namespace {
6445 
6446 class BitCastBuffer {
6447   // FIXME: We're going to need bit-level granularity when we support
6448   // bit-fields.
6449   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6450   // we don't support a host or target where that is the case. Still, we should
6451   // use a more generic type in case we ever do.
6452   SmallVector<Optional<unsigned char>, 32> Bytes;
6453 
6454   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6455                 "Need at least 8 bit unsigned char");
6456 
6457   bool TargetIsLittleEndian;
6458 
6459 public:
6460   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6461       : Bytes(Width.getQuantity()),
6462         TargetIsLittleEndian(TargetIsLittleEndian) {}
6463 
6464   LLVM_NODISCARD
6465   bool readObject(CharUnits Offset, CharUnits Width,
6466                   SmallVectorImpl<unsigned char> &Output) const {
6467     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6468       // If a byte of an integer is uninitialized, then the whole integer is
6469       // uninitalized.
6470       if (!Bytes[I.getQuantity()])
6471         return false;
6472       Output.push_back(*Bytes[I.getQuantity()]);
6473     }
6474     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6475       std::reverse(Output.begin(), Output.end());
6476     return true;
6477   }
6478 
6479   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6480     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6481       std::reverse(Input.begin(), Input.end());
6482 
6483     size_t Index = 0;
6484     for (unsigned char Byte : Input) {
6485       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6486       Bytes[Offset.getQuantity() + Index] = Byte;
6487       ++Index;
6488     }
6489   }
6490 
6491   size_t size() { return Bytes.size(); }
6492 };
6493 
6494 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6495 /// target would represent the value at runtime.
6496 class APValueToBufferConverter {
6497   EvalInfo &Info;
6498   BitCastBuffer Buffer;
6499   const CastExpr *BCE;
6500 
6501   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6502                            const CastExpr *BCE)
6503       : Info(Info),
6504         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6505         BCE(BCE) {}
6506 
6507   bool visit(const APValue &Val, QualType Ty) {
6508     return visit(Val, Ty, CharUnits::fromQuantity(0));
6509   }
6510 
6511   // Write out Val with type Ty into Buffer starting at Offset.
6512   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6513     assert((size_t)Offset.getQuantity() <= Buffer.size());
6514 
6515     // As a special case, nullptr_t has an indeterminate value.
6516     if (Ty->isNullPtrType())
6517       return true;
6518 
6519     // Dig through Src to find the byte at SrcOffset.
6520     switch (Val.getKind()) {
6521     case APValue::Indeterminate:
6522     case APValue::None:
6523       return true;
6524 
6525     case APValue::Int:
6526       return visitInt(Val.getInt(), Ty, Offset);
6527     case APValue::Float:
6528       return visitFloat(Val.getFloat(), Ty, Offset);
6529     case APValue::Array:
6530       return visitArray(Val, Ty, Offset);
6531     case APValue::Struct:
6532       return visitRecord(Val, Ty, Offset);
6533 
6534     case APValue::ComplexInt:
6535     case APValue::ComplexFloat:
6536     case APValue::Vector:
6537     case APValue::FixedPoint:
6538       // FIXME: We should support these.
6539 
6540     case APValue::Union:
6541     case APValue::MemberPointer:
6542     case APValue::AddrLabelDiff: {
6543       Info.FFDiag(BCE->getBeginLoc(),
6544                   diag::note_constexpr_bit_cast_unsupported_type)
6545           << Ty;
6546       return false;
6547     }
6548 
6549     case APValue::LValue:
6550       llvm_unreachable("LValue subobject in bit_cast?");
6551     }
6552     llvm_unreachable("Unhandled APValue::ValueKind");
6553   }
6554 
6555   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6556     const RecordDecl *RD = Ty->getAsRecordDecl();
6557     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6558 
6559     // Visit the base classes.
6560     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6561       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6562         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6563         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6564 
6565         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6566                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6567           return false;
6568       }
6569     }
6570 
6571     // Visit the fields.
6572     unsigned FieldIdx = 0;
6573     for (FieldDecl *FD : RD->fields()) {
6574       if (FD->isBitField()) {
6575         Info.FFDiag(BCE->getBeginLoc(),
6576                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6577         return false;
6578       }
6579 
6580       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6581 
6582       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6583              "only bit-fields can have sub-char alignment");
6584       CharUnits FieldOffset =
6585           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6586       QualType FieldTy = FD->getType();
6587       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6588         return false;
6589       ++FieldIdx;
6590     }
6591 
6592     return true;
6593   }
6594 
6595   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6596     const auto *CAT =
6597         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6598     if (!CAT)
6599       return false;
6600 
6601     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6602     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6603     unsigned ArraySize = Val.getArraySize();
6604     // First, initialize the initialized elements.
6605     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6606       const APValue &SubObj = Val.getArrayInitializedElt(I);
6607       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6608         return false;
6609     }
6610 
6611     // Next, initialize the rest of the array using the filler.
6612     if (Val.hasArrayFiller()) {
6613       const APValue &Filler = Val.getArrayFiller();
6614       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6615         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6616           return false;
6617       }
6618     }
6619 
6620     return true;
6621   }
6622 
6623   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6624     APSInt AdjustedVal = Val;
6625     unsigned Width = AdjustedVal.getBitWidth();
6626     if (Ty->isBooleanType()) {
6627       Width = Info.Ctx.getTypeSize(Ty);
6628       AdjustedVal = AdjustedVal.extend(Width);
6629     }
6630 
6631     SmallVector<unsigned char, 8> Bytes(Width / 8);
6632     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
6633     Buffer.writeObject(Offset, Bytes);
6634     return true;
6635   }
6636 
6637   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6638     APSInt AsInt(Val.bitcastToAPInt());
6639     return visitInt(AsInt, Ty, Offset);
6640   }
6641 
6642 public:
6643   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6644                                          const CastExpr *BCE) {
6645     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6646     APValueToBufferConverter Converter(Info, DstSize, BCE);
6647     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6648       return None;
6649     return Converter.Buffer;
6650   }
6651 };
6652 
6653 /// Write an BitCastBuffer into an APValue.
6654 class BufferToAPValueConverter {
6655   EvalInfo &Info;
6656   const BitCastBuffer &Buffer;
6657   const CastExpr *BCE;
6658 
6659   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6660                            const CastExpr *BCE)
6661       : Info(Info), Buffer(Buffer), BCE(BCE) {}
6662 
6663   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6664   // with an invalid type, so anything left is a deficiency on our part (FIXME).
6665   // Ideally this will be unreachable.
6666   llvm::NoneType unsupportedType(QualType Ty) {
6667     Info.FFDiag(BCE->getBeginLoc(),
6668                 diag::note_constexpr_bit_cast_unsupported_type)
6669         << Ty;
6670     return None;
6671   }
6672 
6673   llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) {
6674     Info.FFDiag(BCE->getBeginLoc(),
6675                 diag::note_constexpr_bit_cast_unrepresentable_value)
6676         << Ty << Val.toString(/*Radix=*/10);
6677     return None;
6678   }
6679 
6680   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6681                           const EnumType *EnumSugar = nullptr) {
6682     if (T->isNullPtrType()) {
6683       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6684       return APValue((Expr *)nullptr,
6685                      /*Offset=*/CharUnits::fromQuantity(NullValue),
6686                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6687     }
6688 
6689     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6690 
6691     // Work around floating point types that contain unused padding bytes. This
6692     // is really just `long double` on x86, which is the only fundamental type
6693     // with padding bytes.
6694     if (T->isRealFloatingType()) {
6695       const llvm::fltSemantics &Semantics =
6696           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6697       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
6698       assert(NumBits % 8 == 0);
6699       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
6700       if (NumBytes != SizeOf)
6701         SizeOf = NumBytes;
6702     }
6703 
6704     SmallVector<uint8_t, 8> Bytes;
6705     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
6706       // If this is std::byte or unsigned char, then its okay to store an
6707       // indeterminate value.
6708       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
6709       bool IsUChar =
6710           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
6711                          T->isSpecificBuiltinType(BuiltinType::Char_U));
6712       if (!IsStdByte && !IsUChar) {
6713         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
6714         Info.FFDiag(BCE->getExprLoc(),
6715                     diag::note_constexpr_bit_cast_indet_dest)
6716             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
6717         return None;
6718       }
6719 
6720       return APValue::IndeterminateValue();
6721     }
6722 
6723     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
6724     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
6725 
6726     if (T->isIntegralOrEnumerationType()) {
6727       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
6728 
6729       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
6730       if (IntWidth != Val.getBitWidth()) {
6731         APSInt Truncated = Val.trunc(IntWidth);
6732         if (Truncated.extend(Val.getBitWidth()) != Val)
6733           return unrepresentableValue(QualType(T, 0), Val);
6734         Val = Truncated;
6735       }
6736 
6737       return APValue(Val);
6738     }
6739 
6740     if (T->isRealFloatingType()) {
6741       const llvm::fltSemantics &Semantics =
6742           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6743       return APValue(APFloat(Semantics, Val));
6744     }
6745 
6746     return unsupportedType(QualType(T, 0));
6747   }
6748 
6749   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
6750     const RecordDecl *RD = RTy->getAsRecordDecl();
6751     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6752 
6753     unsigned NumBases = 0;
6754     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6755       NumBases = CXXRD->getNumBases();
6756 
6757     APValue ResultVal(APValue::UninitStruct(), NumBases,
6758                       std::distance(RD->field_begin(), RD->field_end()));
6759 
6760     // Visit the base classes.
6761     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6762       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6763         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6764         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6765         if (BaseDecl->isEmpty() ||
6766             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
6767           continue;
6768 
6769         Optional<APValue> SubObj = visitType(
6770             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
6771         if (!SubObj)
6772           return None;
6773         ResultVal.getStructBase(I) = *SubObj;
6774       }
6775     }
6776 
6777     // Visit the fields.
6778     unsigned FieldIdx = 0;
6779     for (FieldDecl *FD : RD->fields()) {
6780       // FIXME: We don't currently support bit-fields. A lot of the logic for
6781       // this is in CodeGen, so we need to factor it around.
6782       if (FD->isBitField()) {
6783         Info.FFDiag(BCE->getBeginLoc(),
6784                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6785         return None;
6786       }
6787 
6788       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6789       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
6790 
6791       CharUnits FieldOffset =
6792           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
6793           Offset;
6794       QualType FieldTy = FD->getType();
6795       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
6796       if (!SubObj)
6797         return None;
6798       ResultVal.getStructField(FieldIdx) = *SubObj;
6799       ++FieldIdx;
6800     }
6801 
6802     return ResultVal;
6803   }
6804 
6805   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
6806     QualType RepresentationType = Ty->getDecl()->getIntegerType();
6807     assert(!RepresentationType.isNull() &&
6808            "enum forward decl should be caught by Sema");
6809     const auto *AsBuiltin =
6810         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
6811     // Recurse into the underlying type. Treat std::byte transparently as
6812     // unsigned char.
6813     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
6814   }
6815 
6816   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
6817     size_t Size = Ty->getSize().getLimitedValue();
6818     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
6819 
6820     APValue ArrayValue(APValue::UninitArray(), Size, Size);
6821     for (size_t I = 0; I != Size; ++I) {
6822       Optional<APValue> ElementValue =
6823           visitType(Ty->getElementType(), Offset + I * ElementWidth);
6824       if (!ElementValue)
6825         return None;
6826       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
6827     }
6828 
6829     return ArrayValue;
6830   }
6831 
6832   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
6833     return unsupportedType(QualType(Ty, 0));
6834   }
6835 
6836   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
6837     QualType Can = Ty.getCanonicalType();
6838 
6839     switch (Can->getTypeClass()) {
6840 #define TYPE(Class, Base)                                                      \
6841   case Type::Class:                                                            \
6842     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
6843 #define ABSTRACT_TYPE(Class, Base)
6844 #define NON_CANONICAL_TYPE(Class, Base)                                        \
6845   case Type::Class:                                                            \
6846     llvm_unreachable("non-canonical type should be impossible!");
6847 #define DEPENDENT_TYPE(Class, Base)                                            \
6848   case Type::Class:                                                            \
6849     llvm_unreachable(                                                          \
6850         "dependent types aren't supported in the constant evaluator!");
6851 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
6852   case Type::Class:                                                            \
6853     llvm_unreachable("either dependent or not canonical!");
6854 #include "clang/AST/TypeNodes.inc"
6855     }
6856     llvm_unreachable("Unhandled Type::TypeClass");
6857   }
6858 
6859 public:
6860   // Pull out a full value of type DstType.
6861   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
6862                                    const CastExpr *BCE) {
6863     BufferToAPValueConverter Converter(Info, Buffer, BCE);
6864     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
6865   }
6866 };
6867 
6868 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
6869                                                  QualType Ty, EvalInfo *Info,
6870                                                  const ASTContext &Ctx,
6871                                                  bool CheckingDest) {
6872   Ty = Ty.getCanonicalType();
6873 
6874   auto diag = [&](int Reason) {
6875     if (Info)
6876       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
6877           << CheckingDest << (Reason == 4) << Reason;
6878     return false;
6879   };
6880   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
6881     if (Info)
6882       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
6883           << NoteTy << Construct << Ty;
6884     return false;
6885   };
6886 
6887   if (Ty->isUnionType())
6888     return diag(0);
6889   if (Ty->isPointerType())
6890     return diag(1);
6891   if (Ty->isMemberPointerType())
6892     return diag(2);
6893   if (Ty.isVolatileQualified())
6894     return diag(3);
6895 
6896   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
6897     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
6898       for (CXXBaseSpecifier &BS : CXXRD->bases())
6899         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
6900                                                   CheckingDest))
6901           return note(1, BS.getType(), BS.getBeginLoc());
6902     }
6903     for (FieldDecl *FD : Record->fields()) {
6904       if (FD->getType()->isReferenceType())
6905         return diag(4);
6906       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
6907                                                 CheckingDest))
6908         return note(0, FD->getType(), FD->getBeginLoc());
6909     }
6910   }
6911 
6912   if (Ty->isArrayType() &&
6913       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
6914                                             Info, Ctx, CheckingDest))
6915     return false;
6916 
6917   return true;
6918 }
6919 
6920 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
6921                                              const ASTContext &Ctx,
6922                                              const CastExpr *BCE) {
6923   bool DestOK = checkBitCastConstexprEligibilityType(
6924       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
6925   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
6926                                 BCE->getBeginLoc(),
6927                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
6928   return SourceOK;
6929 }
6930 
6931 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
6932                                         APValue &SourceValue,
6933                                         const CastExpr *BCE) {
6934   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
6935          "no host or target supports non 8-bit chars");
6936   assert(SourceValue.isLValue() &&
6937          "LValueToRValueBitcast requires an lvalue operand!");
6938 
6939   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
6940     return false;
6941 
6942   LValue SourceLValue;
6943   APValue SourceRValue;
6944   SourceLValue.setFrom(Info.Ctx, SourceValue);
6945   if (!handleLValueToRValueConversion(
6946           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
6947           SourceRValue, /*WantObjectRepresentation=*/true))
6948     return false;
6949 
6950   // Read out SourceValue into a char buffer.
6951   Optional<BitCastBuffer> Buffer =
6952       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
6953   if (!Buffer)
6954     return false;
6955 
6956   // Write out the buffer into a new APValue.
6957   Optional<APValue> MaybeDestValue =
6958       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
6959   if (!MaybeDestValue)
6960     return false;
6961 
6962   DestValue = std::move(*MaybeDestValue);
6963   return true;
6964 }
6965 
6966 template <class Derived>
6967 class ExprEvaluatorBase
6968   : public ConstStmtVisitor<Derived, bool> {
6969 private:
6970   Derived &getDerived() { return static_cast<Derived&>(*this); }
6971   bool DerivedSuccess(const APValue &V, const Expr *E) {
6972     return getDerived().Success(V, E);
6973   }
6974   bool DerivedZeroInitialization(const Expr *E) {
6975     return getDerived().ZeroInitialization(E);
6976   }
6977 
6978   // Check whether a conditional operator with a non-constant condition is a
6979   // potential constant expression. If neither arm is a potential constant
6980   // expression, then the conditional operator is not either.
6981   template<typename ConditionalOperator>
6982   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
6983     assert(Info.checkingPotentialConstantExpression());
6984 
6985     // Speculatively evaluate both arms.
6986     SmallVector<PartialDiagnosticAt, 8> Diag;
6987     {
6988       SpeculativeEvaluationRAII Speculate(Info, &Diag);
6989       StmtVisitorTy::Visit(E->getFalseExpr());
6990       if (Diag.empty())
6991         return;
6992     }
6993 
6994     {
6995       SpeculativeEvaluationRAII Speculate(Info, &Diag);
6996       Diag.clear();
6997       StmtVisitorTy::Visit(E->getTrueExpr());
6998       if (Diag.empty())
6999         return;
7000     }
7001 
7002     Error(E, diag::note_constexpr_conditional_never_const);
7003   }
7004 
7005 
7006   template<typename ConditionalOperator>
7007   bool HandleConditionalOperator(const ConditionalOperator *E) {
7008     bool BoolResult;
7009     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7010       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7011         CheckPotentialConstantConditional(E);
7012         return false;
7013       }
7014       if (Info.noteFailure()) {
7015         StmtVisitorTy::Visit(E->getTrueExpr());
7016         StmtVisitorTy::Visit(E->getFalseExpr());
7017       }
7018       return false;
7019     }
7020 
7021     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7022     return StmtVisitorTy::Visit(EvalExpr);
7023   }
7024 
7025 protected:
7026   EvalInfo &Info;
7027   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7028   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7029 
7030   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7031     return Info.CCEDiag(E, D);
7032   }
7033 
7034   bool ZeroInitialization(const Expr *E) { return Error(E); }
7035 
7036 public:
7037   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7038 
7039   EvalInfo &getEvalInfo() { return Info; }
7040 
7041   /// Report an evaluation error. This should only be called when an error is
7042   /// first discovered. When propagating an error, just return false.
7043   bool Error(const Expr *E, diag::kind D) {
7044     Info.FFDiag(E, D);
7045     return false;
7046   }
7047   bool Error(const Expr *E) {
7048     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7049   }
7050 
7051   bool VisitStmt(const Stmt *) {
7052     llvm_unreachable("Expression evaluator should not be called on stmts");
7053   }
7054   bool VisitExpr(const Expr *E) {
7055     return Error(E);
7056   }
7057 
7058   bool VisitConstantExpr(const ConstantExpr *E) {
7059     if (E->hasAPValueResult())
7060       return DerivedSuccess(E->getAPValueResult(), E);
7061 
7062     return StmtVisitorTy::Visit(E->getSubExpr());
7063   }
7064 
7065   bool VisitParenExpr(const ParenExpr *E)
7066     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7067   bool VisitUnaryExtension(const UnaryOperator *E)
7068     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7069   bool VisitUnaryPlus(const UnaryOperator *E)
7070     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7071   bool VisitChooseExpr(const ChooseExpr *E)
7072     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7073   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7074     { return StmtVisitorTy::Visit(E->getResultExpr()); }
7075   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7076     { return StmtVisitorTy::Visit(E->getReplacement()); }
7077   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7078     TempVersionRAII RAII(*Info.CurrentCall);
7079     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7080     return StmtVisitorTy::Visit(E->getExpr());
7081   }
7082   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7083     TempVersionRAII RAII(*Info.CurrentCall);
7084     // The initializer may not have been parsed yet, or might be erroneous.
7085     if (!E->getExpr())
7086       return Error(E);
7087     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7088     return StmtVisitorTy::Visit(E->getExpr());
7089   }
7090 
7091   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7092     FullExpressionRAII Scope(Info);
7093     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7094   }
7095 
7096   // Temporaries are registered when created, so we don't care about
7097   // CXXBindTemporaryExpr.
7098   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7099     return StmtVisitorTy::Visit(E->getSubExpr());
7100   }
7101 
7102   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7103     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7104     return static_cast<Derived*>(this)->VisitCastExpr(E);
7105   }
7106   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7107     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7108       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7109     return static_cast<Derived*>(this)->VisitCastExpr(E);
7110   }
7111   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7112     return static_cast<Derived*>(this)->VisitCastExpr(E);
7113   }
7114 
7115   bool VisitBinaryOperator(const BinaryOperator *E) {
7116     switch (E->getOpcode()) {
7117     default:
7118       return Error(E);
7119 
7120     case BO_Comma:
7121       VisitIgnoredValue(E->getLHS());
7122       return StmtVisitorTy::Visit(E->getRHS());
7123 
7124     case BO_PtrMemD:
7125     case BO_PtrMemI: {
7126       LValue Obj;
7127       if (!HandleMemberPointerAccess(Info, E, Obj))
7128         return false;
7129       APValue Result;
7130       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7131         return false;
7132       return DerivedSuccess(Result, E);
7133     }
7134     }
7135   }
7136 
7137   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7138     return StmtVisitorTy::Visit(E->getSemanticForm());
7139   }
7140 
7141   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7142     // Evaluate and cache the common expression. We treat it as a temporary,
7143     // even though it's not quite the same thing.
7144     LValue CommonLV;
7145     if (!Evaluate(Info.CurrentCall->createTemporary(
7146                       E->getOpaqueValue(),
7147                       getStorageType(Info.Ctx, E->getOpaqueValue()), false,
7148                       CommonLV),
7149                   Info, E->getCommon()))
7150       return false;
7151 
7152     return HandleConditionalOperator(E);
7153   }
7154 
7155   bool VisitConditionalOperator(const ConditionalOperator *E) {
7156     bool IsBcpCall = false;
7157     // If the condition (ignoring parens) is a __builtin_constant_p call,
7158     // the result is a constant expression if it can be folded without
7159     // side-effects. This is an important GNU extension. See GCC PR38377
7160     // for discussion.
7161     if (const CallExpr *CallCE =
7162           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7163       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7164         IsBcpCall = true;
7165 
7166     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7167     // constant expression; we can't check whether it's potentially foldable.
7168     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7169     // it would return 'false' in this mode.
7170     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7171       return false;
7172 
7173     FoldConstant Fold(Info, IsBcpCall);
7174     if (!HandleConditionalOperator(E)) {
7175       Fold.keepDiagnostics();
7176       return false;
7177     }
7178 
7179     return true;
7180   }
7181 
7182   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7183     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7184       return DerivedSuccess(*Value, E);
7185 
7186     const Expr *Source = E->getSourceExpr();
7187     if (!Source)
7188       return Error(E);
7189     if (Source == E) { // sanity checking.
7190       assert(0 && "OpaqueValueExpr recursively refers to itself");
7191       return Error(E);
7192     }
7193     return StmtVisitorTy::Visit(Source);
7194   }
7195 
7196   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7197     for (const Expr *SemE : E->semantics()) {
7198       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7199         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7200         // result expression: there could be two different LValues that would
7201         // refer to the same object in that case, and we can't model that.
7202         if (SemE == E->getResultExpr())
7203           return Error(E);
7204 
7205         // Unique OVEs get evaluated if and when we encounter them when
7206         // emitting the rest of the semantic form, rather than eagerly.
7207         if (OVE->isUnique())
7208           continue;
7209 
7210         LValue LV;
7211         if (!Evaluate(Info.CurrentCall->createTemporary(
7212                           OVE, getStorageType(Info.Ctx, OVE), false, LV),
7213                       Info, OVE->getSourceExpr()))
7214           return false;
7215       } else if (SemE == E->getResultExpr()) {
7216         if (!StmtVisitorTy::Visit(SemE))
7217           return false;
7218       } else {
7219         if (!EvaluateIgnoredValue(Info, SemE))
7220           return false;
7221       }
7222     }
7223     return true;
7224   }
7225 
7226   bool VisitCallExpr(const CallExpr *E) {
7227     APValue Result;
7228     if (!handleCallExpr(E, Result, nullptr))
7229       return false;
7230     return DerivedSuccess(Result, E);
7231   }
7232 
7233   bool handleCallExpr(const CallExpr *E, APValue &Result,
7234                      const LValue *ResultSlot) {
7235     const Expr *Callee = E->getCallee()->IgnoreParens();
7236     QualType CalleeType = Callee->getType();
7237 
7238     const FunctionDecl *FD = nullptr;
7239     LValue *This = nullptr, ThisVal;
7240     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7241     bool HasQualifier = false;
7242 
7243     // Extract function decl and 'this' pointer from the callee.
7244     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7245       const CXXMethodDecl *Member = nullptr;
7246       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7247         // Explicit bound member calls, such as x.f() or p->g();
7248         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7249           return false;
7250         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7251         if (!Member)
7252           return Error(Callee);
7253         This = &ThisVal;
7254         HasQualifier = ME->hasQualifier();
7255       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7256         // Indirect bound member calls ('.*' or '->*').
7257         const ValueDecl *D =
7258             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7259         if (!D)
7260           return false;
7261         Member = dyn_cast<CXXMethodDecl>(D);
7262         if (!Member)
7263           return Error(Callee);
7264         This = &ThisVal;
7265       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7266         if (!Info.getLangOpts().CPlusPlus20)
7267           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7268         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7269                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7270       } else
7271         return Error(Callee);
7272       FD = Member;
7273     } else if (CalleeType->isFunctionPointerType()) {
7274       LValue Call;
7275       if (!EvaluatePointer(Callee, Call, Info))
7276         return false;
7277 
7278       if (!Call.getLValueOffset().isZero())
7279         return Error(Callee);
7280       FD = dyn_cast_or_null<FunctionDecl>(
7281                              Call.getLValueBase().dyn_cast<const ValueDecl*>());
7282       if (!FD)
7283         return Error(Callee);
7284       // Don't call function pointers which have been cast to some other type.
7285       // Per DR (no number yet), the caller and callee can differ in noexcept.
7286       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7287         CalleeType->getPointeeType(), FD->getType())) {
7288         return Error(E);
7289       }
7290 
7291       // Overloaded operator calls to member functions are represented as normal
7292       // calls with '*this' as the first argument.
7293       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7294       if (MD && !MD->isStatic()) {
7295         // FIXME: When selecting an implicit conversion for an overloaded
7296         // operator delete, we sometimes try to evaluate calls to conversion
7297         // operators without a 'this' parameter!
7298         if (Args.empty())
7299           return Error(E);
7300 
7301         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7302           return false;
7303         This = &ThisVal;
7304         Args = Args.slice(1);
7305       } else if (MD && MD->isLambdaStaticInvoker()) {
7306         // Map the static invoker for the lambda back to the call operator.
7307         // Conveniently, we don't have to slice out the 'this' argument (as is
7308         // being done for the non-static case), since a static member function
7309         // doesn't have an implicit argument passed in.
7310         const CXXRecordDecl *ClosureClass = MD->getParent();
7311         assert(
7312             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7313             "Number of captures must be zero for conversion to function-ptr");
7314 
7315         const CXXMethodDecl *LambdaCallOp =
7316             ClosureClass->getLambdaCallOperator();
7317 
7318         // Set 'FD', the function that will be called below, to the call
7319         // operator.  If the closure object represents a generic lambda, find
7320         // the corresponding specialization of the call operator.
7321 
7322         if (ClosureClass->isGenericLambda()) {
7323           assert(MD->isFunctionTemplateSpecialization() &&
7324                  "A generic lambda's static-invoker function must be a "
7325                  "template specialization");
7326           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7327           FunctionTemplateDecl *CallOpTemplate =
7328               LambdaCallOp->getDescribedFunctionTemplate();
7329           void *InsertPos = nullptr;
7330           FunctionDecl *CorrespondingCallOpSpecialization =
7331               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7332           assert(CorrespondingCallOpSpecialization &&
7333                  "We must always have a function call operator specialization "
7334                  "that corresponds to our static invoker specialization");
7335           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7336         } else
7337           FD = LambdaCallOp;
7338       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7339         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7340             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7341           LValue Ptr;
7342           if (!HandleOperatorNewCall(Info, E, Ptr))
7343             return false;
7344           Ptr.moveInto(Result);
7345           return true;
7346         } else {
7347           return HandleOperatorDeleteCall(Info, E);
7348         }
7349       }
7350     } else
7351       return Error(E);
7352 
7353     SmallVector<QualType, 4> CovariantAdjustmentPath;
7354     if (This) {
7355       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7356       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7357         // Perform virtual dispatch, if necessary.
7358         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7359                                    CovariantAdjustmentPath);
7360         if (!FD)
7361           return false;
7362       } else {
7363         // Check that the 'this' pointer points to an object of the right type.
7364         // FIXME: If this is an assignment operator call, we may need to change
7365         // the active union member before we check this.
7366         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7367           return false;
7368       }
7369     }
7370 
7371     // Destructor calls are different enough that they have their own codepath.
7372     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7373       assert(This && "no 'this' pointer for destructor call");
7374       return HandleDestruction(Info, E, *This,
7375                                Info.Ctx.getRecordType(DD->getParent()));
7376     }
7377 
7378     const FunctionDecl *Definition = nullptr;
7379     Stmt *Body = FD->getBody(Definition);
7380 
7381     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7382         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
7383                             Result, ResultSlot))
7384       return false;
7385 
7386     if (!CovariantAdjustmentPath.empty() &&
7387         !HandleCovariantReturnAdjustment(Info, E, Result,
7388                                          CovariantAdjustmentPath))
7389       return false;
7390 
7391     return true;
7392   }
7393 
7394   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7395     return StmtVisitorTy::Visit(E->getInitializer());
7396   }
7397   bool VisitInitListExpr(const InitListExpr *E) {
7398     if (E->getNumInits() == 0)
7399       return DerivedZeroInitialization(E);
7400     if (E->getNumInits() == 1)
7401       return StmtVisitorTy::Visit(E->getInit(0));
7402     return Error(E);
7403   }
7404   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7405     return DerivedZeroInitialization(E);
7406   }
7407   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7408     return DerivedZeroInitialization(E);
7409   }
7410   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7411     return DerivedZeroInitialization(E);
7412   }
7413 
7414   /// A member expression where the object is a prvalue is itself a prvalue.
7415   bool VisitMemberExpr(const MemberExpr *E) {
7416     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7417            "missing temporary materialization conversion");
7418     assert(!E->isArrow() && "missing call to bound member function?");
7419 
7420     APValue Val;
7421     if (!Evaluate(Val, Info, E->getBase()))
7422       return false;
7423 
7424     QualType BaseTy = E->getBase()->getType();
7425 
7426     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7427     if (!FD) return Error(E);
7428     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7429     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7430            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7431 
7432     // Note: there is no lvalue base here. But this case should only ever
7433     // happen in C or in C++98, where we cannot be evaluating a constexpr
7434     // constructor, which is the only case the base matters.
7435     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7436     SubobjectDesignator Designator(BaseTy);
7437     Designator.addDeclUnchecked(FD);
7438 
7439     APValue Result;
7440     return extractSubobject(Info, E, Obj, Designator, Result) &&
7441            DerivedSuccess(Result, E);
7442   }
7443 
7444   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7445     APValue Val;
7446     if (!Evaluate(Val, Info, E->getBase()))
7447       return false;
7448 
7449     if (Val.isVector()) {
7450       SmallVector<uint32_t, 4> Indices;
7451       E->getEncodedElementAccess(Indices);
7452       if (Indices.size() == 1) {
7453         // Return scalar.
7454         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7455       } else {
7456         // Construct new APValue vector.
7457         SmallVector<APValue, 4> Elts;
7458         for (unsigned I = 0; I < Indices.size(); ++I) {
7459           Elts.push_back(Val.getVectorElt(Indices[I]));
7460         }
7461         APValue VecResult(Elts.data(), Indices.size());
7462         return DerivedSuccess(VecResult, E);
7463       }
7464     }
7465 
7466     return false;
7467   }
7468 
7469   bool VisitCastExpr(const CastExpr *E) {
7470     switch (E->getCastKind()) {
7471     default:
7472       break;
7473 
7474     case CK_AtomicToNonAtomic: {
7475       APValue AtomicVal;
7476       // This does not need to be done in place even for class/array types:
7477       // atomic-to-non-atomic conversion implies copying the object
7478       // representation.
7479       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7480         return false;
7481       return DerivedSuccess(AtomicVal, E);
7482     }
7483 
7484     case CK_NoOp:
7485     case CK_UserDefinedConversion:
7486       return StmtVisitorTy::Visit(E->getSubExpr());
7487 
7488     case CK_LValueToRValue: {
7489       LValue LVal;
7490       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7491         return false;
7492       APValue RVal;
7493       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7494       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7495                                           LVal, RVal))
7496         return false;
7497       return DerivedSuccess(RVal, E);
7498     }
7499     case CK_LValueToRValueBitCast: {
7500       APValue DestValue, SourceValue;
7501       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7502         return false;
7503       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7504         return false;
7505       return DerivedSuccess(DestValue, E);
7506     }
7507 
7508     case CK_AddressSpaceConversion: {
7509       APValue Value;
7510       if (!Evaluate(Value, Info, E->getSubExpr()))
7511         return false;
7512       return DerivedSuccess(Value, E);
7513     }
7514     }
7515 
7516     return Error(E);
7517   }
7518 
7519   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7520     return VisitUnaryPostIncDec(UO);
7521   }
7522   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7523     return VisitUnaryPostIncDec(UO);
7524   }
7525   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7526     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7527       return Error(UO);
7528 
7529     LValue LVal;
7530     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7531       return false;
7532     APValue RVal;
7533     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7534                       UO->isIncrementOp(), &RVal))
7535       return false;
7536     return DerivedSuccess(RVal, UO);
7537   }
7538 
7539   bool VisitStmtExpr(const StmtExpr *E) {
7540     // We will have checked the full-expressions inside the statement expression
7541     // when they were completed, and don't need to check them again now.
7542     if (Info.checkingForUndefinedBehavior())
7543       return Error(E);
7544 
7545     const CompoundStmt *CS = E->getSubStmt();
7546     if (CS->body_empty())
7547       return true;
7548 
7549     BlockScopeRAII Scope(Info);
7550     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7551                                            BE = CS->body_end();
7552          /**/; ++BI) {
7553       if (BI + 1 == BE) {
7554         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7555         if (!FinalExpr) {
7556           Info.FFDiag((*BI)->getBeginLoc(),
7557                       diag::note_constexpr_stmt_expr_unsupported);
7558           return false;
7559         }
7560         return this->Visit(FinalExpr) && Scope.destroy();
7561       }
7562 
7563       APValue ReturnValue;
7564       StmtResult Result = { ReturnValue, nullptr };
7565       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7566       if (ESR != ESR_Succeeded) {
7567         // FIXME: If the statement-expression terminated due to 'return',
7568         // 'break', or 'continue', it would be nice to propagate that to
7569         // the outer statement evaluation rather than bailing out.
7570         if (ESR != ESR_Failed)
7571           Info.FFDiag((*BI)->getBeginLoc(),
7572                       diag::note_constexpr_stmt_expr_unsupported);
7573         return false;
7574       }
7575     }
7576 
7577     llvm_unreachable("Return from function from the loop above.");
7578   }
7579 
7580   /// Visit a value which is evaluated, but whose value is ignored.
7581   void VisitIgnoredValue(const Expr *E) {
7582     EvaluateIgnoredValue(Info, E);
7583   }
7584 
7585   /// Potentially visit a MemberExpr's base expression.
7586   void VisitIgnoredBaseExpression(const Expr *E) {
7587     // While MSVC doesn't evaluate the base expression, it does diagnose the
7588     // presence of side-effecting behavior.
7589     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7590       return;
7591     VisitIgnoredValue(E);
7592   }
7593 };
7594 
7595 } // namespace
7596 
7597 //===----------------------------------------------------------------------===//
7598 // Common base class for lvalue and temporary evaluation.
7599 //===----------------------------------------------------------------------===//
7600 namespace {
7601 template<class Derived>
7602 class LValueExprEvaluatorBase
7603   : public ExprEvaluatorBase<Derived> {
7604 protected:
7605   LValue &Result;
7606   bool InvalidBaseOK;
7607   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7608   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7609 
7610   bool Success(APValue::LValueBase B) {
7611     Result.set(B);
7612     return true;
7613   }
7614 
7615   bool evaluatePointer(const Expr *E, LValue &Result) {
7616     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7617   }
7618 
7619 public:
7620   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7621       : ExprEvaluatorBaseTy(Info), Result(Result),
7622         InvalidBaseOK(InvalidBaseOK) {}
7623 
7624   bool Success(const APValue &V, const Expr *E) {
7625     Result.setFrom(this->Info.Ctx, V);
7626     return true;
7627   }
7628 
7629   bool VisitMemberExpr(const MemberExpr *E) {
7630     // Handle non-static data members.
7631     QualType BaseTy;
7632     bool EvalOK;
7633     if (E->isArrow()) {
7634       EvalOK = evaluatePointer(E->getBase(), Result);
7635       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
7636     } else if (E->getBase()->isRValue()) {
7637       assert(E->getBase()->getType()->isRecordType());
7638       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
7639       BaseTy = E->getBase()->getType();
7640     } else {
7641       EvalOK = this->Visit(E->getBase());
7642       BaseTy = E->getBase()->getType();
7643     }
7644     if (!EvalOK) {
7645       if (!InvalidBaseOK)
7646         return false;
7647       Result.setInvalid(E);
7648       return true;
7649     }
7650 
7651     const ValueDecl *MD = E->getMemberDecl();
7652     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
7653       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7654              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7655       (void)BaseTy;
7656       if (!HandleLValueMember(this->Info, E, Result, FD))
7657         return false;
7658     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
7659       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
7660         return false;
7661     } else
7662       return this->Error(E);
7663 
7664     if (MD->getType()->isReferenceType()) {
7665       APValue RefValue;
7666       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
7667                                           RefValue))
7668         return false;
7669       return Success(RefValue, E);
7670     }
7671     return true;
7672   }
7673 
7674   bool VisitBinaryOperator(const BinaryOperator *E) {
7675     switch (E->getOpcode()) {
7676     default:
7677       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7678 
7679     case BO_PtrMemD:
7680     case BO_PtrMemI:
7681       return HandleMemberPointerAccess(this->Info, E, Result);
7682     }
7683   }
7684 
7685   bool VisitCastExpr(const CastExpr *E) {
7686     switch (E->getCastKind()) {
7687     default:
7688       return ExprEvaluatorBaseTy::VisitCastExpr(E);
7689 
7690     case CK_DerivedToBase:
7691     case CK_UncheckedDerivedToBase:
7692       if (!this->Visit(E->getSubExpr()))
7693         return false;
7694 
7695       // Now figure out the necessary offset to add to the base LV to get from
7696       // the derived class to the base class.
7697       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
7698                                   Result);
7699     }
7700   }
7701 };
7702 }
7703 
7704 //===----------------------------------------------------------------------===//
7705 // LValue Evaluation
7706 //
7707 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
7708 // function designators (in C), decl references to void objects (in C), and
7709 // temporaries (if building with -Wno-address-of-temporary).
7710 //
7711 // LValue evaluation produces values comprising a base expression of one of the
7712 // following types:
7713 // - Declarations
7714 //  * VarDecl
7715 //  * FunctionDecl
7716 // - Literals
7717 //  * CompoundLiteralExpr in C (and in global scope in C++)
7718 //  * StringLiteral
7719 //  * PredefinedExpr
7720 //  * ObjCStringLiteralExpr
7721 //  * ObjCEncodeExpr
7722 //  * AddrLabelExpr
7723 //  * BlockExpr
7724 //  * CallExpr for a MakeStringConstant builtin
7725 // - typeid(T) expressions, as TypeInfoLValues
7726 // - Locals and temporaries
7727 //  * MaterializeTemporaryExpr
7728 //  * Any Expr, with a CallIndex indicating the function in which the temporary
7729 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
7730 //    from the AST (FIXME).
7731 //  * A MaterializeTemporaryExpr that has static storage duration, with no
7732 //    CallIndex, for a lifetime-extended temporary.
7733 //  * The ConstantExpr that is currently being evaluated during evaluation of an
7734 //    immediate invocation.
7735 // plus an offset in bytes.
7736 //===----------------------------------------------------------------------===//
7737 namespace {
7738 class LValueExprEvaluator
7739   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
7740 public:
7741   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
7742     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
7743 
7744   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
7745   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
7746 
7747   bool VisitDeclRefExpr(const DeclRefExpr *E);
7748   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
7749   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
7750   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
7751   bool VisitMemberExpr(const MemberExpr *E);
7752   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
7753   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
7754   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
7755   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
7756   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
7757   bool VisitUnaryDeref(const UnaryOperator *E);
7758   bool VisitUnaryReal(const UnaryOperator *E);
7759   bool VisitUnaryImag(const UnaryOperator *E);
7760   bool VisitUnaryPreInc(const UnaryOperator *UO) {
7761     return VisitUnaryPreIncDec(UO);
7762   }
7763   bool VisitUnaryPreDec(const UnaryOperator *UO) {
7764     return VisitUnaryPreIncDec(UO);
7765   }
7766   bool VisitBinAssign(const BinaryOperator *BO);
7767   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
7768 
7769   bool VisitCastExpr(const CastExpr *E) {
7770     switch (E->getCastKind()) {
7771     default:
7772       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
7773 
7774     case CK_LValueBitCast:
7775       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7776       if (!Visit(E->getSubExpr()))
7777         return false;
7778       Result.Designator.setInvalid();
7779       return true;
7780 
7781     case CK_BaseToDerived:
7782       if (!Visit(E->getSubExpr()))
7783         return false;
7784       return HandleBaseToDerivedCast(Info, E, Result);
7785 
7786     case CK_Dynamic:
7787       if (!Visit(E->getSubExpr()))
7788         return false;
7789       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
7790     }
7791   }
7792 };
7793 } // end anonymous namespace
7794 
7795 /// Evaluate an expression as an lvalue. This can be legitimately called on
7796 /// expressions which are not glvalues, in three cases:
7797 ///  * function designators in C, and
7798 ///  * "extern void" objects
7799 ///  * @selector() expressions in Objective-C
7800 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
7801                            bool InvalidBaseOK) {
7802   assert(E->isGLValue() || E->getType()->isFunctionType() ||
7803          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
7804   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
7805 }
7806 
7807 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
7808   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
7809     return Success(FD);
7810   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
7811     return VisitVarDecl(E, VD);
7812   if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
7813     return Visit(BD->getBinding());
7814   if (const MSGuidDecl *GD = dyn_cast<MSGuidDecl>(E->getDecl()))
7815     return Success(GD);
7816   return Error(E);
7817 }
7818 
7819 
7820 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
7821 
7822   // If we are within a lambda's call operator, check whether the 'VD' referred
7823   // to within 'E' actually represents a lambda-capture that maps to a
7824   // data-member/field within the closure object, and if so, evaluate to the
7825   // field or what the field refers to.
7826   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
7827       isa<DeclRefExpr>(E) &&
7828       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
7829     // We don't always have a complete capture-map when checking or inferring if
7830     // the function call operator meets the requirements of a constexpr function
7831     // - but we don't need to evaluate the captures to determine constexprness
7832     // (dcl.constexpr C++17).
7833     if (Info.checkingPotentialConstantExpression())
7834       return false;
7835 
7836     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
7837       // Start with 'Result' referring to the complete closure object...
7838       Result = *Info.CurrentCall->This;
7839       // ... then update it to refer to the field of the closure object
7840       // that represents the capture.
7841       if (!HandleLValueMember(Info, E, Result, FD))
7842         return false;
7843       // And if the field is of reference type, update 'Result' to refer to what
7844       // the field refers to.
7845       if (FD->getType()->isReferenceType()) {
7846         APValue RVal;
7847         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
7848                                             RVal))
7849           return false;
7850         Result.setFrom(Info.Ctx, RVal);
7851       }
7852       return true;
7853     }
7854   }
7855   CallStackFrame *Frame = nullptr;
7856   if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
7857     // Only if a local variable was declared in the function currently being
7858     // evaluated, do we expect to be able to find its value in the current
7859     // frame. (Otherwise it was likely declared in an enclosing context and
7860     // could either have a valid evaluatable value (for e.g. a constexpr
7861     // variable) or be ill-formed (and trigger an appropriate evaluation
7862     // diagnostic)).
7863     if (Info.CurrentCall->Callee &&
7864         Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
7865       Frame = Info.CurrentCall;
7866     }
7867   }
7868 
7869   if (!VD->getType()->isReferenceType()) {
7870     if (Frame) {
7871       Result.set({VD, Frame->Index,
7872                   Info.CurrentCall->getCurrentTemporaryVersion(VD)});
7873       return true;
7874     }
7875     return Success(VD);
7876   }
7877 
7878   APValue *V;
7879   if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
7880     return false;
7881   if (!V->hasValue()) {
7882     // FIXME: Is it possible for V to be indeterminate here? If so, we should
7883     // adjust the diagnostic to say that.
7884     if (!Info.checkingPotentialConstantExpression())
7885       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
7886     return false;
7887   }
7888   return Success(*V, E);
7889 }
7890 
7891 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
7892     const MaterializeTemporaryExpr *E) {
7893   // Walk through the expression to find the materialized temporary itself.
7894   SmallVector<const Expr *, 2> CommaLHSs;
7895   SmallVector<SubobjectAdjustment, 2> Adjustments;
7896   const Expr *Inner =
7897       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
7898 
7899   // If we passed any comma operators, evaluate their LHSs.
7900   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
7901     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
7902       return false;
7903 
7904   // A materialized temporary with static storage duration can appear within the
7905   // result of a constant expression evaluation, so we need to preserve its
7906   // value for use outside this evaluation.
7907   APValue *Value;
7908   if (E->getStorageDuration() == SD_Static) {
7909     Value = E->getOrCreateValue(true);
7910     *Value = APValue();
7911     Result.set(E);
7912   } else {
7913     Value = &Info.CurrentCall->createTemporary(
7914         E, E->getType(), E->getStorageDuration() == SD_Automatic, Result);
7915   }
7916 
7917   QualType Type = Inner->getType();
7918 
7919   // Materialize the temporary itself.
7920   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
7921     *Value = APValue();
7922     return false;
7923   }
7924 
7925   // Adjust our lvalue to refer to the desired subobject.
7926   for (unsigned I = Adjustments.size(); I != 0; /**/) {
7927     --I;
7928     switch (Adjustments[I].Kind) {
7929     case SubobjectAdjustment::DerivedToBaseAdjustment:
7930       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
7931                                 Type, Result))
7932         return false;
7933       Type = Adjustments[I].DerivedToBase.BasePath->getType();
7934       break;
7935 
7936     case SubobjectAdjustment::FieldAdjustment:
7937       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
7938         return false;
7939       Type = Adjustments[I].Field->getType();
7940       break;
7941 
7942     case SubobjectAdjustment::MemberPointerAdjustment:
7943       if (!HandleMemberPointerAccess(this->Info, Type, Result,
7944                                      Adjustments[I].Ptr.RHS))
7945         return false;
7946       Type = Adjustments[I].Ptr.MPT->getPointeeType();
7947       break;
7948     }
7949   }
7950 
7951   return true;
7952 }
7953 
7954 bool
7955 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7956   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
7957          "lvalue compound literal in c++?");
7958   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
7959   // only see this when folding in C, so there's no standard to follow here.
7960   return Success(E);
7961 }
7962 
7963 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
7964   TypeInfoLValue TypeInfo;
7965 
7966   if (!E->isPotentiallyEvaluated()) {
7967     if (E->isTypeOperand())
7968       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
7969     else
7970       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
7971   } else {
7972     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
7973       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
7974         << E->getExprOperand()->getType()
7975         << E->getExprOperand()->getSourceRange();
7976     }
7977 
7978     if (!Visit(E->getExprOperand()))
7979       return false;
7980 
7981     Optional<DynamicType> DynType =
7982         ComputeDynamicType(Info, E, Result, AK_TypeId);
7983     if (!DynType)
7984       return false;
7985 
7986     TypeInfo =
7987         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
7988   }
7989 
7990   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
7991 }
7992 
7993 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
7994   return Success(E->getGuidDecl());
7995 }
7996 
7997 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
7998   // Handle static data members.
7999   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8000     VisitIgnoredBaseExpression(E->getBase());
8001     return VisitVarDecl(E, VD);
8002   }
8003 
8004   // Handle static member functions.
8005   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8006     if (MD->isStatic()) {
8007       VisitIgnoredBaseExpression(E->getBase());
8008       return Success(MD);
8009     }
8010   }
8011 
8012   // Handle non-static data members.
8013   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8014 }
8015 
8016 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8017   // FIXME: Deal with vectors as array subscript bases.
8018   if (E->getBase()->getType()->isVectorType())
8019     return Error(E);
8020 
8021   bool Success = true;
8022   if (!evaluatePointer(E->getBase(), Result)) {
8023     if (!Info.noteFailure())
8024       return false;
8025     Success = false;
8026   }
8027 
8028   APSInt Index;
8029   if (!EvaluateInteger(E->getIdx(), Index, Info))
8030     return false;
8031 
8032   return Success &&
8033          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8034 }
8035 
8036 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8037   return evaluatePointer(E->getSubExpr(), Result);
8038 }
8039 
8040 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8041   if (!Visit(E->getSubExpr()))
8042     return false;
8043   // __real is a no-op on scalar lvalues.
8044   if (E->getSubExpr()->getType()->isAnyComplexType())
8045     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8046   return true;
8047 }
8048 
8049 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8050   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8051          "lvalue __imag__ on scalar?");
8052   if (!Visit(E->getSubExpr()))
8053     return false;
8054   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8055   return true;
8056 }
8057 
8058 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8059   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8060     return Error(UO);
8061 
8062   if (!this->Visit(UO->getSubExpr()))
8063     return false;
8064 
8065   return handleIncDec(
8066       this->Info, UO, Result, UO->getSubExpr()->getType(),
8067       UO->isIncrementOp(), nullptr);
8068 }
8069 
8070 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8071     const CompoundAssignOperator *CAO) {
8072   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8073     return Error(CAO);
8074 
8075   APValue RHS;
8076 
8077   // The overall lvalue result is the result of evaluating the LHS.
8078   if (!this->Visit(CAO->getLHS())) {
8079     if (Info.noteFailure())
8080       Evaluate(RHS, this->Info, CAO->getRHS());
8081     return false;
8082   }
8083 
8084   if (!Evaluate(RHS, this->Info, CAO->getRHS()))
8085     return false;
8086 
8087   return handleCompoundAssignment(
8088       this->Info, CAO,
8089       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8090       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8091 }
8092 
8093 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8094   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8095     return Error(E);
8096 
8097   APValue NewVal;
8098 
8099   if (!this->Visit(E->getLHS())) {
8100     if (Info.noteFailure())
8101       Evaluate(NewVal, this->Info, E->getRHS());
8102     return false;
8103   }
8104 
8105   if (!Evaluate(NewVal, this->Info, E->getRHS()))
8106     return false;
8107 
8108   if (Info.getLangOpts().CPlusPlus20 &&
8109       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8110     return false;
8111 
8112   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8113                           NewVal);
8114 }
8115 
8116 //===----------------------------------------------------------------------===//
8117 // Pointer Evaluation
8118 //===----------------------------------------------------------------------===//
8119 
8120 /// Attempts to compute the number of bytes available at the pointer
8121 /// returned by a function with the alloc_size attribute. Returns true if we
8122 /// were successful. Places an unsigned number into `Result`.
8123 ///
8124 /// This expects the given CallExpr to be a call to a function with an
8125 /// alloc_size attribute.
8126 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8127                                             const CallExpr *Call,
8128                                             llvm::APInt &Result) {
8129   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8130 
8131   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8132   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8133   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8134   if (Call->getNumArgs() <= SizeArgNo)
8135     return false;
8136 
8137   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8138     Expr::EvalResult ExprResult;
8139     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8140       return false;
8141     Into = ExprResult.Val.getInt();
8142     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8143       return false;
8144     Into = Into.zextOrSelf(BitsInSizeT);
8145     return true;
8146   };
8147 
8148   APSInt SizeOfElem;
8149   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8150     return false;
8151 
8152   if (!AllocSize->getNumElemsParam().isValid()) {
8153     Result = std::move(SizeOfElem);
8154     return true;
8155   }
8156 
8157   APSInt NumberOfElems;
8158   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8159   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8160     return false;
8161 
8162   bool Overflow;
8163   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8164   if (Overflow)
8165     return false;
8166 
8167   Result = std::move(BytesAvailable);
8168   return true;
8169 }
8170 
8171 /// Convenience function. LVal's base must be a call to an alloc_size
8172 /// function.
8173 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8174                                             const LValue &LVal,
8175                                             llvm::APInt &Result) {
8176   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8177          "Can't get the size of a non alloc_size function");
8178   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8179   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8180   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8181 }
8182 
8183 /// Attempts to evaluate the given LValueBase as the result of a call to
8184 /// a function with the alloc_size attribute. If it was possible to do so, this
8185 /// function will return true, make Result's Base point to said function call,
8186 /// and mark Result's Base as invalid.
8187 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8188                                       LValue &Result) {
8189   if (Base.isNull())
8190     return false;
8191 
8192   // Because we do no form of static analysis, we only support const variables.
8193   //
8194   // Additionally, we can't support parameters, nor can we support static
8195   // variables (in the latter case, use-before-assign isn't UB; in the former,
8196   // we have no clue what they'll be assigned to).
8197   const auto *VD =
8198       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8199   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8200     return false;
8201 
8202   const Expr *Init = VD->getAnyInitializer();
8203   if (!Init)
8204     return false;
8205 
8206   const Expr *E = Init->IgnoreParens();
8207   if (!tryUnwrapAllocSizeCall(E))
8208     return false;
8209 
8210   // Store E instead of E unwrapped so that the type of the LValue's base is
8211   // what the user wanted.
8212   Result.setInvalid(E);
8213 
8214   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8215   Result.addUnsizedArray(Info, E, Pointee);
8216   return true;
8217 }
8218 
8219 namespace {
8220 class PointerExprEvaluator
8221   : public ExprEvaluatorBase<PointerExprEvaluator> {
8222   LValue &Result;
8223   bool InvalidBaseOK;
8224 
8225   bool Success(const Expr *E) {
8226     Result.set(E);
8227     return true;
8228   }
8229 
8230   bool evaluateLValue(const Expr *E, LValue &Result) {
8231     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8232   }
8233 
8234   bool evaluatePointer(const Expr *E, LValue &Result) {
8235     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8236   }
8237 
8238   bool visitNonBuiltinCallExpr(const CallExpr *E);
8239 public:
8240 
8241   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8242       : ExprEvaluatorBaseTy(info), Result(Result),
8243         InvalidBaseOK(InvalidBaseOK) {}
8244 
8245   bool Success(const APValue &V, const Expr *E) {
8246     Result.setFrom(Info.Ctx, V);
8247     return true;
8248   }
8249   bool ZeroInitialization(const Expr *E) {
8250     Result.setNull(Info.Ctx, E->getType());
8251     return true;
8252   }
8253 
8254   bool VisitBinaryOperator(const BinaryOperator *E);
8255   bool VisitCastExpr(const CastExpr* E);
8256   bool VisitUnaryAddrOf(const UnaryOperator *E);
8257   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8258       { return Success(E); }
8259   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8260     if (E->isExpressibleAsConstantInitializer())
8261       return Success(E);
8262     if (Info.noteFailure())
8263       EvaluateIgnoredValue(Info, E->getSubExpr());
8264     return Error(E);
8265   }
8266   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8267       { return Success(E); }
8268   bool VisitCallExpr(const CallExpr *E);
8269   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8270   bool VisitBlockExpr(const BlockExpr *E) {
8271     if (!E->getBlockDecl()->hasCaptures())
8272       return Success(E);
8273     return Error(E);
8274   }
8275   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8276     // Can't look at 'this' when checking a potential constant expression.
8277     if (Info.checkingPotentialConstantExpression())
8278       return false;
8279     if (!Info.CurrentCall->This) {
8280       if (Info.getLangOpts().CPlusPlus11)
8281         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8282       else
8283         Info.FFDiag(E);
8284       return false;
8285     }
8286     Result = *Info.CurrentCall->This;
8287     // If we are inside a lambda's call operator, the 'this' expression refers
8288     // to the enclosing '*this' object (either by value or reference) which is
8289     // either copied into the closure object's field that represents the '*this'
8290     // or refers to '*this'.
8291     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8292       // Ensure we actually have captured 'this'. (an error will have
8293       // been previously reported if not).
8294       if (!Info.CurrentCall->LambdaThisCaptureField)
8295         return false;
8296 
8297       // Update 'Result' to refer to the data member/field of the closure object
8298       // that represents the '*this' capture.
8299       if (!HandleLValueMember(Info, E, Result,
8300                              Info.CurrentCall->LambdaThisCaptureField))
8301         return false;
8302       // If we captured '*this' by reference, replace the field with its referent.
8303       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8304               ->isPointerType()) {
8305         APValue RVal;
8306         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8307                                             RVal))
8308           return false;
8309 
8310         Result.setFrom(Info.Ctx, RVal);
8311       }
8312     }
8313     return true;
8314   }
8315 
8316   bool VisitCXXNewExpr(const CXXNewExpr *E);
8317 
8318   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8319     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
8320     APValue LValResult = E->EvaluateInContext(
8321         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8322     Result.setFrom(Info.Ctx, LValResult);
8323     return true;
8324   }
8325 
8326   // FIXME: Missing: @protocol, @selector
8327 };
8328 } // end anonymous namespace
8329 
8330 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8331                             bool InvalidBaseOK) {
8332   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
8333   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8334 }
8335 
8336 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8337   if (E->getOpcode() != BO_Add &&
8338       E->getOpcode() != BO_Sub)
8339     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8340 
8341   const Expr *PExp = E->getLHS();
8342   const Expr *IExp = E->getRHS();
8343   if (IExp->getType()->isPointerType())
8344     std::swap(PExp, IExp);
8345 
8346   bool EvalPtrOK = evaluatePointer(PExp, Result);
8347   if (!EvalPtrOK && !Info.noteFailure())
8348     return false;
8349 
8350   llvm::APSInt Offset;
8351   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8352     return false;
8353 
8354   if (E->getOpcode() == BO_Sub)
8355     negateAsSigned(Offset);
8356 
8357   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8358   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8359 }
8360 
8361 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8362   return evaluateLValue(E->getSubExpr(), Result);
8363 }
8364 
8365 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8366   const Expr *SubExpr = E->getSubExpr();
8367 
8368   switch (E->getCastKind()) {
8369   default:
8370     break;
8371   case CK_BitCast:
8372   case CK_CPointerToObjCPointerCast:
8373   case CK_BlockPointerToObjCPointerCast:
8374   case CK_AnyPointerToBlockPointerCast:
8375   case CK_AddressSpaceConversion:
8376     if (!Visit(SubExpr))
8377       return false;
8378     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8379     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8380     // also static_casts, but we disallow them as a resolution to DR1312.
8381     if (!E->getType()->isVoidPointerType()) {
8382       if (!Result.InvalidBase && !Result.Designator.Invalid &&
8383           !Result.IsNullPtr &&
8384           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8385                                           E->getType()->getPointeeType()) &&
8386           Info.getStdAllocatorCaller("allocate")) {
8387         // Inside a call to std::allocator::allocate and friends, we permit
8388         // casting from void* back to cv1 T* for a pointer that points to a
8389         // cv2 T.
8390       } else {
8391         Result.Designator.setInvalid();
8392         if (SubExpr->getType()->isVoidPointerType())
8393           CCEDiag(E, diag::note_constexpr_invalid_cast)
8394             << 3 << SubExpr->getType();
8395         else
8396           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8397       }
8398     }
8399     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8400       ZeroInitialization(E);
8401     return true;
8402 
8403   case CK_DerivedToBase:
8404   case CK_UncheckedDerivedToBase:
8405     if (!evaluatePointer(E->getSubExpr(), Result))
8406       return false;
8407     if (!Result.Base && Result.Offset.isZero())
8408       return true;
8409 
8410     // Now figure out the necessary offset to add to the base LV to get from
8411     // the derived class to the base class.
8412     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8413                                   castAs<PointerType>()->getPointeeType(),
8414                                 Result);
8415 
8416   case CK_BaseToDerived:
8417     if (!Visit(E->getSubExpr()))
8418       return false;
8419     if (!Result.Base && Result.Offset.isZero())
8420       return true;
8421     return HandleBaseToDerivedCast(Info, E, Result);
8422 
8423   case CK_Dynamic:
8424     if (!Visit(E->getSubExpr()))
8425       return false;
8426     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8427 
8428   case CK_NullToPointer:
8429     VisitIgnoredValue(E->getSubExpr());
8430     return ZeroInitialization(E);
8431 
8432   case CK_IntegralToPointer: {
8433     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8434 
8435     APValue Value;
8436     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8437       break;
8438 
8439     if (Value.isInt()) {
8440       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8441       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8442       Result.Base = (Expr*)nullptr;
8443       Result.InvalidBase = false;
8444       Result.Offset = CharUnits::fromQuantity(N);
8445       Result.Designator.setInvalid();
8446       Result.IsNullPtr = false;
8447       return true;
8448     } else {
8449       // Cast is of an lvalue, no need to change value.
8450       Result.setFrom(Info.Ctx, Value);
8451       return true;
8452     }
8453   }
8454 
8455   case CK_ArrayToPointerDecay: {
8456     if (SubExpr->isGLValue()) {
8457       if (!evaluateLValue(SubExpr, Result))
8458         return false;
8459     } else {
8460       APValue &Value = Info.CurrentCall->createTemporary(
8461           SubExpr, SubExpr->getType(), false, Result);
8462       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8463         return false;
8464     }
8465     // The result is a pointer to the first element of the array.
8466     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8467     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8468       Result.addArray(Info, E, CAT);
8469     else
8470       Result.addUnsizedArray(Info, E, AT->getElementType());
8471     return true;
8472   }
8473 
8474   case CK_FunctionToPointerDecay:
8475     return evaluateLValue(SubExpr, Result);
8476 
8477   case CK_LValueToRValue: {
8478     LValue LVal;
8479     if (!evaluateLValue(E->getSubExpr(), LVal))
8480       return false;
8481 
8482     APValue RVal;
8483     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8484     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8485                                         LVal, RVal))
8486       return InvalidBaseOK &&
8487              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8488     return Success(RVal, E);
8489   }
8490   }
8491 
8492   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8493 }
8494 
8495 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8496                                 UnaryExprOrTypeTrait ExprKind) {
8497   // C++ [expr.alignof]p3:
8498   //     When alignof is applied to a reference type, the result is the
8499   //     alignment of the referenced type.
8500   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8501     T = Ref->getPointeeType();
8502 
8503   if (T.getQualifiers().hasUnaligned())
8504     return CharUnits::One();
8505 
8506   const bool AlignOfReturnsPreferred =
8507       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8508 
8509   // __alignof is defined to return the preferred alignment.
8510   // Before 8, clang returned the preferred alignment for alignof and _Alignof
8511   // as well.
8512   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8513     return Info.Ctx.toCharUnitsFromBits(
8514       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8515   // alignof and _Alignof are defined to return the ABI alignment.
8516   else if (ExprKind == UETT_AlignOf)
8517     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8518   else
8519     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8520 }
8521 
8522 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8523                                 UnaryExprOrTypeTrait ExprKind) {
8524   E = E->IgnoreParens();
8525 
8526   // The kinds of expressions that we have special-case logic here for
8527   // should be kept up to date with the special checks for those
8528   // expressions in Sema.
8529 
8530   // alignof decl is always accepted, even if it doesn't make sense: we default
8531   // to 1 in those cases.
8532   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8533     return Info.Ctx.getDeclAlign(DRE->getDecl(),
8534                                  /*RefAsPointee*/true);
8535 
8536   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8537     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8538                                  /*RefAsPointee*/true);
8539 
8540   return GetAlignOfType(Info, E->getType(), ExprKind);
8541 }
8542 
8543 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
8544   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
8545     return Info.Ctx.getDeclAlign(VD);
8546   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
8547     return GetAlignOfExpr(Info, E, UETT_AlignOf);
8548   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
8549 }
8550 
8551 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
8552 /// __builtin_is_aligned and __builtin_assume_aligned.
8553 static bool getAlignmentArgument(const Expr *E, QualType ForType,
8554                                  EvalInfo &Info, APSInt &Alignment) {
8555   if (!EvaluateInteger(E, Alignment, Info))
8556     return false;
8557   if (Alignment < 0 || !Alignment.isPowerOf2()) {
8558     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
8559     return false;
8560   }
8561   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
8562   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
8563   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
8564     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
8565         << MaxValue << ForType << Alignment;
8566     return false;
8567   }
8568   // Ensure both alignment and source value have the same bit width so that we
8569   // don't assert when computing the resulting value.
8570   APSInt ExtAlignment =
8571       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
8572   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
8573          "Alignment should not be changed by ext/trunc");
8574   Alignment = ExtAlignment;
8575   assert(Alignment.getBitWidth() == SrcWidth);
8576   return true;
8577 }
8578 
8579 // To be clear: this happily visits unsupported builtins. Better name welcomed.
8580 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8581   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8582     return true;
8583 
8584   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
8585     return false;
8586 
8587   Result.setInvalid(E);
8588   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
8589   Result.addUnsizedArray(Info, E, PointeeTy);
8590   return true;
8591 }
8592 
8593 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
8594   if (IsStringLiteralCall(E))
8595     return Success(E);
8596 
8597   if (unsigned BuiltinOp = E->getBuiltinCallee())
8598     return VisitBuiltinCallExpr(E, BuiltinOp);
8599 
8600   return visitNonBuiltinCallExpr(E);
8601 }
8602 
8603 // Determine if T is a character type for which we guarantee that
8604 // sizeof(T) == 1.
8605 static bool isOneByteCharacterType(QualType T) {
8606   return T->isCharType() || T->isChar8Type();
8607 }
8608 
8609 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8610                                                 unsigned BuiltinOp) {
8611   switch (BuiltinOp) {
8612   case Builtin::BI__builtin_addressof:
8613     return evaluateLValue(E->getArg(0), Result);
8614   case Builtin::BI__builtin_assume_aligned: {
8615     // We need to be very careful here because: if the pointer does not have the
8616     // asserted alignment, then the behavior is undefined, and undefined
8617     // behavior is non-constant.
8618     if (!evaluatePointer(E->getArg(0), Result))
8619       return false;
8620 
8621     LValue OffsetResult(Result);
8622     APSInt Alignment;
8623     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8624                               Alignment))
8625       return false;
8626     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
8627 
8628     if (E->getNumArgs() > 2) {
8629       APSInt Offset;
8630       if (!EvaluateInteger(E->getArg(2), Offset, Info))
8631         return false;
8632 
8633       int64_t AdditionalOffset = -Offset.getZExtValue();
8634       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
8635     }
8636 
8637     // If there is a base object, then it must have the correct alignment.
8638     if (OffsetResult.Base) {
8639       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
8640 
8641       if (BaseAlignment < Align) {
8642         Result.Designator.setInvalid();
8643         // FIXME: Add support to Diagnostic for long / long long.
8644         CCEDiag(E->getArg(0),
8645                 diag::note_constexpr_baa_insufficient_alignment) << 0
8646           << (unsigned)BaseAlignment.getQuantity()
8647           << (unsigned)Align.getQuantity();
8648         return false;
8649       }
8650     }
8651 
8652     // The offset must also have the correct alignment.
8653     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
8654       Result.Designator.setInvalid();
8655 
8656       (OffsetResult.Base
8657            ? CCEDiag(E->getArg(0),
8658                      diag::note_constexpr_baa_insufficient_alignment) << 1
8659            : CCEDiag(E->getArg(0),
8660                      diag::note_constexpr_baa_value_insufficient_alignment))
8661         << (int)OffsetResult.Offset.getQuantity()
8662         << (unsigned)Align.getQuantity();
8663       return false;
8664     }
8665 
8666     return true;
8667   }
8668   case Builtin::BI__builtin_align_up:
8669   case Builtin::BI__builtin_align_down: {
8670     if (!evaluatePointer(E->getArg(0), Result))
8671       return false;
8672     APSInt Alignment;
8673     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8674                               Alignment))
8675       return false;
8676     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
8677     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
8678     // For align_up/align_down, we can return the same value if the alignment
8679     // is known to be greater or equal to the requested value.
8680     if (PtrAlign.getQuantity() >= Alignment)
8681       return true;
8682 
8683     // The alignment could be greater than the minimum at run-time, so we cannot
8684     // infer much about the resulting pointer value. One case is possible:
8685     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
8686     // can infer the correct index if the requested alignment is smaller than
8687     // the base alignment so we can perform the computation on the offset.
8688     if (BaseAlignment.getQuantity() >= Alignment) {
8689       assert(Alignment.getBitWidth() <= 64 &&
8690              "Cannot handle > 64-bit address-space");
8691       uint64_t Alignment64 = Alignment.getZExtValue();
8692       CharUnits NewOffset = CharUnits::fromQuantity(
8693           BuiltinOp == Builtin::BI__builtin_align_down
8694               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
8695               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
8696       Result.adjustOffset(NewOffset - Result.Offset);
8697       // TODO: diagnose out-of-bounds values/only allow for arrays?
8698       return true;
8699     }
8700     // Otherwise, we cannot constant-evaluate the result.
8701     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
8702         << Alignment;
8703     return false;
8704   }
8705   case Builtin::BI__builtin_operator_new:
8706     return HandleOperatorNewCall(Info, E, Result);
8707   case Builtin::BI__builtin_launder:
8708     return evaluatePointer(E->getArg(0), Result);
8709   case Builtin::BIstrchr:
8710   case Builtin::BIwcschr:
8711   case Builtin::BImemchr:
8712   case Builtin::BIwmemchr:
8713     if (Info.getLangOpts().CPlusPlus11)
8714       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8715         << /*isConstexpr*/0 << /*isConstructor*/0
8716         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8717     else
8718       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8719     LLVM_FALLTHROUGH;
8720   case Builtin::BI__builtin_strchr:
8721   case Builtin::BI__builtin_wcschr:
8722   case Builtin::BI__builtin_memchr:
8723   case Builtin::BI__builtin_char_memchr:
8724   case Builtin::BI__builtin_wmemchr: {
8725     if (!Visit(E->getArg(0)))
8726       return false;
8727     APSInt Desired;
8728     if (!EvaluateInteger(E->getArg(1), Desired, Info))
8729       return false;
8730     uint64_t MaxLength = uint64_t(-1);
8731     if (BuiltinOp != Builtin::BIstrchr &&
8732         BuiltinOp != Builtin::BIwcschr &&
8733         BuiltinOp != Builtin::BI__builtin_strchr &&
8734         BuiltinOp != Builtin::BI__builtin_wcschr) {
8735       APSInt N;
8736       if (!EvaluateInteger(E->getArg(2), N, Info))
8737         return false;
8738       MaxLength = N.getExtValue();
8739     }
8740     // We cannot find the value if there are no candidates to match against.
8741     if (MaxLength == 0u)
8742       return ZeroInitialization(E);
8743     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8744         Result.Designator.Invalid)
8745       return false;
8746     QualType CharTy = Result.Designator.getType(Info.Ctx);
8747     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
8748                      BuiltinOp == Builtin::BI__builtin_memchr;
8749     assert(IsRawByte ||
8750            Info.Ctx.hasSameUnqualifiedType(
8751                CharTy, E->getArg(0)->getType()->getPointeeType()));
8752     // Pointers to const void may point to objects of incomplete type.
8753     if (IsRawByte && CharTy->isIncompleteType()) {
8754       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
8755       return false;
8756     }
8757     // Give up on byte-oriented matching against multibyte elements.
8758     // FIXME: We can compare the bytes in the correct order.
8759     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
8760       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
8761           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
8762           << CharTy;
8763       return false;
8764     }
8765     // Figure out what value we're actually looking for (after converting to
8766     // the corresponding unsigned type if necessary).
8767     uint64_t DesiredVal;
8768     bool StopAtNull = false;
8769     switch (BuiltinOp) {
8770     case Builtin::BIstrchr:
8771     case Builtin::BI__builtin_strchr:
8772       // strchr compares directly to the passed integer, and therefore
8773       // always fails if given an int that is not a char.
8774       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
8775                                                   E->getArg(1)->getType(),
8776                                                   Desired),
8777                                Desired))
8778         return ZeroInitialization(E);
8779       StopAtNull = true;
8780       LLVM_FALLTHROUGH;
8781     case Builtin::BImemchr:
8782     case Builtin::BI__builtin_memchr:
8783     case Builtin::BI__builtin_char_memchr:
8784       // memchr compares by converting both sides to unsigned char. That's also
8785       // correct for strchr if we get this far (to cope with plain char being
8786       // unsigned in the strchr case).
8787       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
8788       break;
8789 
8790     case Builtin::BIwcschr:
8791     case Builtin::BI__builtin_wcschr:
8792       StopAtNull = true;
8793       LLVM_FALLTHROUGH;
8794     case Builtin::BIwmemchr:
8795     case Builtin::BI__builtin_wmemchr:
8796       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
8797       DesiredVal = Desired.getZExtValue();
8798       break;
8799     }
8800 
8801     for (; MaxLength; --MaxLength) {
8802       APValue Char;
8803       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
8804           !Char.isInt())
8805         return false;
8806       if (Char.getInt().getZExtValue() == DesiredVal)
8807         return true;
8808       if (StopAtNull && !Char.getInt())
8809         break;
8810       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
8811         return false;
8812     }
8813     // Not found: return nullptr.
8814     return ZeroInitialization(E);
8815   }
8816 
8817   case Builtin::BImemcpy:
8818   case Builtin::BImemmove:
8819   case Builtin::BIwmemcpy:
8820   case Builtin::BIwmemmove:
8821     if (Info.getLangOpts().CPlusPlus11)
8822       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8823         << /*isConstexpr*/0 << /*isConstructor*/0
8824         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8825     else
8826       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8827     LLVM_FALLTHROUGH;
8828   case Builtin::BI__builtin_memcpy:
8829   case Builtin::BI__builtin_memmove:
8830   case Builtin::BI__builtin_wmemcpy:
8831   case Builtin::BI__builtin_wmemmove: {
8832     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
8833                  BuiltinOp == Builtin::BIwmemmove ||
8834                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
8835                  BuiltinOp == Builtin::BI__builtin_wmemmove;
8836     bool Move = BuiltinOp == Builtin::BImemmove ||
8837                 BuiltinOp == Builtin::BIwmemmove ||
8838                 BuiltinOp == Builtin::BI__builtin_memmove ||
8839                 BuiltinOp == Builtin::BI__builtin_wmemmove;
8840 
8841     // The result of mem* is the first argument.
8842     if (!Visit(E->getArg(0)))
8843       return false;
8844     LValue Dest = Result;
8845 
8846     LValue Src;
8847     if (!EvaluatePointer(E->getArg(1), Src, Info))
8848       return false;
8849 
8850     APSInt N;
8851     if (!EvaluateInteger(E->getArg(2), N, Info))
8852       return false;
8853     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
8854 
8855     // If the size is zero, we treat this as always being a valid no-op.
8856     // (Even if one of the src and dest pointers is null.)
8857     if (!N)
8858       return true;
8859 
8860     // Otherwise, if either of the operands is null, we can't proceed. Don't
8861     // try to determine the type of the copied objects, because there aren't
8862     // any.
8863     if (!Src.Base || !Dest.Base) {
8864       APValue Val;
8865       (!Src.Base ? Src : Dest).moveInto(Val);
8866       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
8867           << Move << WChar << !!Src.Base
8868           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
8869       return false;
8870     }
8871     if (Src.Designator.Invalid || Dest.Designator.Invalid)
8872       return false;
8873 
8874     // We require that Src and Dest are both pointers to arrays of
8875     // trivially-copyable type. (For the wide version, the designator will be
8876     // invalid if the designated object is not a wchar_t.)
8877     QualType T = Dest.Designator.getType(Info.Ctx);
8878     QualType SrcT = Src.Designator.getType(Info.Ctx);
8879     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
8880       // FIXME: Consider using our bit_cast implementation to support this.
8881       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
8882       return false;
8883     }
8884     if (T->isIncompleteType()) {
8885       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
8886       return false;
8887     }
8888     if (!T.isTriviallyCopyableType(Info.Ctx)) {
8889       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
8890       return false;
8891     }
8892 
8893     // Figure out how many T's we're copying.
8894     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
8895     if (!WChar) {
8896       uint64_t Remainder;
8897       llvm::APInt OrigN = N;
8898       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
8899       if (Remainder) {
8900         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8901             << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
8902             << (unsigned)TSize;
8903         return false;
8904       }
8905     }
8906 
8907     // Check that the copying will remain within the arrays, just so that we
8908     // can give a more meaningful diagnostic. This implicitly also checks that
8909     // N fits into 64 bits.
8910     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
8911     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
8912     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
8913       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8914           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
8915           << N.toString(10, /*Signed*/false);
8916       return false;
8917     }
8918     uint64_t NElems = N.getZExtValue();
8919     uint64_t NBytes = NElems * TSize;
8920 
8921     // Check for overlap.
8922     int Direction = 1;
8923     if (HasSameBase(Src, Dest)) {
8924       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
8925       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
8926       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
8927         // Dest is inside the source region.
8928         if (!Move) {
8929           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8930           return false;
8931         }
8932         // For memmove and friends, copy backwards.
8933         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
8934             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
8935           return false;
8936         Direction = -1;
8937       } else if (!Move && SrcOffset >= DestOffset &&
8938                  SrcOffset - DestOffset < NBytes) {
8939         // Src is inside the destination region for memcpy: invalid.
8940         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8941         return false;
8942       }
8943     }
8944 
8945     while (true) {
8946       APValue Val;
8947       // FIXME: Set WantObjectRepresentation to true if we're copying a
8948       // char-like type?
8949       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
8950           !handleAssignment(Info, E, Dest, T, Val))
8951         return false;
8952       // Do not iterate past the last element; if we're copying backwards, that
8953       // might take us off the start of the array.
8954       if (--NElems == 0)
8955         return true;
8956       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
8957           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
8958         return false;
8959     }
8960   }
8961 
8962   default:
8963     break;
8964   }
8965 
8966   return visitNonBuiltinCallExpr(E);
8967 }
8968 
8969 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
8970                                      APValue &Result, const InitListExpr *ILE,
8971                                      QualType AllocType);
8972 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
8973                                           APValue &Result,
8974                                           const CXXConstructExpr *CCE,
8975                                           QualType AllocType);
8976 
8977 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
8978   if (!Info.getLangOpts().CPlusPlus20)
8979     Info.CCEDiag(E, diag::note_constexpr_new);
8980 
8981   // We cannot speculatively evaluate a delete expression.
8982   if (Info.SpeculativeEvaluationDepth)
8983     return false;
8984 
8985   FunctionDecl *OperatorNew = E->getOperatorNew();
8986 
8987   bool IsNothrow = false;
8988   bool IsPlacement = false;
8989   if (OperatorNew->isReservedGlobalPlacementOperator() &&
8990       Info.CurrentCall->isStdFunction() && !E->isArray()) {
8991     // FIXME Support array placement new.
8992     assert(E->getNumPlacementArgs() == 1);
8993     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
8994       return false;
8995     if (Result.Designator.Invalid)
8996       return false;
8997     IsPlacement = true;
8998   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
8999     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9000         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9001     return false;
9002   } else if (E->getNumPlacementArgs()) {
9003     // The only new-placement list we support is of the form (std::nothrow).
9004     //
9005     // FIXME: There is no restriction on this, but it's not clear that any
9006     // other form makes any sense. We get here for cases such as:
9007     //
9008     //   new (std::align_val_t{N}) X(int)
9009     //
9010     // (which should presumably be valid only if N is a multiple of
9011     // alignof(int), and in any case can't be deallocated unless N is
9012     // alignof(X) and X has new-extended alignment).
9013     if (E->getNumPlacementArgs() != 1 ||
9014         !E->getPlacementArg(0)->getType()->isNothrowT())
9015       return Error(E, diag::note_constexpr_new_placement);
9016 
9017     LValue Nothrow;
9018     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9019       return false;
9020     IsNothrow = true;
9021   }
9022 
9023   const Expr *Init = E->getInitializer();
9024   const InitListExpr *ResizedArrayILE = nullptr;
9025   const CXXConstructExpr *ResizedArrayCCE = nullptr;
9026   bool ValueInit = false;
9027 
9028   QualType AllocType = E->getAllocatedType();
9029   if (Optional<const Expr*> ArraySize = E->getArraySize()) {
9030     const Expr *Stripped = *ArraySize;
9031     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9032          Stripped = ICE->getSubExpr())
9033       if (ICE->getCastKind() != CK_NoOp &&
9034           ICE->getCastKind() != CK_IntegralCast)
9035         break;
9036 
9037     llvm::APSInt ArrayBound;
9038     if (!EvaluateInteger(Stripped, ArrayBound, Info))
9039       return false;
9040 
9041     // C++ [expr.new]p9:
9042     //   The expression is erroneous if:
9043     //   -- [...] its value before converting to size_t [or] applying the
9044     //      second standard conversion sequence is less than zero
9045     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9046       if (IsNothrow)
9047         return ZeroInitialization(E);
9048 
9049       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9050           << ArrayBound << (*ArraySize)->getSourceRange();
9051       return false;
9052     }
9053 
9054     //   -- its value is such that the size of the allocated object would
9055     //      exceed the implementation-defined limit
9056     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9057                                                 ArrayBound) >
9058         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9059       if (IsNothrow)
9060         return ZeroInitialization(E);
9061 
9062       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9063         << ArrayBound << (*ArraySize)->getSourceRange();
9064       return false;
9065     }
9066 
9067     //   -- the new-initializer is a braced-init-list and the number of
9068     //      array elements for which initializers are provided [...]
9069     //      exceeds the number of elements to initialize
9070     if (!Init) {
9071       // No initialization is performed.
9072     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9073                isa<ImplicitValueInitExpr>(Init)) {
9074       ValueInit = true;
9075     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9076       ResizedArrayCCE = CCE;
9077     } else {
9078       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9079       assert(CAT && "unexpected type for array initializer");
9080 
9081       unsigned Bits =
9082           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9083       llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
9084       llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
9085       if (InitBound.ugt(AllocBound)) {
9086         if (IsNothrow)
9087           return ZeroInitialization(E);
9088 
9089         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9090             << AllocBound.toString(10, /*Signed=*/false)
9091             << InitBound.toString(10, /*Signed=*/false)
9092             << (*ArraySize)->getSourceRange();
9093         return false;
9094       }
9095 
9096       // If the sizes differ, we must have an initializer list, and we need
9097       // special handling for this case when we initialize.
9098       if (InitBound != AllocBound)
9099         ResizedArrayILE = cast<InitListExpr>(Init);
9100     }
9101 
9102     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9103                                               ArrayType::Normal, 0);
9104   } else {
9105     assert(!AllocType->isArrayType() &&
9106            "array allocation with non-array new");
9107   }
9108 
9109   APValue *Val;
9110   if (IsPlacement) {
9111     AccessKinds AK = AK_Construct;
9112     struct FindObjectHandler {
9113       EvalInfo &Info;
9114       const Expr *E;
9115       QualType AllocType;
9116       const AccessKinds AccessKind;
9117       APValue *Value;
9118 
9119       typedef bool result_type;
9120       bool failed() { return false; }
9121       bool found(APValue &Subobj, QualType SubobjType) {
9122         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9123         // old name of the object to be used to name the new object.
9124         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9125           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9126             SubobjType << AllocType;
9127           return false;
9128         }
9129         Value = &Subobj;
9130         return true;
9131       }
9132       bool found(APSInt &Value, QualType SubobjType) {
9133         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9134         return false;
9135       }
9136       bool found(APFloat &Value, QualType SubobjType) {
9137         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9138         return false;
9139       }
9140     } Handler = {Info, E, AllocType, AK, nullptr};
9141 
9142     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9143     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9144       return false;
9145 
9146     Val = Handler.Value;
9147 
9148     // [basic.life]p1:
9149     //   The lifetime of an object o of type T ends when [...] the storage
9150     //   which the object occupies is [...] reused by an object that is not
9151     //   nested within o (6.6.2).
9152     *Val = APValue();
9153   } else {
9154     // Perform the allocation and obtain a pointer to the resulting object.
9155     Val = Info.createHeapAlloc(E, AllocType, Result);
9156     if (!Val)
9157       return false;
9158   }
9159 
9160   if (ValueInit) {
9161     ImplicitValueInitExpr VIE(AllocType);
9162     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9163       return false;
9164   } else if (ResizedArrayILE) {
9165     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9166                                   AllocType))
9167       return false;
9168   } else if (ResizedArrayCCE) {
9169     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9170                                        AllocType))
9171       return false;
9172   } else if (Init) {
9173     if (!EvaluateInPlace(*Val, Info, Result, Init))
9174       return false;
9175   } else if (!getDefaultInitValue(AllocType, *Val)) {
9176     return false;
9177   }
9178 
9179   // Array new returns a pointer to the first element, not a pointer to the
9180   // array.
9181   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9182     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9183 
9184   return true;
9185 }
9186 //===----------------------------------------------------------------------===//
9187 // Member Pointer Evaluation
9188 //===----------------------------------------------------------------------===//
9189 
9190 namespace {
9191 class MemberPointerExprEvaluator
9192   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9193   MemberPtr &Result;
9194 
9195   bool Success(const ValueDecl *D) {
9196     Result = MemberPtr(D);
9197     return true;
9198   }
9199 public:
9200 
9201   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9202     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9203 
9204   bool Success(const APValue &V, const Expr *E) {
9205     Result.setFrom(V);
9206     return true;
9207   }
9208   bool ZeroInitialization(const Expr *E) {
9209     return Success((const ValueDecl*)nullptr);
9210   }
9211 
9212   bool VisitCastExpr(const CastExpr *E);
9213   bool VisitUnaryAddrOf(const UnaryOperator *E);
9214 };
9215 } // end anonymous namespace
9216 
9217 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9218                                   EvalInfo &Info) {
9219   assert(E->isRValue() && E->getType()->isMemberPointerType());
9220   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9221 }
9222 
9223 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9224   switch (E->getCastKind()) {
9225   default:
9226     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9227 
9228   case CK_NullToMemberPointer:
9229     VisitIgnoredValue(E->getSubExpr());
9230     return ZeroInitialization(E);
9231 
9232   case CK_BaseToDerivedMemberPointer: {
9233     if (!Visit(E->getSubExpr()))
9234       return false;
9235     if (E->path_empty())
9236       return true;
9237     // Base-to-derived member pointer casts store the path in derived-to-base
9238     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9239     // the wrong end of the derived->base arc, so stagger the path by one class.
9240     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9241     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9242          PathI != PathE; ++PathI) {
9243       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9244       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9245       if (!Result.castToDerived(Derived))
9246         return Error(E);
9247     }
9248     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9249     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9250       return Error(E);
9251     return true;
9252   }
9253 
9254   case CK_DerivedToBaseMemberPointer:
9255     if (!Visit(E->getSubExpr()))
9256       return false;
9257     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9258          PathE = E->path_end(); PathI != PathE; ++PathI) {
9259       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9260       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9261       if (!Result.castToBase(Base))
9262         return Error(E);
9263     }
9264     return true;
9265   }
9266 }
9267 
9268 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9269   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9270   // member can be formed.
9271   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9272 }
9273 
9274 //===----------------------------------------------------------------------===//
9275 // Record Evaluation
9276 //===----------------------------------------------------------------------===//
9277 
9278 namespace {
9279   class RecordExprEvaluator
9280   : public ExprEvaluatorBase<RecordExprEvaluator> {
9281     const LValue &This;
9282     APValue &Result;
9283   public:
9284 
9285     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9286       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9287 
9288     bool Success(const APValue &V, const Expr *E) {
9289       Result = V;
9290       return true;
9291     }
9292     bool ZeroInitialization(const Expr *E) {
9293       return ZeroInitialization(E, E->getType());
9294     }
9295     bool ZeroInitialization(const Expr *E, QualType T);
9296 
9297     bool VisitCallExpr(const CallExpr *E) {
9298       return handleCallExpr(E, Result, &This);
9299     }
9300     bool VisitCastExpr(const CastExpr *E);
9301     bool VisitInitListExpr(const InitListExpr *E);
9302     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9303       return VisitCXXConstructExpr(E, E->getType());
9304     }
9305     bool VisitLambdaExpr(const LambdaExpr *E);
9306     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9307     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9308     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9309     bool VisitBinCmp(const BinaryOperator *E);
9310   };
9311 }
9312 
9313 /// Perform zero-initialization on an object of non-union class type.
9314 /// C++11 [dcl.init]p5:
9315 ///  To zero-initialize an object or reference of type T means:
9316 ///    [...]
9317 ///    -- if T is a (possibly cv-qualified) non-union class type,
9318 ///       each non-static data member and each base-class subobject is
9319 ///       zero-initialized
9320 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9321                                           const RecordDecl *RD,
9322                                           const LValue &This, APValue &Result) {
9323   assert(!RD->isUnion() && "Expected non-union class type");
9324   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9325   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9326                    std::distance(RD->field_begin(), RD->field_end()));
9327 
9328   if (RD->isInvalidDecl()) return false;
9329   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9330 
9331   if (CD) {
9332     unsigned Index = 0;
9333     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9334            End = CD->bases_end(); I != End; ++I, ++Index) {
9335       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9336       LValue Subobject = This;
9337       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9338         return false;
9339       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9340                                          Result.getStructBase(Index)))
9341         return false;
9342     }
9343   }
9344 
9345   for (const auto *I : RD->fields()) {
9346     // -- if T is a reference type, no initialization is performed.
9347     if (I->getType()->isReferenceType())
9348       continue;
9349 
9350     LValue Subobject = This;
9351     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9352       return false;
9353 
9354     ImplicitValueInitExpr VIE(I->getType());
9355     if (!EvaluateInPlace(
9356           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9357       return false;
9358   }
9359 
9360   return true;
9361 }
9362 
9363 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9364   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9365   if (RD->isInvalidDecl()) return false;
9366   if (RD->isUnion()) {
9367     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9368     // object's first non-static named data member is zero-initialized
9369     RecordDecl::field_iterator I = RD->field_begin();
9370     if (I == RD->field_end()) {
9371       Result = APValue((const FieldDecl*)nullptr);
9372       return true;
9373     }
9374 
9375     LValue Subobject = This;
9376     if (!HandleLValueMember(Info, E, Subobject, *I))
9377       return false;
9378     Result = APValue(*I);
9379     ImplicitValueInitExpr VIE(I->getType());
9380     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9381   }
9382 
9383   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9384     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9385     return false;
9386   }
9387 
9388   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9389 }
9390 
9391 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9392   switch (E->getCastKind()) {
9393   default:
9394     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9395 
9396   case CK_ConstructorConversion:
9397     return Visit(E->getSubExpr());
9398 
9399   case CK_DerivedToBase:
9400   case CK_UncheckedDerivedToBase: {
9401     APValue DerivedObject;
9402     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9403       return false;
9404     if (!DerivedObject.isStruct())
9405       return Error(E->getSubExpr());
9406 
9407     // Derived-to-base rvalue conversion: just slice off the derived part.
9408     APValue *Value = &DerivedObject;
9409     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9410     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9411          PathE = E->path_end(); PathI != PathE; ++PathI) {
9412       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9413       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9414       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9415       RD = Base;
9416     }
9417     Result = *Value;
9418     return true;
9419   }
9420   }
9421 }
9422 
9423 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9424   if (E->isTransparent())
9425     return Visit(E->getInit(0));
9426 
9427   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9428   if (RD->isInvalidDecl()) return false;
9429   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9430   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9431 
9432   EvalInfo::EvaluatingConstructorRAII EvalObj(
9433       Info,
9434       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9435       CXXRD && CXXRD->getNumBases());
9436 
9437   if (RD->isUnion()) {
9438     const FieldDecl *Field = E->getInitializedFieldInUnion();
9439     Result = APValue(Field);
9440     if (!Field)
9441       return true;
9442 
9443     // If the initializer list for a union does not contain any elements, the
9444     // first element of the union is value-initialized.
9445     // FIXME: The element should be initialized from an initializer list.
9446     //        Is this difference ever observable for initializer lists which
9447     //        we don't build?
9448     ImplicitValueInitExpr VIE(Field->getType());
9449     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9450 
9451     LValue Subobject = This;
9452     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9453       return false;
9454 
9455     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9456     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9457                                   isa<CXXDefaultInitExpr>(InitExpr));
9458 
9459     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
9460   }
9461 
9462   if (!Result.hasValue())
9463     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9464                      std::distance(RD->field_begin(), RD->field_end()));
9465   unsigned ElementNo = 0;
9466   bool Success = true;
9467 
9468   // Initialize base classes.
9469   if (CXXRD && CXXRD->getNumBases()) {
9470     for (const auto &Base : CXXRD->bases()) {
9471       assert(ElementNo < E->getNumInits() && "missing init for base class");
9472       const Expr *Init = E->getInit(ElementNo);
9473 
9474       LValue Subobject = This;
9475       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9476         return false;
9477 
9478       APValue &FieldVal = Result.getStructBase(ElementNo);
9479       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9480         if (!Info.noteFailure())
9481           return false;
9482         Success = false;
9483       }
9484       ++ElementNo;
9485     }
9486 
9487     EvalObj.finishedConstructingBases();
9488   }
9489 
9490   // Initialize members.
9491   for (const auto *Field : RD->fields()) {
9492     // Anonymous bit-fields are not considered members of the class for
9493     // purposes of aggregate initialization.
9494     if (Field->isUnnamedBitfield())
9495       continue;
9496 
9497     LValue Subobject = This;
9498 
9499     bool HaveInit = ElementNo < E->getNumInits();
9500 
9501     // FIXME: Diagnostics here should point to the end of the initializer
9502     // list, not the start.
9503     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9504                             Subobject, Field, &Layout))
9505       return false;
9506 
9507     // Perform an implicit value-initialization for members beyond the end of
9508     // the initializer list.
9509     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9510     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9511 
9512     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9513     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9514                                   isa<CXXDefaultInitExpr>(Init));
9515 
9516     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9517     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9518         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9519                                                        FieldVal, Field))) {
9520       if (!Info.noteFailure())
9521         return false;
9522       Success = false;
9523     }
9524   }
9525 
9526   EvalObj.finishedConstructingFields();
9527 
9528   return Success;
9529 }
9530 
9531 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9532                                                 QualType T) {
9533   // Note that E's type is not necessarily the type of our class here; we might
9534   // be initializing an array element instead.
9535   const CXXConstructorDecl *FD = E->getConstructor();
9536   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9537 
9538   bool ZeroInit = E->requiresZeroInitialization();
9539   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
9540     // If we've already performed zero-initialization, we're already done.
9541     if (Result.hasValue())
9542       return true;
9543 
9544     if (ZeroInit)
9545       return ZeroInitialization(E, T);
9546 
9547     return getDefaultInitValue(T, Result);
9548   }
9549 
9550   const FunctionDecl *Definition = nullptr;
9551   auto Body = FD->getBody(Definition);
9552 
9553   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9554     return false;
9555 
9556   // Avoid materializing a temporary for an elidable copy/move constructor.
9557   if (E->isElidable() && !ZeroInit)
9558     if (const MaterializeTemporaryExpr *ME
9559           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
9560       return Visit(ME->getSubExpr());
9561 
9562   if (ZeroInit && !ZeroInitialization(E, T))
9563     return false;
9564 
9565   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
9566   return HandleConstructorCall(E, This, Args,
9567                                cast<CXXConstructorDecl>(Definition), Info,
9568                                Result);
9569 }
9570 
9571 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9572     const CXXInheritedCtorInitExpr *E) {
9573   if (!Info.CurrentCall) {
9574     assert(Info.checkingPotentialConstantExpression());
9575     return false;
9576   }
9577 
9578   const CXXConstructorDecl *FD = E->getConstructor();
9579   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9580     return false;
9581 
9582   const FunctionDecl *Definition = nullptr;
9583   auto Body = FD->getBody(Definition);
9584 
9585   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9586     return false;
9587 
9588   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
9589                                cast<CXXConstructorDecl>(Definition), Info,
9590                                Result);
9591 }
9592 
9593 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
9594     const CXXStdInitializerListExpr *E) {
9595   const ConstantArrayType *ArrayType =
9596       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
9597 
9598   LValue Array;
9599   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
9600     return false;
9601 
9602   // Get a pointer to the first element of the array.
9603   Array.addArray(Info, E, ArrayType);
9604 
9605   auto InvalidType = [&] {
9606     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
9607       << E->getType();
9608     return false;
9609   };
9610 
9611   // FIXME: Perform the checks on the field types in SemaInit.
9612   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
9613   RecordDecl::field_iterator Field = Record->field_begin();
9614   if (Field == Record->field_end())
9615     return InvalidType();
9616 
9617   // Start pointer.
9618   if (!Field->getType()->isPointerType() ||
9619       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9620                             ArrayType->getElementType()))
9621     return InvalidType();
9622 
9623   // FIXME: What if the initializer_list type has base classes, etc?
9624   Result = APValue(APValue::UninitStruct(), 0, 2);
9625   Array.moveInto(Result.getStructField(0));
9626 
9627   if (++Field == Record->field_end())
9628     return InvalidType();
9629 
9630   if (Field->getType()->isPointerType() &&
9631       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9632                            ArrayType->getElementType())) {
9633     // End pointer.
9634     if (!HandleLValueArrayAdjustment(Info, E, Array,
9635                                      ArrayType->getElementType(),
9636                                      ArrayType->getSize().getZExtValue()))
9637       return false;
9638     Array.moveInto(Result.getStructField(1));
9639   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
9640     // Length.
9641     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
9642   else
9643     return InvalidType();
9644 
9645   if (++Field != Record->field_end())
9646     return InvalidType();
9647 
9648   return true;
9649 }
9650 
9651 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
9652   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
9653   if (ClosureClass->isInvalidDecl())
9654     return false;
9655 
9656   const size_t NumFields =
9657       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
9658 
9659   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
9660                                             E->capture_init_end()) &&
9661          "The number of lambda capture initializers should equal the number of "
9662          "fields within the closure type");
9663 
9664   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
9665   // Iterate through all the lambda's closure object's fields and initialize
9666   // them.
9667   auto *CaptureInitIt = E->capture_init_begin();
9668   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
9669   bool Success = true;
9670   for (const auto *Field : ClosureClass->fields()) {
9671     assert(CaptureInitIt != E->capture_init_end());
9672     // Get the initializer for this field
9673     Expr *const CurFieldInit = *CaptureInitIt++;
9674 
9675     // If there is no initializer, either this is a VLA or an error has
9676     // occurred.
9677     if (!CurFieldInit)
9678       return Error(E);
9679 
9680     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9681     if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
9682       if (!Info.keepEvaluatingAfterFailure())
9683         return false;
9684       Success = false;
9685     }
9686     ++CaptureIt;
9687   }
9688   return Success;
9689 }
9690 
9691 static bool EvaluateRecord(const Expr *E, const LValue &This,
9692                            APValue &Result, EvalInfo &Info) {
9693   assert(E->isRValue() && E->getType()->isRecordType() &&
9694          "can't evaluate expression as a record rvalue");
9695   return RecordExprEvaluator(Info, This, Result).Visit(E);
9696 }
9697 
9698 //===----------------------------------------------------------------------===//
9699 // Temporary Evaluation
9700 //
9701 // Temporaries are represented in the AST as rvalues, but generally behave like
9702 // lvalues. The full-object of which the temporary is a subobject is implicitly
9703 // materialized so that a reference can bind to it.
9704 //===----------------------------------------------------------------------===//
9705 namespace {
9706 class TemporaryExprEvaluator
9707   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
9708 public:
9709   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
9710     LValueExprEvaluatorBaseTy(Info, Result, false) {}
9711 
9712   /// Visit an expression which constructs the value of this temporary.
9713   bool VisitConstructExpr(const Expr *E) {
9714     APValue &Value =
9715         Info.CurrentCall->createTemporary(E, E->getType(), false, Result);
9716     return EvaluateInPlace(Value, Info, Result, E);
9717   }
9718 
9719   bool VisitCastExpr(const CastExpr *E) {
9720     switch (E->getCastKind()) {
9721     default:
9722       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9723 
9724     case CK_ConstructorConversion:
9725       return VisitConstructExpr(E->getSubExpr());
9726     }
9727   }
9728   bool VisitInitListExpr(const InitListExpr *E) {
9729     return VisitConstructExpr(E);
9730   }
9731   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9732     return VisitConstructExpr(E);
9733   }
9734   bool VisitCallExpr(const CallExpr *E) {
9735     return VisitConstructExpr(E);
9736   }
9737   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
9738     return VisitConstructExpr(E);
9739   }
9740   bool VisitLambdaExpr(const LambdaExpr *E) {
9741     return VisitConstructExpr(E);
9742   }
9743 };
9744 } // end anonymous namespace
9745 
9746 /// Evaluate an expression of record type as a temporary.
9747 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
9748   assert(E->isRValue() && E->getType()->isRecordType());
9749   return TemporaryExprEvaluator(Info, Result).Visit(E);
9750 }
9751 
9752 //===----------------------------------------------------------------------===//
9753 // Vector Evaluation
9754 //===----------------------------------------------------------------------===//
9755 
9756 namespace {
9757   class VectorExprEvaluator
9758   : public ExprEvaluatorBase<VectorExprEvaluator> {
9759     APValue &Result;
9760   public:
9761 
9762     VectorExprEvaluator(EvalInfo &info, APValue &Result)
9763       : ExprEvaluatorBaseTy(info), Result(Result) {}
9764 
9765     bool Success(ArrayRef<APValue> V, const Expr *E) {
9766       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
9767       // FIXME: remove this APValue copy.
9768       Result = APValue(V.data(), V.size());
9769       return true;
9770     }
9771     bool Success(const APValue &V, const Expr *E) {
9772       assert(V.isVector());
9773       Result = V;
9774       return true;
9775     }
9776     bool ZeroInitialization(const Expr *E);
9777 
9778     bool VisitUnaryReal(const UnaryOperator *E)
9779       { return Visit(E->getSubExpr()); }
9780     bool VisitCastExpr(const CastExpr* E);
9781     bool VisitInitListExpr(const InitListExpr *E);
9782     bool VisitUnaryImag(const UnaryOperator *E);
9783     bool VisitBinaryOperator(const BinaryOperator *E);
9784     // FIXME: Missing: unary -, unary ~, conditional operator (for GNU
9785     //                 conditional select), shufflevector, ExtVectorElementExpr
9786   };
9787 } // end anonymous namespace
9788 
9789 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
9790   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
9791   return VectorExprEvaluator(Info, Result).Visit(E);
9792 }
9793 
9794 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
9795   const VectorType *VTy = E->getType()->castAs<VectorType>();
9796   unsigned NElts = VTy->getNumElements();
9797 
9798   const Expr *SE = E->getSubExpr();
9799   QualType SETy = SE->getType();
9800 
9801   switch (E->getCastKind()) {
9802   case CK_VectorSplat: {
9803     APValue Val = APValue();
9804     if (SETy->isIntegerType()) {
9805       APSInt IntResult;
9806       if (!EvaluateInteger(SE, IntResult, Info))
9807         return false;
9808       Val = APValue(std::move(IntResult));
9809     } else if (SETy->isRealFloatingType()) {
9810       APFloat FloatResult(0.0);
9811       if (!EvaluateFloat(SE, FloatResult, Info))
9812         return false;
9813       Val = APValue(std::move(FloatResult));
9814     } else {
9815       return Error(E);
9816     }
9817 
9818     // Splat and create vector APValue.
9819     SmallVector<APValue, 4> Elts(NElts, Val);
9820     return Success(Elts, E);
9821   }
9822   case CK_BitCast: {
9823     // Evaluate the operand into an APInt we can extract from.
9824     llvm::APInt SValInt;
9825     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
9826       return false;
9827     // Extract the elements
9828     QualType EltTy = VTy->getElementType();
9829     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
9830     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
9831     SmallVector<APValue, 4> Elts;
9832     if (EltTy->isRealFloatingType()) {
9833       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
9834       unsigned FloatEltSize = EltSize;
9835       if (&Sem == &APFloat::x87DoubleExtended())
9836         FloatEltSize = 80;
9837       for (unsigned i = 0; i < NElts; i++) {
9838         llvm::APInt Elt;
9839         if (BigEndian)
9840           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
9841         else
9842           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
9843         Elts.push_back(APValue(APFloat(Sem, Elt)));
9844       }
9845     } else if (EltTy->isIntegerType()) {
9846       for (unsigned i = 0; i < NElts; i++) {
9847         llvm::APInt Elt;
9848         if (BigEndian)
9849           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
9850         else
9851           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
9852         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
9853       }
9854     } else {
9855       return Error(E);
9856     }
9857     return Success(Elts, E);
9858   }
9859   default:
9860     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9861   }
9862 }
9863 
9864 bool
9865 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9866   const VectorType *VT = E->getType()->castAs<VectorType>();
9867   unsigned NumInits = E->getNumInits();
9868   unsigned NumElements = VT->getNumElements();
9869 
9870   QualType EltTy = VT->getElementType();
9871   SmallVector<APValue, 4> Elements;
9872 
9873   // The number of initializers can be less than the number of
9874   // vector elements. For OpenCL, this can be due to nested vector
9875   // initialization. For GCC compatibility, missing trailing elements
9876   // should be initialized with zeroes.
9877   unsigned CountInits = 0, CountElts = 0;
9878   while (CountElts < NumElements) {
9879     // Handle nested vector initialization.
9880     if (CountInits < NumInits
9881         && E->getInit(CountInits)->getType()->isVectorType()) {
9882       APValue v;
9883       if (!EvaluateVector(E->getInit(CountInits), v, Info))
9884         return Error(E);
9885       unsigned vlen = v.getVectorLength();
9886       for (unsigned j = 0; j < vlen; j++)
9887         Elements.push_back(v.getVectorElt(j));
9888       CountElts += vlen;
9889     } else if (EltTy->isIntegerType()) {
9890       llvm::APSInt sInt(32);
9891       if (CountInits < NumInits) {
9892         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
9893           return false;
9894       } else // trailing integer zero.
9895         sInt = Info.Ctx.MakeIntValue(0, EltTy);
9896       Elements.push_back(APValue(sInt));
9897       CountElts++;
9898     } else {
9899       llvm::APFloat f(0.0);
9900       if (CountInits < NumInits) {
9901         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
9902           return false;
9903       } else // trailing float zero.
9904         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
9905       Elements.push_back(APValue(f));
9906       CountElts++;
9907     }
9908     CountInits++;
9909   }
9910   return Success(Elements, E);
9911 }
9912 
9913 bool
9914 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
9915   const auto *VT = E->getType()->castAs<VectorType>();
9916   QualType EltTy = VT->getElementType();
9917   APValue ZeroElement;
9918   if (EltTy->isIntegerType())
9919     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
9920   else
9921     ZeroElement =
9922         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
9923 
9924   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
9925   return Success(Elements, E);
9926 }
9927 
9928 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9929   VisitIgnoredValue(E->getSubExpr());
9930   return ZeroInitialization(E);
9931 }
9932 
9933 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9934   BinaryOperatorKind Op = E->getOpcode();
9935   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
9936          "Operation not supported on vector types");
9937 
9938   if (Op == BO_Comma)
9939     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9940 
9941   Expr *LHS = E->getLHS();
9942   Expr *RHS = E->getRHS();
9943 
9944   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
9945          "Must both be vector types");
9946   // Checking JUST the types are the same would be fine, except shifts don't
9947   // need to have their types be the same (since you always shift by an int).
9948   assert(LHS->getType()->getAs<VectorType>()->getNumElements() ==
9949              E->getType()->getAs<VectorType>()->getNumElements() &&
9950          RHS->getType()->getAs<VectorType>()->getNumElements() ==
9951              E->getType()->getAs<VectorType>()->getNumElements() &&
9952          "All operands must be the same size.");
9953 
9954   APValue LHSValue;
9955   APValue RHSValue;
9956   bool LHSOK = Evaluate(LHSValue, Info, LHS);
9957   if (!LHSOK && !Info.noteFailure())
9958     return false;
9959   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
9960     return false;
9961 
9962   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
9963     return false;
9964 
9965   return Success(LHSValue, E);
9966 }
9967 
9968 //===----------------------------------------------------------------------===//
9969 // Array Evaluation
9970 //===----------------------------------------------------------------------===//
9971 
9972 namespace {
9973   class ArrayExprEvaluator
9974   : public ExprEvaluatorBase<ArrayExprEvaluator> {
9975     const LValue &This;
9976     APValue &Result;
9977   public:
9978 
9979     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
9980       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
9981 
9982     bool Success(const APValue &V, const Expr *E) {
9983       assert(V.isArray() && "expected array");
9984       Result = V;
9985       return true;
9986     }
9987 
9988     bool ZeroInitialization(const Expr *E) {
9989       const ConstantArrayType *CAT =
9990           Info.Ctx.getAsConstantArrayType(E->getType());
9991       if (!CAT) {
9992         if (E->getType()->isIncompleteArrayType()) {
9993           // We can be asked to zero-initialize a flexible array member; this
9994           // is represented as an ImplicitValueInitExpr of incomplete array
9995           // type. In this case, the array has zero elements.
9996           Result = APValue(APValue::UninitArray(), 0, 0);
9997           return true;
9998         }
9999         // FIXME: We could handle VLAs here.
10000         return Error(E);
10001       }
10002 
10003       Result = APValue(APValue::UninitArray(), 0,
10004                        CAT->getSize().getZExtValue());
10005       if (!Result.hasArrayFiller()) return true;
10006 
10007       // Zero-initialize all elements.
10008       LValue Subobject = This;
10009       Subobject.addArray(Info, E, CAT);
10010       ImplicitValueInitExpr VIE(CAT->getElementType());
10011       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10012     }
10013 
10014     bool VisitCallExpr(const CallExpr *E) {
10015       return handleCallExpr(E, Result, &This);
10016     }
10017     bool VisitInitListExpr(const InitListExpr *E,
10018                            QualType AllocType = QualType());
10019     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10020     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10021     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10022                                const LValue &Subobject,
10023                                APValue *Value, QualType Type);
10024     bool VisitStringLiteral(const StringLiteral *E,
10025                             QualType AllocType = QualType()) {
10026       expandStringLiteral(Info, E, Result, AllocType);
10027       return true;
10028     }
10029   };
10030 } // end anonymous namespace
10031 
10032 static bool EvaluateArray(const Expr *E, const LValue &This,
10033                           APValue &Result, EvalInfo &Info) {
10034   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
10035   return ArrayExprEvaluator(Info, This, Result).Visit(E);
10036 }
10037 
10038 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10039                                      APValue &Result, const InitListExpr *ILE,
10040                                      QualType AllocType) {
10041   assert(ILE->isRValue() && ILE->getType()->isArrayType() &&
10042          "not an array rvalue");
10043   return ArrayExprEvaluator(Info, This, Result)
10044       .VisitInitListExpr(ILE, AllocType);
10045 }
10046 
10047 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10048                                           APValue &Result,
10049                                           const CXXConstructExpr *CCE,
10050                                           QualType AllocType) {
10051   assert(CCE->isRValue() && CCE->getType()->isArrayType() &&
10052          "not an array rvalue");
10053   return ArrayExprEvaluator(Info, This, Result)
10054       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10055 }
10056 
10057 // Return true iff the given array filler may depend on the element index.
10058 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10059   // For now, just allow non-class value-initialization and initialization
10060   // lists comprised of them.
10061   if (isa<ImplicitValueInitExpr>(FillerExpr))
10062     return false;
10063   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10064     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10065       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10066         return true;
10067     }
10068     return false;
10069   }
10070   return true;
10071 }
10072 
10073 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10074                                            QualType AllocType) {
10075   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10076       AllocType.isNull() ? E->getType() : AllocType);
10077   if (!CAT)
10078     return Error(E);
10079 
10080   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10081   // an appropriately-typed string literal enclosed in braces.
10082   if (E->isStringLiteralInit()) {
10083     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
10084     // FIXME: Support ObjCEncodeExpr here once we support it in
10085     // ArrayExprEvaluator generally.
10086     if (!SL)
10087       return Error(E);
10088     return VisitStringLiteral(SL, AllocType);
10089   }
10090 
10091   bool Success = true;
10092 
10093   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10094          "zero-initialized array shouldn't have any initialized elts");
10095   APValue Filler;
10096   if (Result.isArray() && Result.hasArrayFiller())
10097     Filler = Result.getArrayFiller();
10098 
10099   unsigned NumEltsToInit = E->getNumInits();
10100   unsigned NumElts = CAT->getSize().getZExtValue();
10101   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
10102 
10103   // If the initializer might depend on the array index, run it for each
10104   // array element.
10105   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
10106     NumEltsToInit = NumElts;
10107 
10108   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10109                           << NumEltsToInit << ".\n");
10110 
10111   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10112 
10113   // If the array was previously zero-initialized, preserve the
10114   // zero-initialized values.
10115   if (Filler.hasValue()) {
10116     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10117       Result.getArrayInitializedElt(I) = Filler;
10118     if (Result.hasArrayFiller())
10119       Result.getArrayFiller() = Filler;
10120   }
10121 
10122   LValue Subobject = This;
10123   Subobject.addArray(Info, E, CAT);
10124   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10125     const Expr *Init =
10126         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
10127     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10128                          Info, Subobject, Init) ||
10129         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10130                                      CAT->getElementType(), 1)) {
10131       if (!Info.noteFailure())
10132         return false;
10133       Success = false;
10134     }
10135   }
10136 
10137   if (!Result.hasArrayFiller())
10138     return Success;
10139 
10140   // If we get here, we have a trivial filler, which we can just evaluate
10141   // once and splat over the rest of the array elements.
10142   assert(FillerExpr && "no array filler for incomplete init list");
10143   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10144                          FillerExpr) && Success;
10145 }
10146 
10147 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10148   LValue CommonLV;
10149   if (E->getCommonExpr() &&
10150       !Evaluate(Info.CurrentCall->createTemporary(
10151                     E->getCommonExpr(),
10152                     getStorageType(Info.Ctx, E->getCommonExpr()), false,
10153                     CommonLV),
10154                 Info, E->getCommonExpr()->getSourceExpr()))
10155     return false;
10156 
10157   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10158 
10159   uint64_t Elements = CAT->getSize().getZExtValue();
10160   Result = APValue(APValue::UninitArray(), Elements, Elements);
10161 
10162   LValue Subobject = This;
10163   Subobject.addArray(Info, E, CAT);
10164 
10165   bool Success = true;
10166   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10167     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10168                          Info, Subobject, E->getSubExpr()) ||
10169         !HandleLValueArrayAdjustment(Info, E, Subobject,
10170                                      CAT->getElementType(), 1)) {
10171       if (!Info.noteFailure())
10172         return false;
10173       Success = false;
10174     }
10175   }
10176 
10177   return Success;
10178 }
10179 
10180 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10181   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10182 }
10183 
10184 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10185                                                const LValue &Subobject,
10186                                                APValue *Value,
10187                                                QualType Type) {
10188   bool HadZeroInit = Value->hasValue();
10189 
10190   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10191     unsigned N = CAT->getSize().getZExtValue();
10192 
10193     // Preserve the array filler if we had prior zero-initialization.
10194     APValue Filler =
10195       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10196                                              : APValue();
10197 
10198     *Value = APValue(APValue::UninitArray(), N, N);
10199 
10200     if (HadZeroInit)
10201       for (unsigned I = 0; I != N; ++I)
10202         Value->getArrayInitializedElt(I) = Filler;
10203 
10204     // Initialize the elements.
10205     LValue ArrayElt = Subobject;
10206     ArrayElt.addArray(Info, E, CAT);
10207     for (unsigned I = 0; I != N; ++I)
10208       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
10209                                  CAT->getElementType()) ||
10210           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10211                                        CAT->getElementType(), 1))
10212         return false;
10213 
10214     return true;
10215   }
10216 
10217   if (!Type->isRecordType())
10218     return Error(E);
10219 
10220   return RecordExprEvaluator(Info, Subobject, *Value)
10221              .VisitCXXConstructExpr(E, Type);
10222 }
10223 
10224 //===----------------------------------------------------------------------===//
10225 // Integer Evaluation
10226 //
10227 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10228 // types and back in constant folding. Integer values are thus represented
10229 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10230 //===----------------------------------------------------------------------===//
10231 
10232 namespace {
10233 class IntExprEvaluator
10234         : public ExprEvaluatorBase<IntExprEvaluator> {
10235   APValue &Result;
10236 public:
10237   IntExprEvaluator(EvalInfo &info, APValue &result)
10238       : ExprEvaluatorBaseTy(info), Result(result) {}
10239 
10240   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10241     assert(E->getType()->isIntegralOrEnumerationType() &&
10242            "Invalid evaluation result.");
10243     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10244            "Invalid evaluation result.");
10245     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10246            "Invalid evaluation result.");
10247     Result = APValue(SI);
10248     return true;
10249   }
10250   bool Success(const llvm::APSInt &SI, const Expr *E) {
10251     return Success(SI, E, Result);
10252   }
10253 
10254   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10255     assert(E->getType()->isIntegralOrEnumerationType() &&
10256            "Invalid evaluation result.");
10257     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10258            "Invalid evaluation result.");
10259     Result = APValue(APSInt(I));
10260     Result.getInt().setIsUnsigned(
10261                             E->getType()->isUnsignedIntegerOrEnumerationType());
10262     return true;
10263   }
10264   bool Success(const llvm::APInt &I, const Expr *E) {
10265     return Success(I, E, Result);
10266   }
10267 
10268   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10269     assert(E->getType()->isIntegralOrEnumerationType() &&
10270            "Invalid evaluation result.");
10271     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10272     return true;
10273   }
10274   bool Success(uint64_t Value, const Expr *E) {
10275     return Success(Value, E, Result);
10276   }
10277 
10278   bool Success(CharUnits Size, const Expr *E) {
10279     return Success(Size.getQuantity(), E);
10280   }
10281 
10282   bool Success(const APValue &V, const Expr *E) {
10283     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10284       Result = V;
10285       return true;
10286     }
10287     return Success(V.getInt(), E);
10288   }
10289 
10290   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10291 
10292   //===--------------------------------------------------------------------===//
10293   //                            Visitor Methods
10294   //===--------------------------------------------------------------------===//
10295 
10296   bool VisitIntegerLiteral(const IntegerLiteral *E) {
10297     return Success(E->getValue(), E);
10298   }
10299   bool VisitCharacterLiteral(const CharacterLiteral *E) {
10300     return Success(E->getValue(), E);
10301   }
10302 
10303   bool CheckReferencedDecl(const Expr *E, const Decl *D);
10304   bool VisitDeclRefExpr(const DeclRefExpr *E) {
10305     if (CheckReferencedDecl(E, E->getDecl()))
10306       return true;
10307 
10308     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
10309   }
10310   bool VisitMemberExpr(const MemberExpr *E) {
10311     if (CheckReferencedDecl(E, E->getMemberDecl())) {
10312       VisitIgnoredBaseExpression(E->getBase());
10313       return true;
10314     }
10315 
10316     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
10317   }
10318 
10319   bool VisitCallExpr(const CallExpr *E);
10320   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10321   bool VisitBinaryOperator(const BinaryOperator *E);
10322   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
10323   bool VisitUnaryOperator(const UnaryOperator *E);
10324 
10325   bool VisitCastExpr(const CastExpr* E);
10326   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
10327 
10328   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
10329     return Success(E->getValue(), E);
10330   }
10331 
10332   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
10333     return Success(E->getValue(), E);
10334   }
10335 
10336   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
10337     if (Info.ArrayInitIndex == uint64_t(-1)) {
10338       // We were asked to evaluate this subexpression independent of the
10339       // enclosing ArrayInitLoopExpr. We can't do that.
10340       Info.FFDiag(E);
10341       return false;
10342     }
10343     return Success(Info.ArrayInitIndex, E);
10344   }
10345 
10346   // Note, GNU defines __null as an integer, not a pointer.
10347   bool VisitGNUNullExpr(const GNUNullExpr *E) {
10348     return ZeroInitialization(E);
10349   }
10350 
10351   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
10352     return Success(E->getValue(), E);
10353   }
10354 
10355   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
10356     return Success(E->getValue(), E);
10357   }
10358 
10359   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
10360     return Success(E->getValue(), E);
10361   }
10362 
10363   bool VisitUnaryReal(const UnaryOperator *E);
10364   bool VisitUnaryImag(const UnaryOperator *E);
10365 
10366   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
10367   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
10368   bool VisitSourceLocExpr(const SourceLocExpr *E);
10369   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
10370   bool VisitRequiresExpr(const RequiresExpr *E);
10371   // FIXME: Missing: array subscript of vector, member of vector
10372 };
10373 
10374 class FixedPointExprEvaluator
10375     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
10376   APValue &Result;
10377 
10378  public:
10379   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
10380       : ExprEvaluatorBaseTy(info), Result(result) {}
10381 
10382   bool Success(const llvm::APInt &I, const Expr *E) {
10383     return Success(
10384         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10385   }
10386 
10387   bool Success(uint64_t Value, const Expr *E) {
10388     return Success(
10389         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10390   }
10391 
10392   bool Success(const APValue &V, const Expr *E) {
10393     return Success(V.getFixedPoint(), E);
10394   }
10395 
10396   bool Success(const APFixedPoint &V, const Expr *E) {
10397     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
10398     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10399            "Invalid evaluation result.");
10400     Result = APValue(V);
10401     return true;
10402   }
10403 
10404   //===--------------------------------------------------------------------===//
10405   //                            Visitor Methods
10406   //===--------------------------------------------------------------------===//
10407 
10408   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
10409     return Success(E->getValue(), E);
10410   }
10411 
10412   bool VisitCastExpr(const CastExpr *E);
10413   bool VisitUnaryOperator(const UnaryOperator *E);
10414   bool VisitBinaryOperator(const BinaryOperator *E);
10415 };
10416 } // end anonymous namespace
10417 
10418 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
10419 /// produce either the integer value or a pointer.
10420 ///
10421 /// GCC has a heinous extension which folds casts between pointer types and
10422 /// pointer-sized integral types. We support this by allowing the evaluation of
10423 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
10424 /// Some simple arithmetic on such values is supported (they are treated much
10425 /// like char*).
10426 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
10427                                     EvalInfo &Info) {
10428   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
10429   return IntExprEvaluator(Info, Result).Visit(E);
10430 }
10431 
10432 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
10433   APValue Val;
10434   if (!EvaluateIntegerOrLValue(E, Val, Info))
10435     return false;
10436   if (!Val.isInt()) {
10437     // FIXME: It would be better to produce the diagnostic for casting
10438     //        a pointer to an integer.
10439     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10440     return false;
10441   }
10442   Result = Val.getInt();
10443   return true;
10444 }
10445 
10446 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
10447   APValue Evaluated = E->EvaluateInContext(
10448       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10449   return Success(Evaluated, E);
10450 }
10451 
10452 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
10453                                EvalInfo &Info) {
10454   if (E->getType()->isFixedPointType()) {
10455     APValue Val;
10456     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
10457       return false;
10458     if (!Val.isFixedPoint())
10459       return false;
10460 
10461     Result = Val.getFixedPoint();
10462     return true;
10463   }
10464   return false;
10465 }
10466 
10467 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
10468                                         EvalInfo &Info) {
10469   if (E->getType()->isIntegerType()) {
10470     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
10471     APSInt Val;
10472     if (!EvaluateInteger(E, Val, Info))
10473       return false;
10474     Result = APFixedPoint(Val, FXSema);
10475     return true;
10476   } else if (E->getType()->isFixedPointType()) {
10477     return EvaluateFixedPoint(E, Result, Info);
10478   }
10479   return false;
10480 }
10481 
10482 /// Check whether the given declaration can be directly converted to an integral
10483 /// rvalue. If not, no diagnostic is produced; there are other things we can
10484 /// try.
10485 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
10486   // Enums are integer constant exprs.
10487   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
10488     // Check for signedness/width mismatches between E type and ECD value.
10489     bool SameSign = (ECD->getInitVal().isSigned()
10490                      == E->getType()->isSignedIntegerOrEnumerationType());
10491     bool SameWidth = (ECD->getInitVal().getBitWidth()
10492                       == Info.Ctx.getIntWidth(E->getType()));
10493     if (SameSign && SameWidth)
10494       return Success(ECD->getInitVal(), E);
10495     else {
10496       // Get rid of mismatch (otherwise Success assertions will fail)
10497       // by computing a new value matching the type of E.
10498       llvm::APSInt Val = ECD->getInitVal();
10499       if (!SameSign)
10500         Val.setIsSigned(!ECD->getInitVal().isSigned());
10501       if (!SameWidth)
10502         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
10503       return Success(Val, E);
10504     }
10505   }
10506   return false;
10507 }
10508 
10509 /// Values returned by __builtin_classify_type, chosen to match the values
10510 /// produced by GCC's builtin.
10511 enum class GCCTypeClass {
10512   None = -1,
10513   Void = 0,
10514   Integer = 1,
10515   // GCC reserves 2 for character types, but instead classifies them as
10516   // integers.
10517   Enum = 3,
10518   Bool = 4,
10519   Pointer = 5,
10520   // GCC reserves 6 for references, but appears to never use it (because
10521   // expressions never have reference type, presumably).
10522   PointerToDataMember = 7,
10523   RealFloat = 8,
10524   Complex = 9,
10525   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
10526   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
10527   // GCC claims to reserve 11 for pointers to member functions, but *actually*
10528   // uses 12 for that purpose, same as for a class or struct. Maybe it
10529   // internally implements a pointer to member as a struct?  Who knows.
10530   PointerToMemberFunction = 12, // Not a bug, see above.
10531   ClassOrStruct = 12,
10532   Union = 13,
10533   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
10534   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
10535   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
10536   // literals.
10537 };
10538 
10539 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10540 /// as GCC.
10541 static GCCTypeClass
10542 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
10543   assert(!T->isDependentType() && "unexpected dependent type");
10544 
10545   QualType CanTy = T.getCanonicalType();
10546   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
10547 
10548   switch (CanTy->getTypeClass()) {
10549 #define TYPE(ID, BASE)
10550 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
10551 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
10552 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
10553 #include "clang/AST/TypeNodes.inc"
10554   case Type::Auto:
10555   case Type::DeducedTemplateSpecialization:
10556       llvm_unreachable("unexpected non-canonical or dependent type");
10557 
10558   case Type::Builtin:
10559     switch (BT->getKind()) {
10560 #define BUILTIN_TYPE(ID, SINGLETON_ID)
10561 #define SIGNED_TYPE(ID, SINGLETON_ID) \
10562     case BuiltinType::ID: return GCCTypeClass::Integer;
10563 #define FLOATING_TYPE(ID, SINGLETON_ID) \
10564     case BuiltinType::ID: return GCCTypeClass::RealFloat;
10565 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
10566     case BuiltinType::ID: break;
10567 #include "clang/AST/BuiltinTypes.def"
10568     case BuiltinType::Void:
10569       return GCCTypeClass::Void;
10570 
10571     case BuiltinType::Bool:
10572       return GCCTypeClass::Bool;
10573 
10574     case BuiltinType::Char_U:
10575     case BuiltinType::UChar:
10576     case BuiltinType::WChar_U:
10577     case BuiltinType::Char8:
10578     case BuiltinType::Char16:
10579     case BuiltinType::Char32:
10580     case BuiltinType::UShort:
10581     case BuiltinType::UInt:
10582     case BuiltinType::ULong:
10583     case BuiltinType::ULongLong:
10584     case BuiltinType::UInt128:
10585       return GCCTypeClass::Integer;
10586 
10587     case BuiltinType::UShortAccum:
10588     case BuiltinType::UAccum:
10589     case BuiltinType::ULongAccum:
10590     case BuiltinType::UShortFract:
10591     case BuiltinType::UFract:
10592     case BuiltinType::ULongFract:
10593     case BuiltinType::SatUShortAccum:
10594     case BuiltinType::SatUAccum:
10595     case BuiltinType::SatULongAccum:
10596     case BuiltinType::SatUShortFract:
10597     case BuiltinType::SatUFract:
10598     case BuiltinType::SatULongFract:
10599       return GCCTypeClass::None;
10600 
10601     case BuiltinType::NullPtr:
10602 
10603     case BuiltinType::ObjCId:
10604     case BuiltinType::ObjCClass:
10605     case BuiltinType::ObjCSel:
10606 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
10607     case BuiltinType::Id:
10608 #include "clang/Basic/OpenCLImageTypes.def"
10609 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
10610     case BuiltinType::Id:
10611 #include "clang/Basic/OpenCLExtensionTypes.def"
10612     case BuiltinType::OCLSampler:
10613     case BuiltinType::OCLEvent:
10614     case BuiltinType::OCLClkEvent:
10615     case BuiltinType::OCLQueue:
10616     case BuiltinType::OCLReserveID:
10617 #define SVE_TYPE(Name, Id, SingletonId) \
10618     case BuiltinType::Id:
10619 #include "clang/Basic/AArch64SVEACLETypes.def"
10620       return GCCTypeClass::None;
10621 
10622     case BuiltinType::Dependent:
10623       llvm_unreachable("unexpected dependent type");
10624     };
10625     llvm_unreachable("unexpected placeholder type");
10626 
10627   case Type::Enum:
10628     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
10629 
10630   case Type::Pointer:
10631   case Type::ConstantArray:
10632   case Type::VariableArray:
10633   case Type::IncompleteArray:
10634   case Type::FunctionNoProto:
10635   case Type::FunctionProto:
10636     return GCCTypeClass::Pointer;
10637 
10638   case Type::MemberPointer:
10639     return CanTy->isMemberDataPointerType()
10640                ? GCCTypeClass::PointerToDataMember
10641                : GCCTypeClass::PointerToMemberFunction;
10642 
10643   case Type::Complex:
10644     return GCCTypeClass::Complex;
10645 
10646   case Type::Record:
10647     return CanTy->isUnionType() ? GCCTypeClass::Union
10648                                 : GCCTypeClass::ClassOrStruct;
10649 
10650   case Type::Atomic:
10651     // GCC classifies _Atomic T the same as T.
10652     return EvaluateBuiltinClassifyType(
10653         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
10654 
10655   case Type::BlockPointer:
10656   case Type::Vector:
10657   case Type::ExtVector:
10658   case Type::ConstantMatrix:
10659   case Type::ObjCObject:
10660   case Type::ObjCInterface:
10661   case Type::ObjCObjectPointer:
10662   case Type::Pipe:
10663   case Type::ExtInt:
10664     // GCC classifies vectors as None. We follow its lead and classify all
10665     // other types that don't fit into the regular classification the same way.
10666     return GCCTypeClass::None;
10667 
10668   case Type::LValueReference:
10669   case Type::RValueReference:
10670     llvm_unreachable("invalid type for expression");
10671   }
10672 
10673   llvm_unreachable("unexpected type class");
10674 }
10675 
10676 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10677 /// as GCC.
10678 static GCCTypeClass
10679 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
10680   // If no argument was supplied, default to None. This isn't
10681   // ideal, however it is what gcc does.
10682   if (E->getNumArgs() == 0)
10683     return GCCTypeClass::None;
10684 
10685   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
10686   // being an ICE, but still folds it to a constant using the type of the first
10687   // argument.
10688   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
10689 }
10690 
10691 /// EvaluateBuiltinConstantPForLValue - Determine the result of
10692 /// __builtin_constant_p when applied to the given pointer.
10693 ///
10694 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
10695 /// or it points to the first character of a string literal.
10696 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
10697   APValue::LValueBase Base = LV.getLValueBase();
10698   if (Base.isNull()) {
10699     // A null base is acceptable.
10700     return true;
10701   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
10702     if (!isa<StringLiteral>(E))
10703       return false;
10704     return LV.getLValueOffset().isZero();
10705   } else if (Base.is<TypeInfoLValue>()) {
10706     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
10707     // evaluate to true.
10708     return true;
10709   } else {
10710     // Any other base is not constant enough for GCC.
10711     return false;
10712   }
10713 }
10714 
10715 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
10716 /// GCC as we can manage.
10717 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
10718   // This evaluation is not permitted to have side-effects, so evaluate it in
10719   // a speculative evaluation context.
10720   SpeculativeEvaluationRAII SpeculativeEval(Info);
10721 
10722   // Constant-folding is always enabled for the operand of __builtin_constant_p
10723   // (even when the enclosing evaluation context otherwise requires a strict
10724   // language-specific constant expression).
10725   FoldConstant Fold(Info, true);
10726 
10727   QualType ArgType = Arg->getType();
10728 
10729   // __builtin_constant_p always has one operand. The rules which gcc follows
10730   // are not precisely documented, but are as follows:
10731   //
10732   //  - If the operand is of integral, floating, complex or enumeration type,
10733   //    and can be folded to a known value of that type, it returns 1.
10734   //  - If the operand can be folded to a pointer to the first character
10735   //    of a string literal (or such a pointer cast to an integral type)
10736   //    or to a null pointer or an integer cast to a pointer, it returns 1.
10737   //
10738   // Otherwise, it returns 0.
10739   //
10740   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
10741   // its support for this did not work prior to GCC 9 and is not yet well
10742   // understood.
10743   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
10744       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
10745       ArgType->isNullPtrType()) {
10746     APValue V;
10747     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
10748       Fold.keepDiagnostics();
10749       return false;
10750     }
10751 
10752     // For a pointer (possibly cast to integer), there are special rules.
10753     if (V.getKind() == APValue::LValue)
10754       return EvaluateBuiltinConstantPForLValue(V);
10755 
10756     // Otherwise, any constant value is good enough.
10757     return V.hasValue();
10758   }
10759 
10760   // Anything else isn't considered to be sufficiently constant.
10761   return false;
10762 }
10763 
10764 /// Retrieves the "underlying object type" of the given expression,
10765 /// as used by __builtin_object_size.
10766 static QualType getObjectType(APValue::LValueBase B) {
10767   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
10768     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
10769       return VD->getType();
10770   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
10771     if (isa<CompoundLiteralExpr>(E))
10772       return E->getType();
10773   } else if (B.is<TypeInfoLValue>()) {
10774     return B.getTypeInfoType();
10775   } else if (B.is<DynamicAllocLValue>()) {
10776     return B.getDynamicAllocType();
10777   }
10778 
10779   return QualType();
10780 }
10781 
10782 /// A more selective version of E->IgnoreParenCasts for
10783 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
10784 /// to change the type of E.
10785 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
10786 ///
10787 /// Always returns an RValue with a pointer representation.
10788 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
10789   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
10790 
10791   auto *NoParens = E->IgnoreParens();
10792   auto *Cast = dyn_cast<CastExpr>(NoParens);
10793   if (Cast == nullptr)
10794     return NoParens;
10795 
10796   // We only conservatively allow a few kinds of casts, because this code is
10797   // inherently a simple solution that seeks to support the common case.
10798   auto CastKind = Cast->getCastKind();
10799   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
10800       CastKind != CK_AddressSpaceConversion)
10801     return NoParens;
10802 
10803   auto *SubExpr = Cast->getSubExpr();
10804   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
10805     return NoParens;
10806   return ignorePointerCastsAndParens(SubExpr);
10807 }
10808 
10809 /// Checks to see if the given LValue's Designator is at the end of the LValue's
10810 /// record layout. e.g.
10811 ///   struct { struct { int a, b; } fst, snd; } obj;
10812 ///   obj.fst   // no
10813 ///   obj.snd   // yes
10814 ///   obj.fst.a // no
10815 ///   obj.fst.b // no
10816 ///   obj.snd.a // no
10817 ///   obj.snd.b // yes
10818 ///
10819 /// Please note: this function is specialized for how __builtin_object_size
10820 /// views "objects".
10821 ///
10822 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
10823 /// correct result, it will always return true.
10824 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
10825   assert(!LVal.Designator.Invalid);
10826 
10827   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
10828     const RecordDecl *Parent = FD->getParent();
10829     Invalid = Parent->isInvalidDecl();
10830     if (Invalid || Parent->isUnion())
10831       return true;
10832     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
10833     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
10834   };
10835 
10836   auto &Base = LVal.getLValueBase();
10837   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
10838     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
10839       bool Invalid;
10840       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10841         return Invalid;
10842     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
10843       for (auto *FD : IFD->chain()) {
10844         bool Invalid;
10845         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
10846           return Invalid;
10847       }
10848     }
10849   }
10850 
10851   unsigned I = 0;
10852   QualType BaseType = getType(Base);
10853   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
10854     // If we don't know the array bound, conservatively assume we're looking at
10855     // the final array element.
10856     ++I;
10857     if (BaseType->isIncompleteArrayType())
10858       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
10859     else
10860       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
10861   }
10862 
10863   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
10864     const auto &Entry = LVal.Designator.Entries[I];
10865     if (BaseType->isArrayType()) {
10866       // Because __builtin_object_size treats arrays as objects, we can ignore
10867       // the index iff this is the last array in the Designator.
10868       if (I + 1 == E)
10869         return true;
10870       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
10871       uint64_t Index = Entry.getAsArrayIndex();
10872       if (Index + 1 != CAT->getSize())
10873         return false;
10874       BaseType = CAT->getElementType();
10875     } else if (BaseType->isAnyComplexType()) {
10876       const auto *CT = BaseType->castAs<ComplexType>();
10877       uint64_t Index = Entry.getAsArrayIndex();
10878       if (Index != 1)
10879         return false;
10880       BaseType = CT->getElementType();
10881     } else if (auto *FD = getAsField(Entry)) {
10882       bool Invalid;
10883       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10884         return Invalid;
10885       BaseType = FD->getType();
10886     } else {
10887       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
10888       return false;
10889     }
10890   }
10891   return true;
10892 }
10893 
10894 /// Tests to see if the LValue has a user-specified designator (that isn't
10895 /// necessarily valid). Note that this always returns 'true' if the LValue has
10896 /// an unsized array as its first designator entry, because there's currently no
10897 /// way to tell if the user typed *foo or foo[0].
10898 static bool refersToCompleteObject(const LValue &LVal) {
10899   if (LVal.Designator.Invalid)
10900     return false;
10901 
10902   if (!LVal.Designator.Entries.empty())
10903     return LVal.Designator.isMostDerivedAnUnsizedArray();
10904 
10905   if (!LVal.InvalidBase)
10906     return true;
10907 
10908   // If `E` is a MemberExpr, then the first part of the designator is hiding in
10909   // the LValueBase.
10910   const auto *E = LVal.Base.dyn_cast<const Expr *>();
10911   return !E || !isa<MemberExpr>(E);
10912 }
10913 
10914 /// Attempts to detect a user writing into a piece of memory that's impossible
10915 /// to figure out the size of by just using types.
10916 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
10917   const SubobjectDesignator &Designator = LVal.Designator;
10918   // Notes:
10919   // - Users can only write off of the end when we have an invalid base. Invalid
10920   //   bases imply we don't know where the memory came from.
10921   // - We used to be a bit more aggressive here; we'd only be conservative if
10922   //   the array at the end was flexible, or if it had 0 or 1 elements. This
10923   //   broke some common standard library extensions (PR30346), but was
10924   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
10925   //   with some sort of list. OTOH, it seems that GCC is always
10926   //   conservative with the last element in structs (if it's an array), so our
10927   //   current behavior is more compatible than an explicit list approach would
10928   //   be.
10929   return LVal.InvalidBase &&
10930          Designator.Entries.size() == Designator.MostDerivedPathLength &&
10931          Designator.MostDerivedIsArrayElement &&
10932          isDesignatorAtObjectEnd(Ctx, LVal);
10933 }
10934 
10935 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
10936 /// Fails if the conversion would cause loss of precision.
10937 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
10938                                             CharUnits &Result) {
10939   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
10940   if (Int.ugt(CharUnitsMax))
10941     return false;
10942   Result = CharUnits::fromQuantity(Int.getZExtValue());
10943   return true;
10944 }
10945 
10946 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
10947 /// determine how many bytes exist from the beginning of the object to either
10948 /// the end of the current subobject, or the end of the object itself, depending
10949 /// on what the LValue looks like + the value of Type.
10950 ///
10951 /// If this returns false, the value of Result is undefined.
10952 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
10953                                unsigned Type, const LValue &LVal,
10954                                CharUnits &EndOffset) {
10955   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
10956 
10957   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
10958     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
10959       return false;
10960     return HandleSizeof(Info, ExprLoc, Ty, Result);
10961   };
10962 
10963   // We want to evaluate the size of the entire object. This is a valid fallback
10964   // for when Type=1 and the designator is invalid, because we're asked for an
10965   // upper-bound.
10966   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
10967     // Type=3 wants a lower bound, so we can't fall back to this.
10968     if (Type == 3 && !DetermineForCompleteObject)
10969       return false;
10970 
10971     llvm::APInt APEndOffset;
10972     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10973         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10974       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10975 
10976     if (LVal.InvalidBase)
10977       return false;
10978 
10979     QualType BaseTy = getObjectType(LVal.getLValueBase());
10980     return CheckedHandleSizeof(BaseTy, EndOffset);
10981   }
10982 
10983   // We want to evaluate the size of a subobject.
10984   const SubobjectDesignator &Designator = LVal.Designator;
10985 
10986   // The following is a moderately common idiom in C:
10987   //
10988   // struct Foo { int a; char c[1]; };
10989   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
10990   // strcpy(&F->c[0], Bar);
10991   //
10992   // In order to not break too much legacy code, we need to support it.
10993   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
10994     // If we can resolve this to an alloc_size call, we can hand that back,
10995     // because we know for certain how many bytes there are to write to.
10996     llvm::APInt APEndOffset;
10997     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10998         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10999       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11000 
11001     // If we cannot determine the size of the initial allocation, then we can't
11002     // given an accurate upper-bound. However, we are still able to give
11003     // conservative lower-bounds for Type=3.
11004     if (Type == 1)
11005       return false;
11006   }
11007 
11008   CharUnits BytesPerElem;
11009   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11010     return false;
11011 
11012   // According to the GCC documentation, we want the size of the subobject
11013   // denoted by the pointer. But that's not quite right -- what we actually
11014   // want is the size of the immediately-enclosing array, if there is one.
11015   int64_t ElemsRemaining;
11016   if (Designator.MostDerivedIsArrayElement &&
11017       Designator.Entries.size() == Designator.MostDerivedPathLength) {
11018     uint64_t ArraySize = Designator.getMostDerivedArraySize();
11019     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11020     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11021   } else {
11022     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11023   }
11024 
11025   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11026   return true;
11027 }
11028 
11029 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11030 /// returns true and stores the result in @p Size.
11031 ///
11032 /// If @p WasError is non-null, this will report whether the failure to evaluate
11033 /// is to be treated as an Error in IntExprEvaluator.
11034 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11035                                          EvalInfo &Info, uint64_t &Size) {
11036   // Determine the denoted object.
11037   LValue LVal;
11038   {
11039     // The operand of __builtin_object_size is never evaluated for side-effects.
11040     // If there are any, but we can determine the pointed-to object anyway, then
11041     // ignore the side-effects.
11042     SpeculativeEvaluationRAII SpeculativeEval(Info);
11043     IgnoreSideEffectsRAII Fold(Info);
11044 
11045     if (E->isGLValue()) {
11046       // It's possible for us to be given GLValues if we're called via
11047       // Expr::tryEvaluateObjectSize.
11048       APValue RVal;
11049       if (!EvaluateAsRValue(Info, E, RVal))
11050         return false;
11051       LVal.setFrom(Info.Ctx, RVal);
11052     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11053                                 /*InvalidBaseOK=*/true))
11054       return false;
11055   }
11056 
11057   // If we point to before the start of the object, there are no accessible
11058   // bytes.
11059   if (LVal.getLValueOffset().isNegative()) {
11060     Size = 0;
11061     return true;
11062   }
11063 
11064   CharUnits EndOffset;
11065   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11066     return false;
11067 
11068   // If we've fallen outside of the end offset, just pretend there's nothing to
11069   // write to/read from.
11070   if (EndOffset <= LVal.getLValueOffset())
11071     Size = 0;
11072   else
11073     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11074   return true;
11075 }
11076 
11077 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11078   if (unsigned BuiltinOp = E->getBuiltinCallee())
11079     return VisitBuiltinCallExpr(E, BuiltinOp);
11080 
11081   return ExprEvaluatorBaseTy::VisitCallExpr(E);
11082 }
11083 
11084 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11085                                      APValue &Val, APSInt &Alignment) {
11086   QualType SrcTy = E->getArg(0)->getType();
11087   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11088     return false;
11089   // Even though we are evaluating integer expressions we could get a pointer
11090   // argument for the __builtin_is_aligned() case.
11091   if (SrcTy->isPointerType()) {
11092     LValue Ptr;
11093     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11094       return false;
11095     Ptr.moveInto(Val);
11096   } else if (!SrcTy->isIntegralOrEnumerationType()) {
11097     Info.FFDiag(E->getArg(0));
11098     return false;
11099   } else {
11100     APSInt SrcInt;
11101     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11102       return false;
11103     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11104            "Bit widths must be the same");
11105     Val = APValue(SrcInt);
11106   }
11107   assert(Val.hasValue());
11108   return true;
11109 }
11110 
11111 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11112                                             unsigned BuiltinOp) {
11113   switch (BuiltinOp) {
11114   default:
11115     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11116 
11117   case Builtin::BI__builtin_dynamic_object_size:
11118   case Builtin::BI__builtin_object_size: {
11119     // The type was checked when we built the expression.
11120     unsigned Type =
11121         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11122     assert(Type <= 3 && "unexpected type");
11123 
11124     uint64_t Size;
11125     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11126       return Success(Size, E);
11127 
11128     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11129       return Success((Type & 2) ? 0 : -1, E);
11130 
11131     // Expression had no side effects, but we couldn't statically determine the
11132     // size of the referenced object.
11133     switch (Info.EvalMode) {
11134     case EvalInfo::EM_ConstantExpression:
11135     case EvalInfo::EM_ConstantFold:
11136     case EvalInfo::EM_IgnoreSideEffects:
11137       // Leave it to IR generation.
11138       return Error(E);
11139     case EvalInfo::EM_ConstantExpressionUnevaluated:
11140       // Reduce it to a constant now.
11141       return Success((Type & 2) ? 0 : -1, E);
11142     }
11143 
11144     llvm_unreachable("unexpected EvalMode");
11145   }
11146 
11147   case Builtin::BI__builtin_os_log_format_buffer_size: {
11148     analyze_os_log::OSLogBufferLayout Layout;
11149     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11150     return Success(Layout.size().getQuantity(), E);
11151   }
11152 
11153   case Builtin::BI__builtin_is_aligned: {
11154     APValue Src;
11155     APSInt Alignment;
11156     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11157       return false;
11158     if (Src.isLValue()) {
11159       // If we evaluated a pointer, check the minimum known alignment.
11160       LValue Ptr;
11161       Ptr.setFrom(Info.Ctx, Src);
11162       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11163       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11164       // We can return true if the known alignment at the computed offset is
11165       // greater than the requested alignment.
11166       assert(PtrAlign.isPowerOfTwo());
11167       assert(Alignment.isPowerOf2());
11168       if (PtrAlign.getQuantity() >= Alignment)
11169         return Success(1, E);
11170       // If the alignment is not known to be sufficient, some cases could still
11171       // be aligned at run time. However, if the requested alignment is less or
11172       // equal to the base alignment and the offset is not aligned, we know that
11173       // the run-time value can never be aligned.
11174       if (BaseAlignment.getQuantity() >= Alignment &&
11175           PtrAlign.getQuantity() < Alignment)
11176         return Success(0, E);
11177       // Otherwise we can't infer whether the value is sufficiently aligned.
11178       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11179       //  in cases where we can't fully evaluate the pointer.
11180       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11181           << Alignment;
11182       return false;
11183     }
11184     assert(Src.isInt());
11185     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11186   }
11187   case Builtin::BI__builtin_align_up: {
11188     APValue Src;
11189     APSInt Alignment;
11190     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11191       return false;
11192     if (!Src.isInt())
11193       return Error(E);
11194     APSInt AlignedVal =
11195         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11196                Src.getInt().isUnsigned());
11197     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11198     return Success(AlignedVal, E);
11199   }
11200   case Builtin::BI__builtin_align_down: {
11201     APValue Src;
11202     APSInt Alignment;
11203     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11204       return false;
11205     if (!Src.isInt())
11206       return Error(E);
11207     APSInt AlignedVal =
11208         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11209     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11210     return Success(AlignedVal, E);
11211   }
11212 
11213   case Builtin::BI__builtin_bitreverse8:
11214   case Builtin::BI__builtin_bitreverse16:
11215   case Builtin::BI__builtin_bitreverse32:
11216   case Builtin::BI__builtin_bitreverse64: {
11217     APSInt Val;
11218     if (!EvaluateInteger(E->getArg(0), Val, Info))
11219       return false;
11220 
11221     return Success(Val.reverseBits(), E);
11222   }
11223 
11224   case Builtin::BI__builtin_bswap16:
11225   case Builtin::BI__builtin_bswap32:
11226   case Builtin::BI__builtin_bswap64: {
11227     APSInt Val;
11228     if (!EvaluateInteger(E->getArg(0), Val, Info))
11229       return false;
11230 
11231     return Success(Val.byteSwap(), E);
11232   }
11233 
11234   case Builtin::BI__builtin_classify_type:
11235     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11236 
11237   case Builtin::BI__builtin_clrsb:
11238   case Builtin::BI__builtin_clrsbl:
11239   case Builtin::BI__builtin_clrsbll: {
11240     APSInt Val;
11241     if (!EvaluateInteger(E->getArg(0), Val, Info))
11242       return false;
11243 
11244     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11245   }
11246 
11247   case Builtin::BI__builtin_clz:
11248   case Builtin::BI__builtin_clzl:
11249   case Builtin::BI__builtin_clzll:
11250   case Builtin::BI__builtin_clzs: {
11251     APSInt Val;
11252     if (!EvaluateInteger(E->getArg(0), Val, Info))
11253       return false;
11254     if (!Val)
11255       return Error(E);
11256 
11257     return Success(Val.countLeadingZeros(), E);
11258   }
11259 
11260   case Builtin::BI__builtin_constant_p: {
11261     const Expr *Arg = E->getArg(0);
11262     if (EvaluateBuiltinConstantP(Info, Arg))
11263       return Success(true, E);
11264     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11265       // Outside a constant context, eagerly evaluate to false in the presence
11266       // of side-effects in order to avoid -Wunsequenced false-positives in
11267       // a branch on __builtin_constant_p(expr).
11268       return Success(false, E);
11269     }
11270     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11271     return false;
11272   }
11273 
11274   case Builtin::BI__builtin_is_constant_evaluated: {
11275     const auto *Callee = Info.CurrentCall->getCallee();
11276     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
11277         (Info.CallStackDepth == 1 ||
11278          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
11279           Callee->getIdentifier() &&
11280           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
11281       // FIXME: Find a better way to avoid duplicated diagnostics.
11282       if (Info.EvalStatus.Diag)
11283         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
11284                                                : Info.CurrentCall->CallLoc,
11285                     diag::warn_is_constant_evaluated_always_true_constexpr)
11286             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
11287                                          : "std::is_constant_evaluated");
11288     }
11289 
11290     return Success(Info.InConstantContext, E);
11291   }
11292 
11293   case Builtin::BI__builtin_ctz:
11294   case Builtin::BI__builtin_ctzl:
11295   case Builtin::BI__builtin_ctzll:
11296   case Builtin::BI__builtin_ctzs: {
11297     APSInt Val;
11298     if (!EvaluateInteger(E->getArg(0), Val, Info))
11299       return false;
11300     if (!Val)
11301       return Error(E);
11302 
11303     return Success(Val.countTrailingZeros(), E);
11304   }
11305 
11306   case Builtin::BI__builtin_eh_return_data_regno: {
11307     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11308     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
11309     return Success(Operand, E);
11310   }
11311 
11312   case Builtin::BI__builtin_expect:
11313   case Builtin::BI__builtin_expect_with_probability:
11314     return Visit(E->getArg(0));
11315 
11316   case Builtin::BI__builtin_ffs:
11317   case Builtin::BI__builtin_ffsl:
11318   case Builtin::BI__builtin_ffsll: {
11319     APSInt Val;
11320     if (!EvaluateInteger(E->getArg(0), Val, Info))
11321       return false;
11322 
11323     unsigned N = Val.countTrailingZeros();
11324     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
11325   }
11326 
11327   case Builtin::BI__builtin_fpclassify: {
11328     APFloat Val(0.0);
11329     if (!EvaluateFloat(E->getArg(5), Val, Info))
11330       return false;
11331     unsigned Arg;
11332     switch (Val.getCategory()) {
11333     case APFloat::fcNaN: Arg = 0; break;
11334     case APFloat::fcInfinity: Arg = 1; break;
11335     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
11336     case APFloat::fcZero: Arg = 4; break;
11337     }
11338     return Visit(E->getArg(Arg));
11339   }
11340 
11341   case Builtin::BI__builtin_isinf_sign: {
11342     APFloat Val(0.0);
11343     return EvaluateFloat(E->getArg(0), Val, Info) &&
11344            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
11345   }
11346 
11347   case Builtin::BI__builtin_isinf: {
11348     APFloat Val(0.0);
11349     return EvaluateFloat(E->getArg(0), Val, Info) &&
11350            Success(Val.isInfinity() ? 1 : 0, E);
11351   }
11352 
11353   case Builtin::BI__builtin_isfinite: {
11354     APFloat Val(0.0);
11355     return EvaluateFloat(E->getArg(0), Val, Info) &&
11356            Success(Val.isFinite() ? 1 : 0, E);
11357   }
11358 
11359   case Builtin::BI__builtin_isnan: {
11360     APFloat Val(0.0);
11361     return EvaluateFloat(E->getArg(0), Val, Info) &&
11362            Success(Val.isNaN() ? 1 : 0, E);
11363   }
11364 
11365   case Builtin::BI__builtin_isnormal: {
11366     APFloat Val(0.0);
11367     return EvaluateFloat(E->getArg(0), Val, Info) &&
11368            Success(Val.isNormal() ? 1 : 0, E);
11369   }
11370 
11371   case Builtin::BI__builtin_parity:
11372   case Builtin::BI__builtin_parityl:
11373   case Builtin::BI__builtin_parityll: {
11374     APSInt Val;
11375     if (!EvaluateInteger(E->getArg(0), Val, Info))
11376       return false;
11377 
11378     return Success(Val.countPopulation() % 2, E);
11379   }
11380 
11381   case Builtin::BI__builtin_popcount:
11382   case Builtin::BI__builtin_popcountl:
11383   case Builtin::BI__builtin_popcountll: {
11384     APSInt Val;
11385     if (!EvaluateInteger(E->getArg(0), Val, Info))
11386       return false;
11387 
11388     return Success(Val.countPopulation(), E);
11389   }
11390 
11391   case Builtin::BI__builtin_rotateleft8:
11392   case Builtin::BI__builtin_rotateleft16:
11393   case Builtin::BI__builtin_rotateleft32:
11394   case Builtin::BI__builtin_rotateleft64:
11395   case Builtin::BI_rotl8: // Microsoft variants of rotate right
11396   case Builtin::BI_rotl16:
11397   case Builtin::BI_rotl:
11398   case Builtin::BI_lrotl:
11399   case Builtin::BI_rotl64: {
11400     APSInt Val, Amt;
11401     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11402         !EvaluateInteger(E->getArg(1), Amt, Info))
11403       return false;
11404 
11405     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
11406   }
11407 
11408   case Builtin::BI__builtin_rotateright8:
11409   case Builtin::BI__builtin_rotateright16:
11410   case Builtin::BI__builtin_rotateright32:
11411   case Builtin::BI__builtin_rotateright64:
11412   case Builtin::BI_rotr8: // Microsoft variants of rotate right
11413   case Builtin::BI_rotr16:
11414   case Builtin::BI_rotr:
11415   case Builtin::BI_lrotr:
11416   case Builtin::BI_rotr64: {
11417     APSInt Val, Amt;
11418     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11419         !EvaluateInteger(E->getArg(1), Amt, Info))
11420       return false;
11421 
11422     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
11423   }
11424 
11425   case Builtin::BIstrlen:
11426   case Builtin::BIwcslen:
11427     // A call to strlen is not a constant expression.
11428     if (Info.getLangOpts().CPlusPlus11)
11429       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11430         << /*isConstexpr*/0 << /*isConstructor*/0
11431         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11432     else
11433       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11434     LLVM_FALLTHROUGH;
11435   case Builtin::BI__builtin_strlen:
11436   case Builtin::BI__builtin_wcslen: {
11437     // As an extension, we support __builtin_strlen() as a constant expression,
11438     // and support folding strlen() to a constant.
11439     LValue String;
11440     if (!EvaluatePointer(E->getArg(0), String, Info))
11441       return false;
11442 
11443     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
11444 
11445     // Fast path: if it's a string literal, search the string value.
11446     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
11447             String.getLValueBase().dyn_cast<const Expr *>())) {
11448       // The string literal may have embedded null characters. Find the first
11449       // one and truncate there.
11450       StringRef Str = S->getBytes();
11451       int64_t Off = String.Offset.getQuantity();
11452       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
11453           S->getCharByteWidth() == 1 &&
11454           // FIXME: Add fast-path for wchar_t too.
11455           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
11456         Str = Str.substr(Off);
11457 
11458         StringRef::size_type Pos = Str.find(0);
11459         if (Pos != StringRef::npos)
11460           Str = Str.substr(0, Pos);
11461 
11462         return Success(Str.size(), E);
11463       }
11464 
11465       // Fall through to slow path to issue appropriate diagnostic.
11466     }
11467 
11468     // Slow path: scan the bytes of the string looking for the terminating 0.
11469     for (uint64_t Strlen = 0; /**/; ++Strlen) {
11470       APValue Char;
11471       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
11472           !Char.isInt())
11473         return false;
11474       if (!Char.getInt())
11475         return Success(Strlen, E);
11476       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
11477         return false;
11478     }
11479   }
11480 
11481   case Builtin::BIstrcmp:
11482   case Builtin::BIwcscmp:
11483   case Builtin::BIstrncmp:
11484   case Builtin::BIwcsncmp:
11485   case Builtin::BImemcmp:
11486   case Builtin::BIbcmp:
11487   case Builtin::BIwmemcmp:
11488     // A call to strlen is not a constant expression.
11489     if (Info.getLangOpts().CPlusPlus11)
11490       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11491         << /*isConstexpr*/0 << /*isConstructor*/0
11492         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11493     else
11494       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11495     LLVM_FALLTHROUGH;
11496   case Builtin::BI__builtin_strcmp:
11497   case Builtin::BI__builtin_wcscmp:
11498   case Builtin::BI__builtin_strncmp:
11499   case Builtin::BI__builtin_wcsncmp:
11500   case Builtin::BI__builtin_memcmp:
11501   case Builtin::BI__builtin_bcmp:
11502   case Builtin::BI__builtin_wmemcmp: {
11503     LValue String1, String2;
11504     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
11505         !EvaluatePointer(E->getArg(1), String2, Info))
11506       return false;
11507 
11508     uint64_t MaxLength = uint64_t(-1);
11509     if (BuiltinOp != Builtin::BIstrcmp &&
11510         BuiltinOp != Builtin::BIwcscmp &&
11511         BuiltinOp != Builtin::BI__builtin_strcmp &&
11512         BuiltinOp != Builtin::BI__builtin_wcscmp) {
11513       APSInt N;
11514       if (!EvaluateInteger(E->getArg(2), N, Info))
11515         return false;
11516       MaxLength = N.getExtValue();
11517     }
11518 
11519     // Empty substrings compare equal by definition.
11520     if (MaxLength == 0u)
11521       return Success(0, E);
11522 
11523     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11524         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11525         String1.Designator.Invalid || String2.Designator.Invalid)
11526       return false;
11527 
11528     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
11529     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
11530 
11531     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
11532                      BuiltinOp == Builtin::BIbcmp ||
11533                      BuiltinOp == Builtin::BI__builtin_memcmp ||
11534                      BuiltinOp == Builtin::BI__builtin_bcmp;
11535 
11536     assert(IsRawByte ||
11537            (Info.Ctx.hasSameUnqualifiedType(
11538                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
11539             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
11540 
11541     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
11542     // 'char8_t', but no other types.
11543     if (IsRawByte &&
11544         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
11545       // FIXME: Consider using our bit_cast implementation to support this.
11546       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
11547           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
11548           << CharTy1 << CharTy2;
11549       return false;
11550     }
11551 
11552     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
11553       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
11554              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
11555              Char1.isInt() && Char2.isInt();
11556     };
11557     const auto &AdvanceElems = [&] {
11558       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
11559              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
11560     };
11561 
11562     bool StopAtNull =
11563         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
11564          BuiltinOp != Builtin::BIwmemcmp &&
11565          BuiltinOp != Builtin::BI__builtin_memcmp &&
11566          BuiltinOp != Builtin::BI__builtin_bcmp &&
11567          BuiltinOp != Builtin::BI__builtin_wmemcmp);
11568     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
11569                   BuiltinOp == Builtin::BIwcsncmp ||
11570                   BuiltinOp == Builtin::BIwmemcmp ||
11571                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
11572                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
11573                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
11574 
11575     for (; MaxLength; --MaxLength) {
11576       APValue Char1, Char2;
11577       if (!ReadCurElems(Char1, Char2))
11578         return false;
11579       if (Char1.getInt().ne(Char2.getInt())) {
11580         if (IsWide) // wmemcmp compares with wchar_t signedness.
11581           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
11582         // memcmp always compares unsigned chars.
11583         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
11584       }
11585       if (StopAtNull && !Char1.getInt())
11586         return Success(0, E);
11587       assert(!(StopAtNull && !Char2.getInt()));
11588       if (!AdvanceElems())
11589         return false;
11590     }
11591     // We hit the strncmp / memcmp limit.
11592     return Success(0, E);
11593   }
11594 
11595   case Builtin::BI__atomic_always_lock_free:
11596   case Builtin::BI__atomic_is_lock_free:
11597   case Builtin::BI__c11_atomic_is_lock_free: {
11598     APSInt SizeVal;
11599     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
11600       return false;
11601 
11602     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
11603     // of two less than or equal to the maximum inline atomic width, we know it
11604     // is lock-free.  If the size isn't a power of two, or greater than the
11605     // maximum alignment where we promote atomics, we know it is not lock-free
11606     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
11607     // the answer can only be determined at runtime; for example, 16-byte
11608     // atomics have lock-free implementations on some, but not all,
11609     // x86-64 processors.
11610 
11611     // Check power-of-two.
11612     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
11613     if (Size.isPowerOfTwo()) {
11614       // Check against inlining width.
11615       unsigned InlineWidthBits =
11616           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
11617       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
11618         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
11619             Size == CharUnits::One() ||
11620             E->getArg(1)->isNullPointerConstant(Info.Ctx,
11621                                                 Expr::NPC_NeverValueDependent))
11622           // OK, we will inline appropriately-aligned operations of this size,
11623           // and _Atomic(T) is appropriately-aligned.
11624           return Success(1, E);
11625 
11626         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
11627           castAs<PointerType>()->getPointeeType();
11628         if (!PointeeType->isIncompleteType() &&
11629             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
11630           // OK, we will inline operations on this object.
11631           return Success(1, E);
11632         }
11633       }
11634     }
11635 
11636     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
11637         Success(0, E) : Error(E);
11638   }
11639   case Builtin::BIomp_is_initial_device:
11640     // We can decide statically which value the runtime would return if called.
11641     return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
11642   case Builtin::BI__builtin_add_overflow:
11643   case Builtin::BI__builtin_sub_overflow:
11644   case Builtin::BI__builtin_mul_overflow:
11645   case Builtin::BI__builtin_sadd_overflow:
11646   case Builtin::BI__builtin_uadd_overflow:
11647   case Builtin::BI__builtin_uaddl_overflow:
11648   case Builtin::BI__builtin_uaddll_overflow:
11649   case Builtin::BI__builtin_usub_overflow:
11650   case Builtin::BI__builtin_usubl_overflow:
11651   case Builtin::BI__builtin_usubll_overflow:
11652   case Builtin::BI__builtin_umul_overflow:
11653   case Builtin::BI__builtin_umull_overflow:
11654   case Builtin::BI__builtin_umulll_overflow:
11655   case Builtin::BI__builtin_saddl_overflow:
11656   case Builtin::BI__builtin_saddll_overflow:
11657   case Builtin::BI__builtin_ssub_overflow:
11658   case Builtin::BI__builtin_ssubl_overflow:
11659   case Builtin::BI__builtin_ssubll_overflow:
11660   case Builtin::BI__builtin_smul_overflow:
11661   case Builtin::BI__builtin_smull_overflow:
11662   case Builtin::BI__builtin_smulll_overflow: {
11663     LValue ResultLValue;
11664     APSInt LHS, RHS;
11665 
11666     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
11667     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
11668         !EvaluateInteger(E->getArg(1), RHS, Info) ||
11669         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
11670       return false;
11671 
11672     APSInt Result;
11673     bool DidOverflow = false;
11674 
11675     // If the types don't have to match, enlarge all 3 to the largest of them.
11676     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11677         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11678         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11679       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
11680                       ResultType->isSignedIntegerOrEnumerationType();
11681       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
11682                       ResultType->isSignedIntegerOrEnumerationType();
11683       uint64_t LHSSize = LHS.getBitWidth();
11684       uint64_t RHSSize = RHS.getBitWidth();
11685       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
11686       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
11687 
11688       // Add an additional bit if the signedness isn't uniformly agreed to. We
11689       // could do this ONLY if there is a signed and an unsigned that both have
11690       // MaxBits, but the code to check that is pretty nasty.  The issue will be
11691       // caught in the shrink-to-result later anyway.
11692       if (IsSigned && !AllSigned)
11693         ++MaxBits;
11694 
11695       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
11696       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
11697       Result = APSInt(MaxBits, !IsSigned);
11698     }
11699 
11700     // Find largest int.
11701     switch (BuiltinOp) {
11702     default:
11703       llvm_unreachable("Invalid value for BuiltinOp");
11704     case Builtin::BI__builtin_add_overflow:
11705     case Builtin::BI__builtin_sadd_overflow:
11706     case Builtin::BI__builtin_saddl_overflow:
11707     case Builtin::BI__builtin_saddll_overflow:
11708     case Builtin::BI__builtin_uadd_overflow:
11709     case Builtin::BI__builtin_uaddl_overflow:
11710     case Builtin::BI__builtin_uaddll_overflow:
11711       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
11712                               : LHS.uadd_ov(RHS, DidOverflow);
11713       break;
11714     case Builtin::BI__builtin_sub_overflow:
11715     case Builtin::BI__builtin_ssub_overflow:
11716     case Builtin::BI__builtin_ssubl_overflow:
11717     case Builtin::BI__builtin_ssubll_overflow:
11718     case Builtin::BI__builtin_usub_overflow:
11719     case Builtin::BI__builtin_usubl_overflow:
11720     case Builtin::BI__builtin_usubll_overflow:
11721       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
11722                               : LHS.usub_ov(RHS, DidOverflow);
11723       break;
11724     case Builtin::BI__builtin_mul_overflow:
11725     case Builtin::BI__builtin_smul_overflow:
11726     case Builtin::BI__builtin_smull_overflow:
11727     case Builtin::BI__builtin_smulll_overflow:
11728     case Builtin::BI__builtin_umul_overflow:
11729     case Builtin::BI__builtin_umull_overflow:
11730     case Builtin::BI__builtin_umulll_overflow:
11731       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
11732                               : LHS.umul_ov(RHS, DidOverflow);
11733       break;
11734     }
11735 
11736     // In the case where multiple sizes are allowed, truncate and see if
11737     // the values are the same.
11738     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11739         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11740         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11741       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
11742       // since it will give us the behavior of a TruncOrSelf in the case where
11743       // its parameter <= its size.  We previously set Result to be at least the
11744       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
11745       // will work exactly like TruncOrSelf.
11746       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
11747       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
11748 
11749       if (!APSInt::isSameValue(Temp, Result))
11750         DidOverflow = true;
11751       Result = Temp;
11752     }
11753 
11754     APValue APV{Result};
11755     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
11756       return false;
11757     return Success(DidOverflow, E);
11758   }
11759   }
11760 }
11761 
11762 /// Determine whether this is a pointer past the end of the complete
11763 /// object referred to by the lvalue.
11764 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
11765                                             const LValue &LV) {
11766   // A null pointer can be viewed as being "past the end" but we don't
11767   // choose to look at it that way here.
11768   if (!LV.getLValueBase())
11769     return false;
11770 
11771   // If the designator is valid and refers to a subobject, we're not pointing
11772   // past the end.
11773   if (!LV.getLValueDesignator().Invalid &&
11774       !LV.getLValueDesignator().isOnePastTheEnd())
11775     return false;
11776 
11777   // A pointer to an incomplete type might be past-the-end if the type's size is
11778   // zero.  We cannot tell because the type is incomplete.
11779   QualType Ty = getType(LV.getLValueBase());
11780   if (Ty->isIncompleteType())
11781     return true;
11782 
11783   // We're a past-the-end pointer if we point to the byte after the object,
11784   // no matter what our type or path is.
11785   auto Size = Ctx.getTypeSizeInChars(Ty);
11786   return LV.getLValueOffset() == Size;
11787 }
11788 
11789 namespace {
11790 
11791 /// Data recursive integer evaluator of certain binary operators.
11792 ///
11793 /// We use a data recursive algorithm for binary operators so that we are able
11794 /// to handle extreme cases of chained binary operators without causing stack
11795 /// overflow.
11796 class DataRecursiveIntBinOpEvaluator {
11797   struct EvalResult {
11798     APValue Val;
11799     bool Failed;
11800 
11801     EvalResult() : Failed(false) { }
11802 
11803     void swap(EvalResult &RHS) {
11804       Val.swap(RHS.Val);
11805       Failed = RHS.Failed;
11806       RHS.Failed = false;
11807     }
11808   };
11809 
11810   struct Job {
11811     const Expr *E;
11812     EvalResult LHSResult; // meaningful only for binary operator expression.
11813     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
11814 
11815     Job() = default;
11816     Job(Job &&) = default;
11817 
11818     void startSpeculativeEval(EvalInfo &Info) {
11819       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
11820     }
11821 
11822   private:
11823     SpeculativeEvaluationRAII SpecEvalRAII;
11824   };
11825 
11826   SmallVector<Job, 16> Queue;
11827 
11828   IntExprEvaluator &IntEval;
11829   EvalInfo &Info;
11830   APValue &FinalResult;
11831 
11832 public:
11833   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
11834     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
11835 
11836   /// True if \param E is a binary operator that we are going to handle
11837   /// data recursively.
11838   /// We handle binary operators that are comma, logical, or that have operands
11839   /// with integral or enumeration type.
11840   static bool shouldEnqueue(const BinaryOperator *E) {
11841     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
11842            (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
11843             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11844             E->getRHS()->getType()->isIntegralOrEnumerationType());
11845   }
11846 
11847   bool Traverse(const BinaryOperator *E) {
11848     enqueue(E);
11849     EvalResult PrevResult;
11850     while (!Queue.empty())
11851       process(PrevResult);
11852 
11853     if (PrevResult.Failed) return false;
11854 
11855     FinalResult.swap(PrevResult.Val);
11856     return true;
11857   }
11858 
11859 private:
11860   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11861     return IntEval.Success(Value, E, Result);
11862   }
11863   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
11864     return IntEval.Success(Value, E, Result);
11865   }
11866   bool Error(const Expr *E) {
11867     return IntEval.Error(E);
11868   }
11869   bool Error(const Expr *E, diag::kind D) {
11870     return IntEval.Error(E, D);
11871   }
11872 
11873   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
11874     return Info.CCEDiag(E, D);
11875   }
11876 
11877   // Returns true if visiting the RHS is necessary, false otherwise.
11878   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
11879                          bool &SuppressRHSDiags);
11880 
11881   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
11882                   const BinaryOperator *E, APValue &Result);
11883 
11884   void EvaluateExpr(const Expr *E, EvalResult &Result) {
11885     Result.Failed = !Evaluate(Result.Val, Info, E);
11886     if (Result.Failed)
11887       Result.Val = APValue();
11888   }
11889 
11890   void process(EvalResult &Result);
11891 
11892   void enqueue(const Expr *E) {
11893     E = E->IgnoreParens();
11894     Queue.resize(Queue.size()+1);
11895     Queue.back().E = E;
11896     Queue.back().Kind = Job::AnyExprKind;
11897   }
11898 };
11899 
11900 }
11901 
11902 bool DataRecursiveIntBinOpEvaluator::
11903        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
11904                          bool &SuppressRHSDiags) {
11905   if (E->getOpcode() == BO_Comma) {
11906     // Ignore LHS but note if we could not evaluate it.
11907     if (LHSResult.Failed)
11908       return Info.noteSideEffect();
11909     return true;
11910   }
11911 
11912   if (E->isLogicalOp()) {
11913     bool LHSAsBool;
11914     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
11915       // We were able to evaluate the LHS, see if we can get away with not
11916       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
11917       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
11918         Success(LHSAsBool, E, LHSResult.Val);
11919         return false; // Ignore RHS
11920       }
11921     } else {
11922       LHSResult.Failed = true;
11923 
11924       // Since we weren't able to evaluate the left hand side, it
11925       // might have had side effects.
11926       if (!Info.noteSideEffect())
11927         return false;
11928 
11929       // We can't evaluate the LHS; however, sometimes the result
11930       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
11931       // Don't ignore RHS and suppress diagnostics from this arm.
11932       SuppressRHSDiags = true;
11933     }
11934 
11935     return true;
11936   }
11937 
11938   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11939          E->getRHS()->getType()->isIntegralOrEnumerationType());
11940 
11941   if (LHSResult.Failed && !Info.noteFailure())
11942     return false; // Ignore RHS;
11943 
11944   return true;
11945 }
11946 
11947 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
11948                                     bool IsSub) {
11949   // Compute the new offset in the appropriate width, wrapping at 64 bits.
11950   // FIXME: When compiling for a 32-bit target, we should use 32-bit
11951   // offsets.
11952   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
11953   CharUnits &Offset = LVal.getLValueOffset();
11954   uint64_t Offset64 = Offset.getQuantity();
11955   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
11956   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
11957                                          : Offset64 + Index64);
11958 }
11959 
11960 bool DataRecursiveIntBinOpEvaluator::
11961        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
11962                   const BinaryOperator *E, APValue &Result) {
11963   if (E->getOpcode() == BO_Comma) {
11964     if (RHSResult.Failed)
11965       return false;
11966     Result = RHSResult.Val;
11967     return true;
11968   }
11969 
11970   if (E->isLogicalOp()) {
11971     bool lhsResult, rhsResult;
11972     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
11973     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
11974 
11975     if (LHSIsOK) {
11976       if (RHSIsOK) {
11977         if (E->getOpcode() == BO_LOr)
11978           return Success(lhsResult || rhsResult, E, Result);
11979         else
11980           return Success(lhsResult && rhsResult, E, Result);
11981       }
11982     } else {
11983       if (RHSIsOK) {
11984         // We can't evaluate the LHS; however, sometimes the result
11985         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
11986         if (rhsResult == (E->getOpcode() == BO_LOr))
11987           return Success(rhsResult, E, Result);
11988       }
11989     }
11990 
11991     return false;
11992   }
11993 
11994   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11995          E->getRHS()->getType()->isIntegralOrEnumerationType());
11996 
11997   if (LHSResult.Failed || RHSResult.Failed)
11998     return false;
11999 
12000   const APValue &LHSVal = LHSResult.Val;
12001   const APValue &RHSVal = RHSResult.Val;
12002 
12003   // Handle cases like (unsigned long)&a + 4.
12004   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12005     Result = LHSVal;
12006     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12007     return true;
12008   }
12009 
12010   // Handle cases like 4 + (unsigned long)&a
12011   if (E->getOpcode() == BO_Add &&
12012       RHSVal.isLValue() && LHSVal.isInt()) {
12013     Result = RHSVal;
12014     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12015     return true;
12016   }
12017 
12018   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12019     // Handle (intptr_t)&&A - (intptr_t)&&B.
12020     if (!LHSVal.getLValueOffset().isZero() ||
12021         !RHSVal.getLValueOffset().isZero())
12022       return false;
12023     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12024     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12025     if (!LHSExpr || !RHSExpr)
12026       return false;
12027     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12028     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12029     if (!LHSAddrExpr || !RHSAddrExpr)
12030       return false;
12031     // Make sure both labels come from the same function.
12032     if (LHSAddrExpr->getLabel()->getDeclContext() !=
12033         RHSAddrExpr->getLabel()->getDeclContext())
12034       return false;
12035     Result = APValue(LHSAddrExpr, RHSAddrExpr);
12036     return true;
12037   }
12038 
12039   // All the remaining cases expect both operands to be an integer
12040   if (!LHSVal.isInt() || !RHSVal.isInt())
12041     return Error(E);
12042 
12043   // Set up the width and signedness manually, in case it can't be deduced
12044   // from the operation we're performing.
12045   // FIXME: Don't do this in the cases where we can deduce it.
12046   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12047                E->getType()->isUnsignedIntegerOrEnumerationType());
12048   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12049                          RHSVal.getInt(), Value))
12050     return false;
12051   return Success(Value, E, Result);
12052 }
12053 
12054 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12055   Job &job = Queue.back();
12056 
12057   switch (job.Kind) {
12058     case Job::AnyExprKind: {
12059       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12060         if (shouldEnqueue(Bop)) {
12061           job.Kind = Job::BinOpKind;
12062           enqueue(Bop->getLHS());
12063           return;
12064         }
12065       }
12066 
12067       EvaluateExpr(job.E, Result);
12068       Queue.pop_back();
12069       return;
12070     }
12071 
12072     case Job::BinOpKind: {
12073       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12074       bool SuppressRHSDiags = false;
12075       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12076         Queue.pop_back();
12077         return;
12078       }
12079       if (SuppressRHSDiags)
12080         job.startSpeculativeEval(Info);
12081       job.LHSResult.swap(Result);
12082       job.Kind = Job::BinOpVisitedLHSKind;
12083       enqueue(Bop->getRHS());
12084       return;
12085     }
12086 
12087     case Job::BinOpVisitedLHSKind: {
12088       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12089       EvalResult RHS;
12090       RHS.swap(Result);
12091       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12092       Queue.pop_back();
12093       return;
12094     }
12095   }
12096 
12097   llvm_unreachable("Invalid Job::Kind!");
12098 }
12099 
12100 namespace {
12101 /// Used when we determine that we should fail, but can keep evaluating prior to
12102 /// noting that we had a failure.
12103 class DelayedNoteFailureRAII {
12104   EvalInfo &Info;
12105   bool NoteFailure;
12106 
12107 public:
12108   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
12109       : Info(Info), NoteFailure(NoteFailure) {}
12110   ~DelayedNoteFailureRAII() {
12111     if (NoteFailure) {
12112       bool ContinueAfterFailure = Info.noteFailure();
12113       (void)ContinueAfterFailure;
12114       assert(ContinueAfterFailure &&
12115              "Shouldn't have kept evaluating on failure.");
12116     }
12117   }
12118 };
12119 
12120 enum class CmpResult {
12121   Unequal,
12122   Less,
12123   Equal,
12124   Greater,
12125   Unordered,
12126 };
12127 }
12128 
12129 template <class SuccessCB, class AfterCB>
12130 static bool
12131 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12132                                  SuccessCB &&Success, AfterCB &&DoAfter) {
12133   assert(E->isComparisonOp() && "expected comparison operator");
12134   assert((E->getOpcode() == BO_Cmp ||
12135           E->getType()->isIntegralOrEnumerationType()) &&
12136          "unsupported binary expression evaluation");
12137   auto Error = [&](const Expr *E) {
12138     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12139     return false;
12140   };
12141 
12142   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12143   bool IsEquality = E->isEqualityOp();
12144 
12145   QualType LHSTy = E->getLHS()->getType();
12146   QualType RHSTy = E->getRHS()->getType();
12147 
12148   if (LHSTy->isIntegralOrEnumerationType() &&
12149       RHSTy->isIntegralOrEnumerationType()) {
12150     APSInt LHS, RHS;
12151     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12152     if (!LHSOK && !Info.noteFailure())
12153       return false;
12154     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12155       return false;
12156     if (LHS < RHS)
12157       return Success(CmpResult::Less, E);
12158     if (LHS > RHS)
12159       return Success(CmpResult::Greater, E);
12160     return Success(CmpResult::Equal, E);
12161   }
12162 
12163   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12164     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12165     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12166 
12167     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12168     if (!LHSOK && !Info.noteFailure())
12169       return false;
12170     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12171       return false;
12172     if (LHSFX < RHSFX)
12173       return Success(CmpResult::Less, E);
12174     if (LHSFX > RHSFX)
12175       return Success(CmpResult::Greater, E);
12176     return Success(CmpResult::Equal, E);
12177   }
12178 
12179   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12180     ComplexValue LHS, RHS;
12181     bool LHSOK;
12182     if (E->isAssignmentOp()) {
12183       LValue LV;
12184       EvaluateLValue(E->getLHS(), LV, Info);
12185       LHSOK = false;
12186     } else if (LHSTy->isRealFloatingType()) {
12187       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12188       if (LHSOK) {
12189         LHS.makeComplexFloat();
12190         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12191       }
12192     } else {
12193       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12194     }
12195     if (!LHSOK && !Info.noteFailure())
12196       return false;
12197 
12198     if (E->getRHS()->getType()->isRealFloatingType()) {
12199       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12200         return false;
12201       RHS.makeComplexFloat();
12202       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12203     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12204       return false;
12205 
12206     if (LHS.isComplexFloat()) {
12207       APFloat::cmpResult CR_r =
12208         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12209       APFloat::cmpResult CR_i =
12210         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12211       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12212       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12213     } else {
12214       assert(IsEquality && "invalid complex comparison");
12215       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12216                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
12217       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12218     }
12219   }
12220 
12221   if (LHSTy->isRealFloatingType() &&
12222       RHSTy->isRealFloatingType()) {
12223     APFloat RHS(0.0), LHS(0.0);
12224 
12225     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12226     if (!LHSOK && !Info.noteFailure())
12227       return false;
12228 
12229     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12230       return false;
12231 
12232     assert(E->isComparisonOp() && "Invalid binary operator!");
12233     auto GetCmpRes = [&]() {
12234       switch (LHS.compare(RHS)) {
12235       case APFloat::cmpEqual:
12236         return CmpResult::Equal;
12237       case APFloat::cmpLessThan:
12238         return CmpResult::Less;
12239       case APFloat::cmpGreaterThan:
12240         return CmpResult::Greater;
12241       case APFloat::cmpUnordered:
12242         return CmpResult::Unordered;
12243       }
12244       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12245     };
12246     return Success(GetCmpRes(), E);
12247   }
12248 
12249   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12250     LValue LHSValue, RHSValue;
12251 
12252     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12253     if (!LHSOK && !Info.noteFailure())
12254       return false;
12255 
12256     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12257       return false;
12258 
12259     // Reject differing bases from the normal codepath; we special-case
12260     // comparisons to null.
12261     if (!HasSameBase(LHSValue, RHSValue)) {
12262       // Inequalities and subtractions between unrelated pointers have
12263       // unspecified or undefined behavior.
12264       if (!IsEquality) {
12265         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
12266         return false;
12267       }
12268       // A constant address may compare equal to the address of a symbol.
12269       // The one exception is that address of an object cannot compare equal
12270       // to a null pointer constant.
12271       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12272           (!RHSValue.Base && !RHSValue.Offset.isZero()))
12273         return Error(E);
12274       // It's implementation-defined whether distinct literals will have
12275       // distinct addresses. In clang, the result of such a comparison is
12276       // unspecified, so it is not a constant expression. However, we do know
12277       // that the address of a literal will be non-null.
12278       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12279           LHSValue.Base && RHSValue.Base)
12280         return Error(E);
12281       // We can't tell whether weak symbols will end up pointing to the same
12282       // object.
12283       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12284         return Error(E);
12285       // We can't compare the address of the start of one object with the
12286       // past-the-end address of another object, per C++ DR1652.
12287       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
12288            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
12289           (RHSValue.Base && RHSValue.Offset.isZero() &&
12290            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
12291         return Error(E);
12292       // We can't tell whether an object is at the same address as another
12293       // zero sized object.
12294       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12295           (LHSValue.Base && isZeroSized(RHSValue)))
12296         return Error(E);
12297       return Success(CmpResult::Unequal, E);
12298     }
12299 
12300     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12301     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12302 
12303     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12304     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12305 
12306     // C++11 [expr.rel]p3:
12307     //   Pointers to void (after pointer conversions) can be compared, with a
12308     //   result defined as follows: If both pointers represent the same
12309     //   address or are both the null pointer value, the result is true if the
12310     //   operator is <= or >= and false otherwise; otherwise the result is
12311     //   unspecified.
12312     // We interpret this as applying to pointers to *cv* void.
12313     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
12314       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
12315 
12316     // C++11 [expr.rel]p2:
12317     // - If two pointers point to non-static data members of the same object,
12318     //   or to subobjects or array elements fo such members, recursively, the
12319     //   pointer to the later declared member compares greater provided the
12320     //   two members have the same access control and provided their class is
12321     //   not a union.
12322     //   [...]
12323     // - Otherwise pointer comparisons are unspecified.
12324     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
12325       bool WasArrayIndex;
12326       unsigned Mismatch = FindDesignatorMismatch(
12327           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
12328       // At the point where the designators diverge, the comparison has a
12329       // specified value if:
12330       //  - we are comparing array indices
12331       //  - we are comparing fields of a union, or fields with the same access
12332       // Otherwise, the result is unspecified and thus the comparison is not a
12333       // constant expression.
12334       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
12335           Mismatch < RHSDesignator.Entries.size()) {
12336         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
12337         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
12338         if (!LF && !RF)
12339           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
12340         else if (!LF)
12341           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12342               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
12343               << RF->getParent() << RF;
12344         else if (!RF)
12345           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12346               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
12347               << LF->getParent() << LF;
12348         else if (!LF->getParent()->isUnion() &&
12349                  LF->getAccess() != RF->getAccess())
12350           Info.CCEDiag(E,
12351                        diag::note_constexpr_pointer_comparison_differing_access)
12352               << LF << LF->getAccess() << RF << RF->getAccess()
12353               << LF->getParent();
12354       }
12355     }
12356 
12357     // The comparison here must be unsigned, and performed with the same
12358     // width as the pointer.
12359     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
12360     uint64_t CompareLHS = LHSOffset.getQuantity();
12361     uint64_t CompareRHS = RHSOffset.getQuantity();
12362     assert(PtrSize <= 64 && "Unexpected pointer width");
12363     uint64_t Mask = ~0ULL >> (64 - PtrSize);
12364     CompareLHS &= Mask;
12365     CompareRHS &= Mask;
12366 
12367     // If there is a base and this is a relational operator, we can only
12368     // compare pointers within the object in question; otherwise, the result
12369     // depends on where the object is located in memory.
12370     if (!LHSValue.Base.isNull() && IsRelational) {
12371       QualType BaseTy = getType(LHSValue.Base);
12372       if (BaseTy->isIncompleteType())
12373         return Error(E);
12374       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
12375       uint64_t OffsetLimit = Size.getQuantity();
12376       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
12377         return Error(E);
12378     }
12379 
12380     if (CompareLHS < CompareRHS)
12381       return Success(CmpResult::Less, E);
12382     if (CompareLHS > CompareRHS)
12383       return Success(CmpResult::Greater, E);
12384     return Success(CmpResult::Equal, E);
12385   }
12386 
12387   if (LHSTy->isMemberPointerType()) {
12388     assert(IsEquality && "unexpected member pointer operation");
12389     assert(RHSTy->isMemberPointerType() && "invalid comparison");
12390 
12391     MemberPtr LHSValue, RHSValue;
12392 
12393     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
12394     if (!LHSOK && !Info.noteFailure())
12395       return false;
12396 
12397     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12398       return false;
12399 
12400     // C++11 [expr.eq]p2:
12401     //   If both operands are null, they compare equal. Otherwise if only one is
12402     //   null, they compare unequal.
12403     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
12404       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
12405       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12406     }
12407 
12408     //   Otherwise if either is a pointer to a virtual member function, the
12409     //   result is unspecified.
12410     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
12411       if (MD->isVirtual())
12412         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12413     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
12414       if (MD->isVirtual())
12415         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12416 
12417     //   Otherwise they compare equal if and only if they would refer to the
12418     //   same member of the same most derived object or the same subobject if
12419     //   they were dereferenced with a hypothetical object of the associated
12420     //   class type.
12421     bool Equal = LHSValue == RHSValue;
12422     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12423   }
12424 
12425   if (LHSTy->isNullPtrType()) {
12426     assert(E->isComparisonOp() && "unexpected nullptr operation");
12427     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12428     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12429     // are compared, the result is true of the operator is <=, >= or ==, and
12430     // false otherwise.
12431     return Success(CmpResult::Equal, E);
12432   }
12433 
12434   return DoAfter();
12435 }
12436 
12437 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
12438   if (!CheckLiteralType(Info, E))
12439     return false;
12440 
12441   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12442     ComparisonCategoryResult CCR;
12443     switch (CR) {
12444     case CmpResult::Unequal:
12445       llvm_unreachable("should never produce Unequal for three-way comparison");
12446     case CmpResult::Less:
12447       CCR = ComparisonCategoryResult::Less;
12448       break;
12449     case CmpResult::Equal:
12450       CCR = ComparisonCategoryResult::Equal;
12451       break;
12452     case CmpResult::Greater:
12453       CCR = ComparisonCategoryResult::Greater;
12454       break;
12455     case CmpResult::Unordered:
12456       CCR = ComparisonCategoryResult::Unordered;
12457       break;
12458     }
12459     // Evaluation succeeded. Lookup the information for the comparison category
12460     // type and fetch the VarDecl for the result.
12461     const ComparisonCategoryInfo &CmpInfo =
12462         Info.Ctx.CompCategories.getInfoForType(E->getType());
12463     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
12464     // Check and evaluate the result as a constant expression.
12465     LValue LV;
12466     LV.set(VD);
12467     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12468       return false;
12469     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
12470   };
12471   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12472     return ExprEvaluatorBaseTy::VisitBinCmp(E);
12473   });
12474 }
12475 
12476 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12477   // We don't call noteFailure immediately because the assignment happens after
12478   // we evaluate LHS and RHS.
12479   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
12480     return Error(E);
12481 
12482   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
12483   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
12484     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
12485 
12486   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
12487           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
12488          "DataRecursiveIntBinOpEvaluator should have handled integral types");
12489 
12490   if (E->isComparisonOp()) {
12491     // Evaluate builtin binary comparisons by evaluating them as three-way
12492     // comparisons and then translating the result.
12493     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12494       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
12495              "should only produce Unequal for equality comparisons");
12496       bool IsEqual   = CR == CmpResult::Equal,
12497            IsLess    = CR == CmpResult::Less,
12498            IsGreater = CR == CmpResult::Greater;
12499       auto Op = E->getOpcode();
12500       switch (Op) {
12501       default:
12502         llvm_unreachable("unsupported binary operator");
12503       case BO_EQ:
12504       case BO_NE:
12505         return Success(IsEqual == (Op == BO_EQ), E);
12506       case BO_LT:
12507         return Success(IsLess, E);
12508       case BO_GT:
12509         return Success(IsGreater, E);
12510       case BO_LE:
12511         return Success(IsEqual || IsLess, E);
12512       case BO_GE:
12513         return Success(IsEqual || IsGreater, E);
12514       }
12515     };
12516     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12517       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12518     });
12519   }
12520 
12521   QualType LHSTy = E->getLHS()->getType();
12522   QualType RHSTy = E->getRHS()->getType();
12523 
12524   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
12525       E->getOpcode() == BO_Sub) {
12526     LValue LHSValue, RHSValue;
12527 
12528     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12529     if (!LHSOK && !Info.noteFailure())
12530       return false;
12531 
12532     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12533       return false;
12534 
12535     // Reject differing bases from the normal codepath; we special-case
12536     // comparisons to null.
12537     if (!HasSameBase(LHSValue, RHSValue)) {
12538       // Handle &&A - &&B.
12539       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
12540         return Error(E);
12541       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
12542       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
12543       if (!LHSExpr || !RHSExpr)
12544         return Error(E);
12545       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12546       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12547       if (!LHSAddrExpr || !RHSAddrExpr)
12548         return Error(E);
12549       // Make sure both labels come from the same function.
12550       if (LHSAddrExpr->getLabel()->getDeclContext() !=
12551           RHSAddrExpr->getLabel()->getDeclContext())
12552         return Error(E);
12553       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
12554     }
12555     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12556     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12557 
12558     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12559     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12560 
12561     // C++11 [expr.add]p6:
12562     //   Unless both pointers point to elements of the same array object, or
12563     //   one past the last element of the array object, the behavior is
12564     //   undefined.
12565     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
12566         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
12567                                 RHSDesignator))
12568       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
12569 
12570     QualType Type = E->getLHS()->getType();
12571     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
12572 
12573     CharUnits ElementSize;
12574     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
12575       return false;
12576 
12577     // As an extension, a type may have zero size (empty struct or union in
12578     // C, array of zero length). Pointer subtraction in such cases has
12579     // undefined behavior, so is not constant.
12580     if (ElementSize.isZero()) {
12581       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
12582           << ElementType;
12583       return false;
12584     }
12585 
12586     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
12587     // and produce incorrect results when it overflows. Such behavior
12588     // appears to be non-conforming, but is common, so perhaps we should
12589     // assume the standard intended for such cases to be undefined behavior
12590     // and check for them.
12591 
12592     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
12593     // overflow in the final conversion to ptrdiff_t.
12594     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
12595     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
12596     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
12597                     false);
12598     APSInt TrueResult = (LHS - RHS) / ElemSize;
12599     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
12600 
12601     if (Result.extend(65) != TrueResult &&
12602         !HandleOverflow(Info, E, TrueResult, E->getType()))
12603       return false;
12604     return Success(Result, E);
12605   }
12606 
12607   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12608 }
12609 
12610 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
12611 /// a result as the expression's type.
12612 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
12613                                     const UnaryExprOrTypeTraitExpr *E) {
12614   switch(E->getKind()) {
12615   case UETT_PreferredAlignOf:
12616   case UETT_AlignOf: {
12617     if (E->isArgumentType())
12618       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
12619                      E);
12620     else
12621       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
12622                      E);
12623   }
12624 
12625   case UETT_VecStep: {
12626     QualType Ty = E->getTypeOfArgument();
12627 
12628     if (Ty->isVectorType()) {
12629       unsigned n = Ty->castAs<VectorType>()->getNumElements();
12630 
12631       // The vec_step built-in functions that take a 3-component
12632       // vector return 4. (OpenCL 1.1 spec 6.11.12)
12633       if (n == 3)
12634         n = 4;
12635 
12636       return Success(n, E);
12637     } else
12638       return Success(1, E);
12639   }
12640 
12641   case UETT_SizeOf: {
12642     QualType SrcTy = E->getTypeOfArgument();
12643     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
12644     //   the result is the size of the referenced type."
12645     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
12646       SrcTy = Ref->getPointeeType();
12647 
12648     CharUnits Sizeof;
12649     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
12650       return false;
12651     return Success(Sizeof, E);
12652   }
12653   case UETT_OpenMPRequiredSimdAlign:
12654     assert(E->isArgumentType());
12655     return Success(
12656         Info.Ctx.toCharUnitsFromBits(
12657                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
12658             .getQuantity(),
12659         E);
12660   }
12661 
12662   llvm_unreachable("unknown expr/type trait");
12663 }
12664 
12665 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
12666   CharUnits Result;
12667   unsigned n = OOE->getNumComponents();
12668   if (n == 0)
12669     return Error(OOE);
12670   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
12671   for (unsigned i = 0; i != n; ++i) {
12672     OffsetOfNode ON = OOE->getComponent(i);
12673     switch (ON.getKind()) {
12674     case OffsetOfNode::Array: {
12675       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
12676       APSInt IdxResult;
12677       if (!EvaluateInteger(Idx, IdxResult, Info))
12678         return false;
12679       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
12680       if (!AT)
12681         return Error(OOE);
12682       CurrentType = AT->getElementType();
12683       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
12684       Result += IdxResult.getSExtValue() * ElementSize;
12685       break;
12686     }
12687 
12688     case OffsetOfNode::Field: {
12689       FieldDecl *MemberDecl = ON.getField();
12690       const RecordType *RT = CurrentType->getAs<RecordType>();
12691       if (!RT)
12692         return Error(OOE);
12693       RecordDecl *RD = RT->getDecl();
12694       if (RD->isInvalidDecl()) return false;
12695       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
12696       unsigned i = MemberDecl->getFieldIndex();
12697       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
12698       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
12699       CurrentType = MemberDecl->getType().getNonReferenceType();
12700       break;
12701     }
12702 
12703     case OffsetOfNode::Identifier:
12704       llvm_unreachable("dependent __builtin_offsetof");
12705 
12706     case OffsetOfNode::Base: {
12707       CXXBaseSpecifier *BaseSpec = ON.getBase();
12708       if (BaseSpec->isVirtual())
12709         return Error(OOE);
12710 
12711       // Find the layout of the class whose base we are looking into.
12712       const RecordType *RT = CurrentType->getAs<RecordType>();
12713       if (!RT)
12714         return Error(OOE);
12715       RecordDecl *RD = RT->getDecl();
12716       if (RD->isInvalidDecl()) return false;
12717       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
12718 
12719       // Find the base class itself.
12720       CurrentType = BaseSpec->getType();
12721       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
12722       if (!BaseRT)
12723         return Error(OOE);
12724 
12725       // Add the offset to the base.
12726       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
12727       break;
12728     }
12729     }
12730   }
12731   return Success(Result, OOE);
12732 }
12733 
12734 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12735   switch (E->getOpcode()) {
12736   default:
12737     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
12738     // See C99 6.6p3.
12739     return Error(E);
12740   case UO_Extension:
12741     // FIXME: Should extension allow i-c-e extension expressions in its scope?
12742     // If so, we could clear the diagnostic ID.
12743     return Visit(E->getSubExpr());
12744   case UO_Plus:
12745     // The result is just the value.
12746     return Visit(E->getSubExpr());
12747   case UO_Minus: {
12748     if (!Visit(E->getSubExpr()))
12749       return false;
12750     if (!Result.isInt()) return Error(E);
12751     const APSInt &Value = Result.getInt();
12752     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
12753         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
12754                         E->getType()))
12755       return false;
12756     return Success(-Value, E);
12757   }
12758   case UO_Not: {
12759     if (!Visit(E->getSubExpr()))
12760       return false;
12761     if (!Result.isInt()) return Error(E);
12762     return Success(~Result.getInt(), E);
12763   }
12764   case UO_LNot: {
12765     bool bres;
12766     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
12767       return false;
12768     return Success(!bres, E);
12769   }
12770   }
12771 }
12772 
12773 /// HandleCast - This is used to evaluate implicit or explicit casts where the
12774 /// result type is integer.
12775 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
12776   const Expr *SubExpr = E->getSubExpr();
12777   QualType DestType = E->getType();
12778   QualType SrcType = SubExpr->getType();
12779 
12780   switch (E->getCastKind()) {
12781   case CK_BaseToDerived:
12782   case CK_DerivedToBase:
12783   case CK_UncheckedDerivedToBase:
12784   case CK_Dynamic:
12785   case CK_ToUnion:
12786   case CK_ArrayToPointerDecay:
12787   case CK_FunctionToPointerDecay:
12788   case CK_NullToPointer:
12789   case CK_NullToMemberPointer:
12790   case CK_BaseToDerivedMemberPointer:
12791   case CK_DerivedToBaseMemberPointer:
12792   case CK_ReinterpretMemberPointer:
12793   case CK_ConstructorConversion:
12794   case CK_IntegralToPointer:
12795   case CK_ToVoid:
12796   case CK_VectorSplat:
12797   case CK_IntegralToFloating:
12798   case CK_FloatingCast:
12799   case CK_CPointerToObjCPointerCast:
12800   case CK_BlockPointerToObjCPointerCast:
12801   case CK_AnyPointerToBlockPointerCast:
12802   case CK_ObjCObjectLValueCast:
12803   case CK_FloatingRealToComplex:
12804   case CK_FloatingComplexToReal:
12805   case CK_FloatingComplexCast:
12806   case CK_FloatingComplexToIntegralComplex:
12807   case CK_IntegralRealToComplex:
12808   case CK_IntegralComplexCast:
12809   case CK_IntegralComplexToFloatingComplex:
12810   case CK_BuiltinFnToFnPtr:
12811   case CK_ZeroToOCLOpaqueType:
12812   case CK_NonAtomicToAtomic:
12813   case CK_AddressSpaceConversion:
12814   case CK_IntToOCLSampler:
12815   case CK_FixedPointCast:
12816   case CK_IntegralToFixedPoint:
12817     llvm_unreachable("invalid cast kind for integral value");
12818 
12819   case CK_BitCast:
12820   case CK_Dependent:
12821   case CK_LValueBitCast:
12822   case CK_ARCProduceObject:
12823   case CK_ARCConsumeObject:
12824   case CK_ARCReclaimReturnedObject:
12825   case CK_ARCExtendBlockObject:
12826   case CK_CopyAndAutoreleaseBlockObject:
12827     return Error(E);
12828 
12829   case CK_UserDefinedConversion:
12830   case CK_LValueToRValue:
12831   case CK_AtomicToNonAtomic:
12832   case CK_NoOp:
12833   case CK_LValueToRValueBitCast:
12834     return ExprEvaluatorBaseTy::VisitCastExpr(E);
12835 
12836   case CK_MemberPointerToBoolean:
12837   case CK_PointerToBoolean:
12838   case CK_IntegralToBoolean:
12839   case CK_FloatingToBoolean:
12840   case CK_BooleanToSignedIntegral:
12841   case CK_FloatingComplexToBoolean:
12842   case CK_IntegralComplexToBoolean: {
12843     bool BoolResult;
12844     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
12845       return false;
12846     uint64_t IntResult = BoolResult;
12847     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
12848       IntResult = (uint64_t)-1;
12849     return Success(IntResult, E);
12850   }
12851 
12852   case CK_FixedPointToIntegral: {
12853     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
12854     if (!EvaluateFixedPoint(SubExpr, Src, Info))
12855       return false;
12856     bool Overflowed;
12857     llvm::APSInt Result = Src.convertToInt(
12858         Info.Ctx.getIntWidth(DestType),
12859         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
12860     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
12861       return false;
12862     return Success(Result, E);
12863   }
12864 
12865   case CK_FixedPointToBoolean: {
12866     // Unsigned padding does not affect this.
12867     APValue Val;
12868     if (!Evaluate(Val, Info, SubExpr))
12869       return false;
12870     return Success(Val.getFixedPoint().getBoolValue(), E);
12871   }
12872 
12873   case CK_IntegralCast: {
12874     if (!Visit(SubExpr))
12875       return false;
12876 
12877     if (!Result.isInt()) {
12878       // Allow casts of address-of-label differences if they are no-ops
12879       // or narrowing.  (The narrowing case isn't actually guaranteed to
12880       // be constant-evaluatable except in some narrow cases which are hard
12881       // to detect here.  We let it through on the assumption the user knows
12882       // what they are doing.)
12883       if (Result.isAddrLabelDiff())
12884         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
12885       // Only allow casts of lvalues if they are lossless.
12886       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
12887     }
12888 
12889     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
12890                                       Result.getInt()), E);
12891   }
12892 
12893   case CK_PointerToIntegral: {
12894     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
12895 
12896     LValue LV;
12897     if (!EvaluatePointer(SubExpr, LV, Info))
12898       return false;
12899 
12900     if (LV.getLValueBase()) {
12901       // Only allow based lvalue casts if they are lossless.
12902       // FIXME: Allow a larger integer size than the pointer size, and allow
12903       // narrowing back down to pointer width in subsequent integral casts.
12904       // FIXME: Check integer type's active bits, not its type size.
12905       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
12906         return Error(E);
12907 
12908       LV.Designator.setInvalid();
12909       LV.moveInto(Result);
12910       return true;
12911     }
12912 
12913     APSInt AsInt;
12914     APValue V;
12915     LV.moveInto(V);
12916     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
12917       llvm_unreachable("Can't cast this!");
12918 
12919     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
12920   }
12921 
12922   case CK_IntegralComplexToReal: {
12923     ComplexValue C;
12924     if (!EvaluateComplex(SubExpr, C, Info))
12925       return false;
12926     return Success(C.getComplexIntReal(), E);
12927   }
12928 
12929   case CK_FloatingToIntegral: {
12930     APFloat F(0.0);
12931     if (!EvaluateFloat(SubExpr, F, Info))
12932       return false;
12933 
12934     APSInt Value;
12935     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
12936       return false;
12937     return Success(Value, E);
12938   }
12939   }
12940 
12941   llvm_unreachable("unknown cast resulting in integral value");
12942 }
12943 
12944 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
12945   if (E->getSubExpr()->getType()->isAnyComplexType()) {
12946     ComplexValue LV;
12947     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
12948       return false;
12949     if (!LV.isComplexInt())
12950       return Error(E);
12951     return Success(LV.getComplexIntReal(), E);
12952   }
12953 
12954   return Visit(E->getSubExpr());
12955 }
12956 
12957 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
12958   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
12959     ComplexValue LV;
12960     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
12961       return false;
12962     if (!LV.isComplexInt())
12963       return Error(E);
12964     return Success(LV.getComplexIntImag(), E);
12965   }
12966 
12967   VisitIgnoredValue(E->getSubExpr());
12968   return Success(0, E);
12969 }
12970 
12971 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
12972   return Success(E->getPackLength(), E);
12973 }
12974 
12975 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
12976   return Success(E->getValue(), E);
12977 }
12978 
12979 bool IntExprEvaluator::VisitConceptSpecializationExpr(
12980        const ConceptSpecializationExpr *E) {
12981   return Success(E->isSatisfied(), E);
12982 }
12983 
12984 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
12985   return Success(E->isSatisfied(), E);
12986 }
12987 
12988 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12989   switch (E->getOpcode()) {
12990     default:
12991       // Invalid unary operators
12992       return Error(E);
12993     case UO_Plus:
12994       // The result is just the value.
12995       return Visit(E->getSubExpr());
12996     case UO_Minus: {
12997       if (!Visit(E->getSubExpr())) return false;
12998       if (!Result.isFixedPoint())
12999         return Error(E);
13000       bool Overflowed;
13001       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13002       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13003         return false;
13004       return Success(Negated, E);
13005     }
13006     case UO_LNot: {
13007       bool bres;
13008       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13009         return false;
13010       return Success(!bres, E);
13011     }
13012   }
13013 }
13014 
13015 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13016   const Expr *SubExpr = E->getSubExpr();
13017   QualType DestType = E->getType();
13018   assert(DestType->isFixedPointType() &&
13019          "Expected destination type to be a fixed point type");
13020   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13021 
13022   switch (E->getCastKind()) {
13023   case CK_FixedPointCast: {
13024     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13025     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13026       return false;
13027     bool Overflowed;
13028     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13029     if (Overflowed) {
13030       if (Info.checkingForUndefinedBehavior())
13031         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13032                                          diag::warn_fixedpoint_constant_overflow)
13033           << Result.toString() << E->getType();
13034       else if (!HandleOverflow(Info, E, Result, E->getType()))
13035         return false;
13036     }
13037     return Success(Result, E);
13038   }
13039   case CK_IntegralToFixedPoint: {
13040     APSInt Src;
13041     if (!EvaluateInteger(SubExpr, Src, Info))
13042       return false;
13043 
13044     bool Overflowed;
13045     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13046         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13047 
13048     if (Overflowed) {
13049       if (Info.checkingForUndefinedBehavior())
13050         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13051                                          diag::warn_fixedpoint_constant_overflow)
13052           << IntResult.toString() << E->getType();
13053       else if (!HandleOverflow(Info, E, IntResult, E->getType()))
13054         return false;
13055     }
13056 
13057     return Success(IntResult, E);
13058   }
13059   case CK_NoOp:
13060   case CK_LValueToRValue:
13061     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13062   default:
13063     return Error(E);
13064   }
13065 }
13066 
13067 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13068   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13069     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13070 
13071   const Expr *LHS = E->getLHS();
13072   const Expr *RHS = E->getRHS();
13073   FixedPointSemantics ResultFXSema =
13074       Info.Ctx.getFixedPointSemantics(E->getType());
13075 
13076   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13077   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13078     return false;
13079   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13080   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13081     return false;
13082 
13083   bool OpOverflow = false, ConversionOverflow = false;
13084   APFixedPoint Result(LHSFX.getSemantics());
13085   switch (E->getOpcode()) {
13086   case BO_Add: {
13087     Result = LHSFX.add(RHSFX, &OpOverflow)
13088                   .convert(ResultFXSema, &ConversionOverflow);
13089     break;
13090   }
13091   case BO_Sub: {
13092     Result = LHSFX.sub(RHSFX, &OpOverflow)
13093                   .convert(ResultFXSema, &ConversionOverflow);
13094     break;
13095   }
13096   case BO_Mul: {
13097     Result = LHSFX.mul(RHSFX, &OpOverflow)
13098                   .convert(ResultFXSema, &ConversionOverflow);
13099     break;
13100   }
13101   case BO_Div: {
13102     if (RHSFX.getValue() == 0) {
13103       Info.FFDiag(E, diag::note_expr_divide_by_zero);
13104       return false;
13105     }
13106     Result = LHSFX.div(RHSFX, &OpOverflow)
13107                   .convert(ResultFXSema, &ConversionOverflow);
13108     break;
13109   }
13110   case BO_Shl:
13111   case BO_Shr: {
13112     FixedPointSemantics LHSSema = LHSFX.getSemantics();
13113     llvm::APSInt RHSVal = RHSFX.getValue();
13114 
13115     unsigned ShiftBW =
13116         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13117     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13118     // Embedded-C 4.1.6.2.2:
13119     //   The right operand must be nonnegative and less than the total number
13120     //   of (nonpadding) bits of the fixed-point operand ...
13121     if (RHSVal.isNegative())
13122       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13123     else if (Amt != RHSVal)
13124       Info.CCEDiag(E, diag::note_constexpr_large_shift)
13125           << RHSVal << E->getType() << ShiftBW;
13126 
13127     if (E->getOpcode() == BO_Shl)
13128       Result = LHSFX.shl(Amt, &OpOverflow);
13129     else
13130       Result = LHSFX.shr(Amt, &OpOverflow);
13131     break;
13132   }
13133   default:
13134     return false;
13135   }
13136   if (OpOverflow || ConversionOverflow) {
13137     if (Info.checkingForUndefinedBehavior())
13138       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13139                                        diag::warn_fixedpoint_constant_overflow)
13140         << Result.toString() << E->getType();
13141     else if (!HandleOverflow(Info, E, Result, E->getType()))
13142       return false;
13143   }
13144   return Success(Result, E);
13145 }
13146 
13147 //===----------------------------------------------------------------------===//
13148 // Float Evaluation
13149 //===----------------------------------------------------------------------===//
13150 
13151 namespace {
13152 class FloatExprEvaluator
13153   : public ExprEvaluatorBase<FloatExprEvaluator> {
13154   APFloat &Result;
13155 public:
13156   FloatExprEvaluator(EvalInfo &info, APFloat &result)
13157     : ExprEvaluatorBaseTy(info), Result(result) {}
13158 
13159   bool Success(const APValue &V, const Expr *e) {
13160     Result = V.getFloat();
13161     return true;
13162   }
13163 
13164   bool ZeroInitialization(const Expr *E) {
13165     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13166     return true;
13167   }
13168 
13169   bool VisitCallExpr(const CallExpr *E);
13170 
13171   bool VisitUnaryOperator(const UnaryOperator *E);
13172   bool VisitBinaryOperator(const BinaryOperator *E);
13173   bool VisitFloatingLiteral(const FloatingLiteral *E);
13174   bool VisitCastExpr(const CastExpr *E);
13175 
13176   bool VisitUnaryReal(const UnaryOperator *E);
13177   bool VisitUnaryImag(const UnaryOperator *E);
13178 
13179   // FIXME: Missing: array subscript of vector, member of vector
13180 };
13181 } // end anonymous namespace
13182 
13183 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13184   assert(E->isRValue() && E->getType()->isRealFloatingType());
13185   return FloatExprEvaluator(Info, Result).Visit(E);
13186 }
13187 
13188 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13189                                   QualType ResultTy,
13190                                   const Expr *Arg,
13191                                   bool SNaN,
13192                                   llvm::APFloat &Result) {
13193   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13194   if (!S) return false;
13195 
13196   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13197 
13198   llvm::APInt fill;
13199 
13200   // Treat empty strings as if they were zero.
13201   if (S->getString().empty())
13202     fill = llvm::APInt(32, 0);
13203   else if (S->getString().getAsInteger(0, fill))
13204     return false;
13205 
13206   if (Context.getTargetInfo().isNan2008()) {
13207     if (SNaN)
13208       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13209     else
13210       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13211   } else {
13212     // Prior to IEEE 754-2008, architectures were allowed to choose whether
13213     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13214     // a different encoding to what became a standard in 2008, and for pre-
13215     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13216     // sNaN. This is now known as "legacy NaN" encoding.
13217     if (SNaN)
13218       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13219     else
13220       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13221   }
13222 
13223   return true;
13224 }
13225 
13226 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
13227   switch (E->getBuiltinCallee()) {
13228   default:
13229     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13230 
13231   case Builtin::BI__builtin_huge_val:
13232   case Builtin::BI__builtin_huge_valf:
13233   case Builtin::BI__builtin_huge_vall:
13234   case Builtin::BI__builtin_huge_valf128:
13235   case Builtin::BI__builtin_inf:
13236   case Builtin::BI__builtin_inff:
13237   case Builtin::BI__builtin_infl:
13238   case Builtin::BI__builtin_inff128: {
13239     const llvm::fltSemantics &Sem =
13240       Info.Ctx.getFloatTypeSemantics(E->getType());
13241     Result = llvm::APFloat::getInf(Sem);
13242     return true;
13243   }
13244 
13245   case Builtin::BI__builtin_nans:
13246   case Builtin::BI__builtin_nansf:
13247   case Builtin::BI__builtin_nansl:
13248   case Builtin::BI__builtin_nansf128:
13249     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13250                                true, Result))
13251       return Error(E);
13252     return true;
13253 
13254   case Builtin::BI__builtin_nan:
13255   case Builtin::BI__builtin_nanf:
13256   case Builtin::BI__builtin_nanl:
13257   case Builtin::BI__builtin_nanf128:
13258     // If this is __builtin_nan() turn this into a nan, otherwise we
13259     // can't constant fold it.
13260     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13261                                false, Result))
13262       return Error(E);
13263     return true;
13264 
13265   case Builtin::BI__builtin_fabs:
13266   case Builtin::BI__builtin_fabsf:
13267   case Builtin::BI__builtin_fabsl:
13268   case Builtin::BI__builtin_fabsf128:
13269     if (!EvaluateFloat(E->getArg(0), Result, Info))
13270       return false;
13271 
13272     if (Result.isNegative())
13273       Result.changeSign();
13274     return true;
13275 
13276   // FIXME: Builtin::BI__builtin_powi
13277   // FIXME: Builtin::BI__builtin_powif
13278   // FIXME: Builtin::BI__builtin_powil
13279 
13280   case Builtin::BI__builtin_copysign:
13281   case Builtin::BI__builtin_copysignf:
13282   case Builtin::BI__builtin_copysignl:
13283   case Builtin::BI__builtin_copysignf128: {
13284     APFloat RHS(0.);
13285     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
13286         !EvaluateFloat(E->getArg(1), RHS, Info))
13287       return false;
13288     Result.copySign(RHS);
13289     return true;
13290   }
13291   }
13292 }
13293 
13294 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13295   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13296     ComplexValue CV;
13297     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13298       return false;
13299     Result = CV.FloatReal;
13300     return true;
13301   }
13302 
13303   return Visit(E->getSubExpr());
13304 }
13305 
13306 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13307   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13308     ComplexValue CV;
13309     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13310       return false;
13311     Result = CV.FloatImag;
13312     return true;
13313   }
13314 
13315   VisitIgnoredValue(E->getSubExpr());
13316   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
13317   Result = llvm::APFloat::getZero(Sem);
13318   return true;
13319 }
13320 
13321 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13322   switch (E->getOpcode()) {
13323   default: return Error(E);
13324   case UO_Plus:
13325     return EvaluateFloat(E->getSubExpr(), Result, Info);
13326   case UO_Minus:
13327     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
13328       return false;
13329     Result.changeSign();
13330     return true;
13331   }
13332 }
13333 
13334 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13335   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13336     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13337 
13338   APFloat RHS(0.0);
13339   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
13340   if (!LHSOK && !Info.noteFailure())
13341     return false;
13342   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
13343          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
13344 }
13345 
13346 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
13347   Result = E->getValue();
13348   return true;
13349 }
13350 
13351 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
13352   const Expr* SubExpr = E->getSubExpr();
13353 
13354   switch (E->getCastKind()) {
13355   default:
13356     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13357 
13358   case CK_IntegralToFloating: {
13359     APSInt IntResult;
13360     return EvaluateInteger(SubExpr, IntResult, Info) &&
13361            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
13362                                 E->getType(), Result);
13363   }
13364 
13365   case CK_FloatingCast: {
13366     if (!Visit(SubExpr))
13367       return false;
13368     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
13369                                   Result);
13370   }
13371 
13372   case CK_FloatingComplexToReal: {
13373     ComplexValue V;
13374     if (!EvaluateComplex(SubExpr, V, Info))
13375       return false;
13376     Result = V.getComplexFloatReal();
13377     return true;
13378   }
13379   }
13380 }
13381 
13382 //===----------------------------------------------------------------------===//
13383 // Complex Evaluation (for float and integer)
13384 //===----------------------------------------------------------------------===//
13385 
13386 namespace {
13387 class ComplexExprEvaluator
13388   : public ExprEvaluatorBase<ComplexExprEvaluator> {
13389   ComplexValue &Result;
13390 
13391 public:
13392   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
13393     : ExprEvaluatorBaseTy(info), Result(Result) {}
13394 
13395   bool Success(const APValue &V, const Expr *e) {
13396     Result.setFrom(V);
13397     return true;
13398   }
13399 
13400   bool ZeroInitialization(const Expr *E);
13401 
13402   //===--------------------------------------------------------------------===//
13403   //                            Visitor Methods
13404   //===--------------------------------------------------------------------===//
13405 
13406   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
13407   bool VisitCastExpr(const CastExpr *E);
13408   bool VisitBinaryOperator(const BinaryOperator *E);
13409   bool VisitUnaryOperator(const UnaryOperator *E);
13410   bool VisitInitListExpr(const InitListExpr *E);
13411   bool VisitCallExpr(const CallExpr *E);
13412 };
13413 } // end anonymous namespace
13414 
13415 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
13416                             EvalInfo &Info) {
13417   assert(E->isRValue() && E->getType()->isAnyComplexType());
13418   return ComplexExprEvaluator(Info, Result).Visit(E);
13419 }
13420 
13421 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
13422   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
13423   if (ElemTy->isRealFloatingType()) {
13424     Result.makeComplexFloat();
13425     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
13426     Result.FloatReal = Zero;
13427     Result.FloatImag = Zero;
13428   } else {
13429     Result.makeComplexInt();
13430     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
13431     Result.IntReal = Zero;
13432     Result.IntImag = Zero;
13433   }
13434   return true;
13435 }
13436 
13437 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
13438   const Expr* SubExpr = E->getSubExpr();
13439 
13440   if (SubExpr->getType()->isRealFloatingType()) {
13441     Result.makeComplexFloat();
13442     APFloat &Imag = Result.FloatImag;
13443     if (!EvaluateFloat(SubExpr, Imag, Info))
13444       return false;
13445 
13446     Result.FloatReal = APFloat(Imag.getSemantics());
13447     return true;
13448   } else {
13449     assert(SubExpr->getType()->isIntegerType() &&
13450            "Unexpected imaginary literal.");
13451 
13452     Result.makeComplexInt();
13453     APSInt &Imag = Result.IntImag;
13454     if (!EvaluateInteger(SubExpr, Imag, Info))
13455       return false;
13456 
13457     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
13458     return true;
13459   }
13460 }
13461 
13462 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
13463 
13464   switch (E->getCastKind()) {
13465   case CK_BitCast:
13466   case CK_BaseToDerived:
13467   case CK_DerivedToBase:
13468   case CK_UncheckedDerivedToBase:
13469   case CK_Dynamic:
13470   case CK_ToUnion:
13471   case CK_ArrayToPointerDecay:
13472   case CK_FunctionToPointerDecay:
13473   case CK_NullToPointer:
13474   case CK_NullToMemberPointer:
13475   case CK_BaseToDerivedMemberPointer:
13476   case CK_DerivedToBaseMemberPointer:
13477   case CK_MemberPointerToBoolean:
13478   case CK_ReinterpretMemberPointer:
13479   case CK_ConstructorConversion:
13480   case CK_IntegralToPointer:
13481   case CK_PointerToIntegral:
13482   case CK_PointerToBoolean:
13483   case CK_ToVoid:
13484   case CK_VectorSplat:
13485   case CK_IntegralCast:
13486   case CK_BooleanToSignedIntegral:
13487   case CK_IntegralToBoolean:
13488   case CK_IntegralToFloating:
13489   case CK_FloatingToIntegral:
13490   case CK_FloatingToBoolean:
13491   case CK_FloatingCast:
13492   case CK_CPointerToObjCPointerCast:
13493   case CK_BlockPointerToObjCPointerCast:
13494   case CK_AnyPointerToBlockPointerCast:
13495   case CK_ObjCObjectLValueCast:
13496   case CK_FloatingComplexToReal:
13497   case CK_FloatingComplexToBoolean:
13498   case CK_IntegralComplexToReal:
13499   case CK_IntegralComplexToBoolean:
13500   case CK_ARCProduceObject:
13501   case CK_ARCConsumeObject:
13502   case CK_ARCReclaimReturnedObject:
13503   case CK_ARCExtendBlockObject:
13504   case CK_CopyAndAutoreleaseBlockObject:
13505   case CK_BuiltinFnToFnPtr:
13506   case CK_ZeroToOCLOpaqueType:
13507   case CK_NonAtomicToAtomic:
13508   case CK_AddressSpaceConversion:
13509   case CK_IntToOCLSampler:
13510   case CK_FixedPointCast:
13511   case CK_FixedPointToBoolean:
13512   case CK_FixedPointToIntegral:
13513   case CK_IntegralToFixedPoint:
13514     llvm_unreachable("invalid cast kind for complex value");
13515 
13516   case CK_LValueToRValue:
13517   case CK_AtomicToNonAtomic:
13518   case CK_NoOp:
13519   case CK_LValueToRValueBitCast:
13520     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13521 
13522   case CK_Dependent:
13523   case CK_LValueBitCast:
13524   case CK_UserDefinedConversion:
13525     return Error(E);
13526 
13527   case CK_FloatingRealToComplex: {
13528     APFloat &Real = Result.FloatReal;
13529     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
13530       return false;
13531 
13532     Result.makeComplexFloat();
13533     Result.FloatImag = APFloat(Real.getSemantics());
13534     return true;
13535   }
13536 
13537   case CK_FloatingComplexCast: {
13538     if (!Visit(E->getSubExpr()))
13539       return false;
13540 
13541     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13542     QualType From
13543       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13544 
13545     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
13546            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
13547   }
13548 
13549   case CK_FloatingComplexToIntegralComplex: {
13550     if (!Visit(E->getSubExpr()))
13551       return false;
13552 
13553     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13554     QualType From
13555       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13556     Result.makeComplexInt();
13557     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
13558                                 To, Result.IntReal) &&
13559            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
13560                                 To, Result.IntImag);
13561   }
13562 
13563   case CK_IntegralRealToComplex: {
13564     APSInt &Real = Result.IntReal;
13565     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
13566       return false;
13567 
13568     Result.makeComplexInt();
13569     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
13570     return true;
13571   }
13572 
13573   case CK_IntegralComplexCast: {
13574     if (!Visit(E->getSubExpr()))
13575       return false;
13576 
13577     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13578     QualType From
13579       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13580 
13581     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
13582     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
13583     return true;
13584   }
13585 
13586   case CK_IntegralComplexToFloatingComplex: {
13587     if (!Visit(E->getSubExpr()))
13588       return false;
13589 
13590     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13591     QualType From
13592       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13593     Result.makeComplexFloat();
13594     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
13595                                 To, Result.FloatReal) &&
13596            HandleIntToFloatCast(Info, E, From, Result.IntImag,
13597                                 To, Result.FloatImag);
13598   }
13599   }
13600 
13601   llvm_unreachable("unknown cast resulting in complex value");
13602 }
13603 
13604 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13605   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13606     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13607 
13608   // Track whether the LHS or RHS is real at the type system level. When this is
13609   // the case we can simplify our evaluation strategy.
13610   bool LHSReal = false, RHSReal = false;
13611 
13612   bool LHSOK;
13613   if (E->getLHS()->getType()->isRealFloatingType()) {
13614     LHSReal = true;
13615     APFloat &Real = Result.FloatReal;
13616     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
13617     if (LHSOK) {
13618       Result.makeComplexFloat();
13619       Result.FloatImag = APFloat(Real.getSemantics());
13620     }
13621   } else {
13622     LHSOK = Visit(E->getLHS());
13623   }
13624   if (!LHSOK && !Info.noteFailure())
13625     return false;
13626 
13627   ComplexValue RHS;
13628   if (E->getRHS()->getType()->isRealFloatingType()) {
13629     RHSReal = true;
13630     APFloat &Real = RHS.FloatReal;
13631     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
13632       return false;
13633     RHS.makeComplexFloat();
13634     RHS.FloatImag = APFloat(Real.getSemantics());
13635   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
13636     return false;
13637 
13638   assert(!(LHSReal && RHSReal) &&
13639          "Cannot have both operands of a complex operation be real.");
13640   switch (E->getOpcode()) {
13641   default: return Error(E);
13642   case BO_Add:
13643     if (Result.isComplexFloat()) {
13644       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
13645                                        APFloat::rmNearestTiesToEven);
13646       if (LHSReal)
13647         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
13648       else if (!RHSReal)
13649         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
13650                                          APFloat::rmNearestTiesToEven);
13651     } else {
13652       Result.getComplexIntReal() += RHS.getComplexIntReal();
13653       Result.getComplexIntImag() += RHS.getComplexIntImag();
13654     }
13655     break;
13656   case BO_Sub:
13657     if (Result.isComplexFloat()) {
13658       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
13659                                             APFloat::rmNearestTiesToEven);
13660       if (LHSReal) {
13661         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
13662         Result.getComplexFloatImag().changeSign();
13663       } else if (!RHSReal) {
13664         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
13665                                               APFloat::rmNearestTiesToEven);
13666       }
13667     } else {
13668       Result.getComplexIntReal() -= RHS.getComplexIntReal();
13669       Result.getComplexIntImag() -= RHS.getComplexIntImag();
13670     }
13671     break;
13672   case BO_Mul:
13673     if (Result.isComplexFloat()) {
13674       // This is an implementation of complex multiplication according to the
13675       // constraints laid out in C11 Annex G. The implementation uses the
13676       // following naming scheme:
13677       //   (a + ib) * (c + id)
13678       ComplexValue LHS = Result;
13679       APFloat &A = LHS.getComplexFloatReal();
13680       APFloat &B = LHS.getComplexFloatImag();
13681       APFloat &C = RHS.getComplexFloatReal();
13682       APFloat &D = RHS.getComplexFloatImag();
13683       APFloat &ResR = Result.getComplexFloatReal();
13684       APFloat &ResI = Result.getComplexFloatImag();
13685       if (LHSReal) {
13686         assert(!RHSReal && "Cannot have two real operands for a complex op!");
13687         ResR = A * C;
13688         ResI = A * D;
13689       } else if (RHSReal) {
13690         ResR = C * A;
13691         ResI = C * B;
13692       } else {
13693         // In the fully general case, we need to handle NaNs and infinities
13694         // robustly.
13695         APFloat AC = A * C;
13696         APFloat BD = B * D;
13697         APFloat AD = A * D;
13698         APFloat BC = B * C;
13699         ResR = AC - BD;
13700         ResI = AD + BC;
13701         if (ResR.isNaN() && ResI.isNaN()) {
13702           bool Recalc = false;
13703           if (A.isInfinity() || B.isInfinity()) {
13704             A = APFloat::copySign(
13705                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
13706             B = APFloat::copySign(
13707                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
13708             if (C.isNaN())
13709               C = APFloat::copySign(APFloat(C.getSemantics()), C);
13710             if (D.isNaN())
13711               D = APFloat::copySign(APFloat(D.getSemantics()), D);
13712             Recalc = true;
13713           }
13714           if (C.isInfinity() || D.isInfinity()) {
13715             C = APFloat::copySign(
13716                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
13717             D = APFloat::copySign(
13718                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
13719             if (A.isNaN())
13720               A = APFloat::copySign(APFloat(A.getSemantics()), A);
13721             if (B.isNaN())
13722               B = APFloat::copySign(APFloat(B.getSemantics()), B);
13723             Recalc = true;
13724           }
13725           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
13726                           AD.isInfinity() || BC.isInfinity())) {
13727             if (A.isNaN())
13728               A = APFloat::copySign(APFloat(A.getSemantics()), A);
13729             if (B.isNaN())
13730               B = APFloat::copySign(APFloat(B.getSemantics()), B);
13731             if (C.isNaN())
13732               C = APFloat::copySign(APFloat(C.getSemantics()), C);
13733             if (D.isNaN())
13734               D = APFloat::copySign(APFloat(D.getSemantics()), D);
13735             Recalc = true;
13736           }
13737           if (Recalc) {
13738             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
13739             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
13740           }
13741         }
13742       }
13743     } else {
13744       ComplexValue LHS = Result;
13745       Result.getComplexIntReal() =
13746         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
13747          LHS.getComplexIntImag() * RHS.getComplexIntImag());
13748       Result.getComplexIntImag() =
13749         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
13750          LHS.getComplexIntImag() * RHS.getComplexIntReal());
13751     }
13752     break;
13753   case BO_Div:
13754     if (Result.isComplexFloat()) {
13755       // This is an implementation of complex division according to the
13756       // constraints laid out in C11 Annex G. The implementation uses the
13757       // following naming scheme:
13758       //   (a + ib) / (c + id)
13759       ComplexValue LHS = Result;
13760       APFloat &A = LHS.getComplexFloatReal();
13761       APFloat &B = LHS.getComplexFloatImag();
13762       APFloat &C = RHS.getComplexFloatReal();
13763       APFloat &D = RHS.getComplexFloatImag();
13764       APFloat &ResR = Result.getComplexFloatReal();
13765       APFloat &ResI = Result.getComplexFloatImag();
13766       if (RHSReal) {
13767         ResR = A / C;
13768         ResI = B / C;
13769       } else {
13770         if (LHSReal) {
13771           // No real optimizations we can do here, stub out with zero.
13772           B = APFloat::getZero(A.getSemantics());
13773         }
13774         int DenomLogB = 0;
13775         APFloat MaxCD = maxnum(abs(C), abs(D));
13776         if (MaxCD.isFinite()) {
13777           DenomLogB = ilogb(MaxCD);
13778           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
13779           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
13780         }
13781         APFloat Denom = C * C + D * D;
13782         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
13783                       APFloat::rmNearestTiesToEven);
13784         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
13785                       APFloat::rmNearestTiesToEven);
13786         if (ResR.isNaN() && ResI.isNaN()) {
13787           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
13788             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
13789             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
13790           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
13791                      D.isFinite()) {
13792             A = APFloat::copySign(
13793                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
13794             B = APFloat::copySign(
13795                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
13796             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
13797             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
13798           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
13799             C = APFloat::copySign(
13800                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
13801             D = APFloat::copySign(
13802                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
13803             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
13804             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
13805           }
13806         }
13807       }
13808     } else {
13809       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
13810         return Error(E, diag::note_expr_divide_by_zero);
13811 
13812       ComplexValue LHS = Result;
13813       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
13814         RHS.getComplexIntImag() * RHS.getComplexIntImag();
13815       Result.getComplexIntReal() =
13816         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
13817          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
13818       Result.getComplexIntImag() =
13819         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
13820          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
13821     }
13822     break;
13823   }
13824 
13825   return true;
13826 }
13827 
13828 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13829   // Get the operand value into 'Result'.
13830   if (!Visit(E->getSubExpr()))
13831     return false;
13832 
13833   switch (E->getOpcode()) {
13834   default:
13835     return Error(E);
13836   case UO_Extension:
13837     return true;
13838   case UO_Plus:
13839     // The result is always just the subexpr.
13840     return true;
13841   case UO_Minus:
13842     if (Result.isComplexFloat()) {
13843       Result.getComplexFloatReal().changeSign();
13844       Result.getComplexFloatImag().changeSign();
13845     }
13846     else {
13847       Result.getComplexIntReal() = -Result.getComplexIntReal();
13848       Result.getComplexIntImag() = -Result.getComplexIntImag();
13849     }
13850     return true;
13851   case UO_Not:
13852     if (Result.isComplexFloat())
13853       Result.getComplexFloatImag().changeSign();
13854     else
13855       Result.getComplexIntImag() = -Result.getComplexIntImag();
13856     return true;
13857   }
13858 }
13859 
13860 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
13861   if (E->getNumInits() == 2) {
13862     if (E->getType()->isComplexType()) {
13863       Result.makeComplexFloat();
13864       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
13865         return false;
13866       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
13867         return false;
13868     } else {
13869       Result.makeComplexInt();
13870       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
13871         return false;
13872       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
13873         return false;
13874     }
13875     return true;
13876   }
13877   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
13878 }
13879 
13880 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
13881   switch (E->getBuiltinCallee()) {
13882   case Builtin::BI__builtin_complex:
13883     Result.makeComplexFloat();
13884     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
13885       return false;
13886     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
13887       return false;
13888     return true;
13889 
13890   default:
13891     break;
13892   }
13893 
13894   return ExprEvaluatorBaseTy::VisitCallExpr(E);
13895 }
13896 
13897 //===----------------------------------------------------------------------===//
13898 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
13899 // implicit conversion.
13900 //===----------------------------------------------------------------------===//
13901 
13902 namespace {
13903 class AtomicExprEvaluator :
13904     public ExprEvaluatorBase<AtomicExprEvaluator> {
13905   const LValue *This;
13906   APValue &Result;
13907 public:
13908   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
13909       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
13910 
13911   bool Success(const APValue &V, const Expr *E) {
13912     Result = V;
13913     return true;
13914   }
13915 
13916   bool ZeroInitialization(const Expr *E) {
13917     ImplicitValueInitExpr VIE(
13918         E->getType()->castAs<AtomicType>()->getValueType());
13919     // For atomic-qualified class (and array) types in C++, initialize the
13920     // _Atomic-wrapped subobject directly, in-place.
13921     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
13922                 : Evaluate(Result, Info, &VIE);
13923   }
13924 
13925   bool VisitCastExpr(const CastExpr *E) {
13926     switch (E->getCastKind()) {
13927     default:
13928       return ExprEvaluatorBaseTy::VisitCastExpr(E);
13929     case CK_NonAtomicToAtomic:
13930       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
13931                   : Evaluate(Result, Info, E->getSubExpr());
13932     }
13933   }
13934 };
13935 } // end anonymous namespace
13936 
13937 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
13938                            EvalInfo &Info) {
13939   assert(E->isRValue() && E->getType()->isAtomicType());
13940   return AtomicExprEvaluator(Info, This, Result).Visit(E);
13941 }
13942 
13943 //===----------------------------------------------------------------------===//
13944 // Void expression evaluation, primarily for a cast to void on the LHS of a
13945 // comma operator
13946 //===----------------------------------------------------------------------===//
13947 
13948 namespace {
13949 class VoidExprEvaluator
13950   : public ExprEvaluatorBase<VoidExprEvaluator> {
13951 public:
13952   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
13953 
13954   bool Success(const APValue &V, const Expr *e) { return true; }
13955 
13956   bool ZeroInitialization(const Expr *E) { return true; }
13957 
13958   bool VisitCastExpr(const CastExpr *E) {
13959     switch (E->getCastKind()) {
13960     default:
13961       return ExprEvaluatorBaseTy::VisitCastExpr(E);
13962     case CK_ToVoid:
13963       VisitIgnoredValue(E->getSubExpr());
13964       return true;
13965     }
13966   }
13967 
13968   bool VisitCallExpr(const CallExpr *E) {
13969     switch (E->getBuiltinCallee()) {
13970     case Builtin::BI__assume:
13971     case Builtin::BI__builtin_assume:
13972       // The argument is not evaluated!
13973       return true;
13974 
13975     case Builtin::BI__builtin_operator_delete:
13976       return HandleOperatorDeleteCall(Info, E);
13977 
13978     default:
13979       break;
13980     }
13981 
13982     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13983   }
13984 
13985   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
13986 };
13987 } // end anonymous namespace
13988 
13989 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
13990   // We cannot speculatively evaluate a delete expression.
13991   if (Info.SpeculativeEvaluationDepth)
13992     return false;
13993 
13994   FunctionDecl *OperatorDelete = E->getOperatorDelete();
13995   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
13996     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
13997         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
13998     return false;
13999   }
14000 
14001   const Expr *Arg = E->getArgument();
14002 
14003   LValue Pointer;
14004   if (!EvaluatePointer(Arg, Pointer, Info))
14005     return false;
14006   if (Pointer.Designator.Invalid)
14007     return false;
14008 
14009   // Deleting a null pointer has no effect.
14010   if (Pointer.isNullPointer()) {
14011     // This is the only case where we need to produce an extension warning:
14012     // the only other way we can succeed is if we find a dynamic allocation,
14013     // and we will have warned when we allocated it in that case.
14014     if (!Info.getLangOpts().CPlusPlus20)
14015       Info.CCEDiag(E, diag::note_constexpr_new);
14016     return true;
14017   }
14018 
14019   Optional<DynAlloc *> Alloc = CheckDeleteKind(
14020       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14021   if (!Alloc)
14022     return false;
14023   QualType AllocType = Pointer.Base.getDynamicAllocType();
14024 
14025   // For the non-array case, the designator must be empty if the static type
14026   // does not have a virtual destructor.
14027   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14028       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14029     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14030         << Arg->getType()->getPointeeType() << AllocType;
14031     return false;
14032   }
14033 
14034   // For a class type with a virtual destructor, the selected operator delete
14035   // is the one looked up when building the destructor.
14036   if (!E->isArrayForm() && !E->isGlobalDelete()) {
14037     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14038     if (VirtualDelete &&
14039         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14040       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14041           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14042       return false;
14043     }
14044   }
14045 
14046   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14047                          (*Alloc)->Value, AllocType))
14048     return false;
14049 
14050   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14051     // The element was already erased. This means the destructor call also
14052     // deleted the object.
14053     // FIXME: This probably results in undefined behavior before we get this
14054     // far, and should be diagnosed elsewhere first.
14055     Info.FFDiag(E, diag::note_constexpr_double_delete);
14056     return false;
14057   }
14058 
14059   return true;
14060 }
14061 
14062 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14063   assert(E->isRValue() && E->getType()->isVoidType());
14064   return VoidExprEvaluator(Info).Visit(E);
14065 }
14066 
14067 //===----------------------------------------------------------------------===//
14068 // Top level Expr::EvaluateAsRValue method.
14069 //===----------------------------------------------------------------------===//
14070 
14071 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14072   // In C, function designators are not lvalues, but we evaluate them as if they
14073   // are.
14074   QualType T = E->getType();
14075   if (E->isGLValue() || T->isFunctionType()) {
14076     LValue LV;
14077     if (!EvaluateLValue(E, LV, Info))
14078       return false;
14079     LV.moveInto(Result);
14080   } else if (T->isVectorType()) {
14081     if (!EvaluateVector(E, Result, Info))
14082       return false;
14083   } else if (T->isIntegralOrEnumerationType()) {
14084     if (!IntExprEvaluator(Info, Result).Visit(E))
14085       return false;
14086   } else if (T->hasPointerRepresentation()) {
14087     LValue LV;
14088     if (!EvaluatePointer(E, LV, Info))
14089       return false;
14090     LV.moveInto(Result);
14091   } else if (T->isRealFloatingType()) {
14092     llvm::APFloat F(0.0);
14093     if (!EvaluateFloat(E, F, Info))
14094       return false;
14095     Result = APValue(F);
14096   } else if (T->isAnyComplexType()) {
14097     ComplexValue C;
14098     if (!EvaluateComplex(E, C, Info))
14099       return false;
14100     C.moveInto(Result);
14101   } else if (T->isFixedPointType()) {
14102     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
14103   } else if (T->isMemberPointerType()) {
14104     MemberPtr P;
14105     if (!EvaluateMemberPointer(E, P, Info))
14106       return false;
14107     P.moveInto(Result);
14108     return true;
14109   } else if (T->isArrayType()) {
14110     LValue LV;
14111     APValue &Value =
14112         Info.CurrentCall->createTemporary(E, T, false, LV);
14113     if (!EvaluateArray(E, LV, Value, Info))
14114       return false;
14115     Result = Value;
14116   } else if (T->isRecordType()) {
14117     LValue LV;
14118     APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV);
14119     if (!EvaluateRecord(E, LV, Value, Info))
14120       return false;
14121     Result = Value;
14122   } else if (T->isVoidType()) {
14123     if (!Info.getLangOpts().CPlusPlus11)
14124       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
14125         << E->getType();
14126     if (!EvaluateVoid(E, Info))
14127       return false;
14128   } else if (T->isAtomicType()) {
14129     QualType Unqual = T.getAtomicUnqualifiedType();
14130     if (Unqual->isArrayType() || Unqual->isRecordType()) {
14131       LValue LV;
14132       APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV);
14133       if (!EvaluateAtomic(E, &LV, Value, Info))
14134         return false;
14135     } else {
14136       if (!EvaluateAtomic(E, nullptr, Result, Info))
14137         return false;
14138     }
14139   } else if (Info.getLangOpts().CPlusPlus11) {
14140     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
14141     return false;
14142   } else {
14143     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14144     return false;
14145   }
14146 
14147   return true;
14148 }
14149 
14150 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
14151 /// cases, the in-place evaluation is essential, since later initializers for
14152 /// an object can indirectly refer to subobjects which were initialized earlier.
14153 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
14154                             const Expr *E, bool AllowNonLiteralTypes) {
14155   assert(!E->isValueDependent());
14156 
14157   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
14158     return false;
14159 
14160   if (E->isRValue()) {
14161     // Evaluate arrays and record types in-place, so that later initializers can
14162     // refer to earlier-initialized members of the object.
14163     QualType T = E->getType();
14164     if (T->isArrayType())
14165       return EvaluateArray(E, This, Result, Info);
14166     else if (T->isRecordType())
14167       return EvaluateRecord(E, This, Result, Info);
14168     else if (T->isAtomicType()) {
14169       QualType Unqual = T.getAtomicUnqualifiedType();
14170       if (Unqual->isArrayType() || Unqual->isRecordType())
14171         return EvaluateAtomic(E, &This, Result, Info);
14172     }
14173   }
14174 
14175   // For any other type, in-place evaluation is unimportant.
14176   return Evaluate(Result, Info, E);
14177 }
14178 
14179 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
14180 /// lvalue-to-rvalue cast if it is an lvalue.
14181 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
14182   if (Info.EnableNewConstInterp) {
14183     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
14184       return false;
14185   } else {
14186     if (E->getType().isNull())
14187       return false;
14188 
14189     if (!CheckLiteralType(Info, E))
14190       return false;
14191 
14192     if (!::Evaluate(Result, Info, E))
14193       return false;
14194 
14195     if (E->isGLValue()) {
14196       LValue LV;
14197       LV.setFrom(Info.Ctx, Result);
14198       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14199         return false;
14200     }
14201   }
14202 
14203   // Check this core constant expression is a constant expression.
14204   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) &&
14205          CheckMemoryLeaks(Info);
14206 }
14207 
14208 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
14209                                  const ASTContext &Ctx, bool &IsConst) {
14210   // Fast-path evaluations of integer literals, since we sometimes see files
14211   // containing vast quantities of these.
14212   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
14213     Result.Val = APValue(APSInt(L->getValue(),
14214                                 L->getType()->isUnsignedIntegerType()));
14215     IsConst = true;
14216     return true;
14217   }
14218 
14219   // This case should be rare, but we need to check it before we check on
14220   // the type below.
14221   if (Exp->getType().isNull()) {
14222     IsConst = false;
14223     return true;
14224   }
14225 
14226   // FIXME: Evaluating values of large array and record types can cause
14227   // performance problems. Only do so in C++11 for now.
14228   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
14229                           Exp->getType()->isRecordType()) &&
14230       !Ctx.getLangOpts().CPlusPlus11) {
14231     IsConst = false;
14232     return true;
14233   }
14234   return false;
14235 }
14236 
14237 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
14238                                       Expr::SideEffectsKind SEK) {
14239   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
14240          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
14241 }
14242 
14243 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
14244                              const ASTContext &Ctx, EvalInfo &Info) {
14245   bool IsConst;
14246   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
14247     return IsConst;
14248 
14249   return EvaluateAsRValue(Info, E, Result.Val);
14250 }
14251 
14252 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
14253                           const ASTContext &Ctx,
14254                           Expr::SideEffectsKind AllowSideEffects,
14255                           EvalInfo &Info) {
14256   if (!E->getType()->isIntegralOrEnumerationType())
14257     return false;
14258 
14259   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
14260       !ExprResult.Val.isInt() ||
14261       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14262     return false;
14263 
14264   return true;
14265 }
14266 
14267 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
14268                                  const ASTContext &Ctx,
14269                                  Expr::SideEffectsKind AllowSideEffects,
14270                                  EvalInfo &Info) {
14271   if (!E->getType()->isFixedPointType())
14272     return false;
14273 
14274   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
14275     return false;
14276 
14277   if (!ExprResult.Val.isFixedPoint() ||
14278       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14279     return false;
14280 
14281   return true;
14282 }
14283 
14284 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
14285 /// any crazy technique (that has nothing to do with language standards) that
14286 /// we want to.  If this function returns true, it returns the folded constant
14287 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
14288 /// will be applied to the result.
14289 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
14290                             bool InConstantContext) const {
14291   assert(!isValueDependent() &&
14292          "Expression evaluator can't be called on a dependent expression.");
14293   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14294   Info.InConstantContext = InConstantContext;
14295   return ::EvaluateAsRValue(this, Result, Ctx, Info);
14296 }
14297 
14298 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
14299                                       bool InConstantContext) const {
14300   assert(!isValueDependent() &&
14301          "Expression evaluator can't be called on a dependent expression.");
14302   EvalResult Scratch;
14303   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
14304          HandleConversionToBool(Scratch.Val, Result);
14305 }
14306 
14307 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
14308                          SideEffectsKind AllowSideEffects,
14309                          bool InConstantContext) const {
14310   assert(!isValueDependent() &&
14311          "Expression evaluator can't be called on a dependent expression.");
14312   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14313   Info.InConstantContext = InConstantContext;
14314   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
14315 }
14316 
14317 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
14318                                 SideEffectsKind AllowSideEffects,
14319                                 bool InConstantContext) const {
14320   assert(!isValueDependent() &&
14321          "Expression evaluator can't be called on a dependent expression.");
14322   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14323   Info.InConstantContext = InConstantContext;
14324   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
14325 }
14326 
14327 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
14328                            SideEffectsKind AllowSideEffects,
14329                            bool InConstantContext) const {
14330   assert(!isValueDependent() &&
14331          "Expression evaluator can't be called on a dependent expression.");
14332 
14333   if (!getType()->isRealFloatingType())
14334     return false;
14335 
14336   EvalResult ExprResult;
14337   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
14338       !ExprResult.Val.isFloat() ||
14339       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14340     return false;
14341 
14342   Result = ExprResult.Val.getFloat();
14343   return true;
14344 }
14345 
14346 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
14347                             bool InConstantContext) const {
14348   assert(!isValueDependent() &&
14349          "Expression evaluator can't be called on a dependent expression.");
14350 
14351   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
14352   Info.InConstantContext = InConstantContext;
14353   LValue LV;
14354   CheckedTemporaries CheckedTemps;
14355   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
14356       Result.HasSideEffects ||
14357       !CheckLValueConstantExpression(Info, getExprLoc(),
14358                                      Ctx.getLValueReferenceType(getType()), LV,
14359                                      Expr::EvaluateForCodeGen, CheckedTemps))
14360     return false;
14361 
14362   LV.moveInto(Result.Val);
14363   return true;
14364 }
14365 
14366 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
14367                                   const ASTContext &Ctx, bool InPlace) const {
14368   assert(!isValueDependent() &&
14369          "Expression evaluator can't be called on a dependent expression.");
14370 
14371   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
14372   EvalInfo Info(Ctx, Result, EM);
14373   Info.InConstantContext = true;
14374 
14375   if (InPlace) {
14376     Info.setEvaluatingDecl(this, Result.Val);
14377     LValue LVal;
14378     LVal.set(this);
14379     if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
14380         Result.HasSideEffects)
14381       return false;
14382   } else if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects)
14383     return false;
14384 
14385   if (!Info.discardCleanups())
14386     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14387 
14388   return CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
14389                                  Result.Val, Usage) &&
14390          CheckMemoryLeaks(Info);
14391 }
14392 
14393 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
14394                                  const VarDecl *VD,
14395                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
14396   assert(!isValueDependent() &&
14397          "Expression evaluator can't be called on a dependent expression.");
14398 
14399   // FIXME: Evaluating initializers for large array and record types can cause
14400   // performance problems. Only do so in C++11 for now.
14401   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
14402       !Ctx.getLangOpts().CPlusPlus11)
14403     return false;
14404 
14405   Expr::EvalStatus EStatus;
14406   EStatus.Diag = &Notes;
14407 
14408   EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
14409                                       ? EvalInfo::EM_ConstantExpression
14410                                       : EvalInfo::EM_ConstantFold);
14411   Info.setEvaluatingDecl(VD, Value);
14412   Info.InConstantContext = true;
14413 
14414   SourceLocation DeclLoc = VD->getLocation();
14415   QualType DeclTy = VD->getType();
14416 
14417   if (Info.EnableNewConstInterp) {
14418     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
14419     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
14420       return false;
14421   } else {
14422     LValue LVal;
14423     LVal.set(VD);
14424 
14425     if (!EvaluateInPlace(Value, Info, LVal, this,
14426                          /*AllowNonLiteralTypes=*/true) ||
14427         EStatus.HasSideEffects)
14428       return false;
14429 
14430     // At this point, any lifetime-extended temporaries are completely
14431     // initialized.
14432     Info.performLifetimeExtension();
14433 
14434     if (!Info.discardCleanups())
14435       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14436   }
14437   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) &&
14438          CheckMemoryLeaks(Info);
14439 }
14440 
14441 bool VarDecl::evaluateDestruction(
14442     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
14443   Expr::EvalStatus EStatus;
14444   EStatus.Diag = &Notes;
14445 
14446   // Make a copy of the value for the destructor to mutate, if we know it.
14447   // Otherwise, treat the value as default-initialized; if the destructor works
14448   // anyway, then the destruction is constant (and must be essentially empty).
14449   APValue DestroyedValue;
14450   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
14451     DestroyedValue = *getEvaluatedValue();
14452   else if (!getDefaultInitValue(getType(), DestroyedValue))
14453     return false;
14454 
14455   EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression);
14456   Info.setEvaluatingDecl(this, DestroyedValue,
14457                          EvalInfo::EvaluatingDeclKind::Dtor);
14458   Info.InConstantContext = true;
14459 
14460   SourceLocation DeclLoc = getLocation();
14461   QualType DeclTy = getType();
14462 
14463   LValue LVal;
14464   LVal.set(this);
14465 
14466   if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) ||
14467       EStatus.HasSideEffects)
14468     return false;
14469 
14470   if (!Info.discardCleanups())
14471     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14472 
14473   ensureEvaluatedStmt()->HasConstantDestruction = true;
14474   return true;
14475 }
14476 
14477 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
14478 /// constant folded, but discard the result.
14479 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
14480   assert(!isValueDependent() &&
14481          "Expression evaluator can't be called on a dependent expression.");
14482 
14483   EvalResult Result;
14484   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
14485          !hasUnacceptableSideEffect(Result, SEK);
14486 }
14487 
14488 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
14489                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14490   assert(!isValueDependent() &&
14491          "Expression evaluator can't be called on a dependent expression.");
14492 
14493   EvalResult EVResult;
14494   EVResult.Diag = Diag;
14495   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14496   Info.InConstantContext = true;
14497 
14498   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
14499   (void)Result;
14500   assert(Result && "Could not evaluate expression");
14501   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14502 
14503   return EVResult.Val.getInt();
14504 }
14505 
14506 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
14507     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14508   assert(!isValueDependent() &&
14509          "Expression evaluator can't be called on a dependent expression.");
14510 
14511   EvalResult EVResult;
14512   EVResult.Diag = Diag;
14513   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14514   Info.InConstantContext = true;
14515   Info.CheckingForUndefinedBehavior = true;
14516 
14517   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
14518   (void)Result;
14519   assert(Result && "Could not evaluate expression");
14520   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14521 
14522   return EVResult.Val.getInt();
14523 }
14524 
14525 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
14526   assert(!isValueDependent() &&
14527          "Expression evaluator can't be called on a dependent expression.");
14528 
14529   bool IsConst;
14530   EvalResult EVResult;
14531   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
14532     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14533     Info.CheckingForUndefinedBehavior = true;
14534     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
14535   }
14536 }
14537 
14538 bool Expr::EvalResult::isGlobalLValue() const {
14539   assert(Val.isLValue());
14540   return IsGlobalLValue(Val.getLValueBase());
14541 }
14542 
14543 
14544 /// isIntegerConstantExpr - this recursive routine will test if an expression is
14545 /// an integer constant expression.
14546 
14547 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
14548 /// comma, etc
14549 
14550 // CheckICE - This function does the fundamental ICE checking: the returned
14551 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
14552 // and a (possibly null) SourceLocation indicating the location of the problem.
14553 //
14554 // Note that to reduce code duplication, this helper does no evaluation
14555 // itself; the caller checks whether the expression is evaluatable, and
14556 // in the rare cases where CheckICE actually cares about the evaluated
14557 // value, it calls into Evaluate.
14558 
14559 namespace {
14560 
14561 enum ICEKind {
14562   /// This expression is an ICE.
14563   IK_ICE,
14564   /// This expression is not an ICE, but if it isn't evaluated, it's
14565   /// a legal subexpression for an ICE. This return value is used to handle
14566   /// the comma operator in C99 mode, and non-constant subexpressions.
14567   IK_ICEIfUnevaluated,
14568   /// This expression is not an ICE, and is not a legal subexpression for one.
14569   IK_NotICE
14570 };
14571 
14572 struct ICEDiag {
14573   ICEKind Kind;
14574   SourceLocation Loc;
14575 
14576   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
14577 };
14578 
14579 }
14580 
14581 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
14582 
14583 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
14584 
14585 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
14586   Expr::EvalResult EVResult;
14587   Expr::EvalStatus Status;
14588   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
14589 
14590   Info.InConstantContext = true;
14591   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
14592       !EVResult.Val.isInt())
14593     return ICEDiag(IK_NotICE, E->getBeginLoc());
14594 
14595   return NoDiag();
14596 }
14597 
14598 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
14599   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
14600   if (!E->getType()->isIntegralOrEnumerationType())
14601     return ICEDiag(IK_NotICE, E->getBeginLoc());
14602 
14603   switch (E->getStmtClass()) {
14604 #define ABSTRACT_STMT(Node)
14605 #define STMT(Node, Base) case Expr::Node##Class:
14606 #define EXPR(Node, Base)
14607 #include "clang/AST/StmtNodes.inc"
14608   case Expr::PredefinedExprClass:
14609   case Expr::FloatingLiteralClass:
14610   case Expr::ImaginaryLiteralClass:
14611   case Expr::StringLiteralClass:
14612   case Expr::ArraySubscriptExprClass:
14613   case Expr::MatrixSubscriptExprClass:
14614   case Expr::OMPArraySectionExprClass:
14615   case Expr::OMPArrayShapingExprClass:
14616   case Expr::OMPIteratorExprClass:
14617   case Expr::MemberExprClass:
14618   case Expr::CompoundAssignOperatorClass:
14619   case Expr::CompoundLiteralExprClass:
14620   case Expr::ExtVectorElementExprClass:
14621   case Expr::DesignatedInitExprClass:
14622   case Expr::ArrayInitLoopExprClass:
14623   case Expr::ArrayInitIndexExprClass:
14624   case Expr::NoInitExprClass:
14625   case Expr::DesignatedInitUpdateExprClass:
14626   case Expr::ImplicitValueInitExprClass:
14627   case Expr::ParenListExprClass:
14628   case Expr::VAArgExprClass:
14629   case Expr::AddrLabelExprClass:
14630   case Expr::StmtExprClass:
14631   case Expr::CXXMemberCallExprClass:
14632   case Expr::CUDAKernelCallExprClass:
14633   case Expr::CXXAddrspaceCastExprClass:
14634   case Expr::CXXDynamicCastExprClass:
14635   case Expr::CXXTypeidExprClass:
14636   case Expr::CXXUuidofExprClass:
14637   case Expr::MSPropertyRefExprClass:
14638   case Expr::MSPropertySubscriptExprClass:
14639   case Expr::CXXNullPtrLiteralExprClass:
14640   case Expr::UserDefinedLiteralClass:
14641   case Expr::CXXThisExprClass:
14642   case Expr::CXXThrowExprClass:
14643   case Expr::CXXNewExprClass:
14644   case Expr::CXXDeleteExprClass:
14645   case Expr::CXXPseudoDestructorExprClass:
14646   case Expr::UnresolvedLookupExprClass:
14647   case Expr::TypoExprClass:
14648   case Expr::RecoveryExprClass:
14649   case Expr::DependentScopeDeclRefExprClass:
14650   case Expr::CXXConstructExprClass:
14651   case Expr::CXXInheritedCtorInitExprClass:
14652   case Expr::CXXStdInitializerListExprClass:
14653   case Expr::CXXBindTemporaryExprClass:
14654   case Expr::ExprWithCleanupsClass:
14655   case Expr::CXXTemporaryObjectExprClass:
14656   case Expr::CXXUnresolvedConstructExprClass:
14657   case Expr::CXXDependentScopeMemberExprClass:
14658   case Expr::UnresolvedMemberExprClass:
14659   case Expr::ObjCStringLiteralClass:
14660   case Expr::ObjCBoxedExprClass:
14661   case Expr::ObjCArrayLiteralClass:
14662   case Expr::ObjCDictionaryLiteralClass:
14663   case Expr::ObjCEncodeExprClass:
14664   case Expr::ObjCMessageExprClass:
14665   case Expr::ObjCSelectorExprClass:
14666   case Expr::ObjCProtocolExprClass:
14667   case Expr::ObjCIvarRefExprClass:
14668   case Expr::ObjCPropertyRefExprClass:
14669   case Expr::ObjCSubscriptRefExprClass:
14670   case Expr::ObjCIsaExprClass:
14671   case Expr::ObjCAvailabilityCheckExprClass:
14672   case Expr::ShuffleVectorExprClass:
14673   case Expr::ConvertVectorExprClass:
14674   case Expr::BlockExprClass:
14675   case Expr::NoStmtClass:
14676   case Expr::OpaqueValueExprClass:
14677   case Expr::PackExpansionExprClass:
14678   case Expr::SubstNonTypeTemplateParmPackExprClass:
14679   case Expr::FunctionParmPackExprClass:
14680   case Expr::AsTypeExprClass:
14681   case Expr::ObjCIndirectCopyRestoreExprClass:
14682   case Expr::MaterializeTemporaryExprClass:
14683   case Expr::PseudoObjectExprClass:
14684   case Expr::AtomicExprClass:
14685   case Expr::LambdaExprClass:
14686   case Expr::CXXFoldExprClass:
14687   case Expr::CoawaitExprClass:
14688   case Expr::DependentCoawaitExprClass:
14689   case Expr::CoyieldExprClass:
14690     return ICEDiag(IK_NotICE, E->getBeginLoc());
14691 
14692   case Expr::InitListExprClass: {
14693     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
14694     // form "T x = { a };" is equivalent to "T x = a;".
14695     // Unless we're initializing a reference, T is a scalar as it is known to be
14696     // of integral or enumeration type.
14697     if (E->isRValue())
14698       if (cast<InitListExpr>(E)->getNumInits() == 1)
14699         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
14700     return ICEDiag(IK_NotICE, E->getBeginLoc());
14701   }
14702 
14703   case Expr::SizeOfPackExprClass:
14704   case Expr::GNUNullExprClass:
14705   case Expr::SourceLocExprClass:
14706     return NoDiag();
14707 
14708   case Expr::SubstNonTypeTemplateParmExprClass:
14709     return
14710       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
14711 
14712   case Expr::ConstantExprClass:
14713     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
14714 
14715   case Expr::ParenExprClass:
14716     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
14717   case Expr::GenericSelectionExprClass:
14718     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
14719   case Expr::IntegerLiteralClass:
14720   case Expr::FixedPointLiteralClass:
14721   case Expr::CharacterLiteralClass:
14722   case Expr::ObjCBoolLiteralExprClass:
14723   case Expr::CXXBoolLiteralExprClass:
14724   case Expr::CXXScalarValueInitExprClass:
14725   case Expr::TypeTraitExprClass:
14726   case Expr::ConceptSpecializationExprClass:
14727   case Expr::RequiresExprClass:
14728   case Expr::ArrayTypeTraitExprClass:
14729   case Expr::ExpressionTraitExprClass:
14730   case Expr::CXXNoexceptExprClass:
14731     return NoDiag();
14732   case Expr::CallExprClass:
14733   case Expr::CXXOperatorCallExprClass: {
14734     // C99 6.6/3 allows function calls within unevaluated subexpressions of
14735     // constant expressions, but they can never be ICEs because an ICE cannot
14736     // contain an operand of (pointer to) function type.
14737     const CallExpr *CE = cast<CallExpr>(E);
14738     if (CE->getBuiltinCallee())
14739       return CheckEvalInICE(E, Ctx);
14740     return ICEDiag(IK_NotICE, E->getBeginLoc());
14741   }
14742   case Expr::CXXRewrittenBinaryOperatorClass:
14743     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
14744                     Ctx);
14745   case Expr::DeclRefExprClass: {
14746     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
14747       return NoDiag();
14748     const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
14749     if (Ctx.getLangOpts().CPlusPlus &&
14750         D && IsConstNonVolatile(D->getType())) {
14751       // Parameter variables are never constants.  Without this check,
14752       // getAnyInitializer() can find a default argument, which leads
14753       // to chaos.
14754       if (isa<ParmVarDecl>(D))
14755         return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14756 
14757       // C++ 7.1.5.1p2
14758       //   A variable of non-volatile const-qualified integral or enumeration
14759       //   type initialized by an ICE can be used in ICEs.
14760       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
14761         if (!Dcl->getType()->isIntegralOrEnumerationType())
14762           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14763 
14764         const VarDecl *VD;
14765         // Look for a declaration of this variable that has an initializer, and
14766         // check whether it is an ICE.
14767         if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
14768           return NoDiag();
14769         else
14770           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14771       }
14772     }
14773     return ICEDiag(IK_NotICE, E->getBeginLoc());
14774   }
14775   case Expr::UnaryOperatorClass: {
14776     const UnaryOperator *Exp = cast<UnaryOperator>(E);
14777     switch (Exp->getOpcode()) {
14778     case UO_PostInc:
14779     case UO_PostDec:
14780     case UO_PreInc:
14781     case UO_PreDec:
14782     case UO_AddrOf:
14783     case UO_Deref:
14784     case UO_Coawait:
14785       // C99 6.6/3 allows increment and decrement within unevaluated
14786       // subexpressions of constant expressions, but they can never be ICEs
14787       // because an ICE cannot contain an lvalue operand.
14788       return ICEDiag(IK_NotICE, E->getBeginLoc());
14789     case UO_Extension:
14790     case UO_LNot:
14791     case UO_Plus:
14792     case UO_Minus:
14793     case UO_Not:
14794     case UO_Real:
14795     case UO_Imag:
14796       return CheckICE(Exp->getSubExpr(), Ctx);
14797     }
14798     llvm_unreachable("invalid unary operator class");
14799   }
14800   case Expr::OffsetOfExprClass: {
14801     // Note that per C99, offsetof must be an ICE. And AFAIK, using
14802     // EvaluateAsRValue matches the proposed gcc behavior for cases like
14803     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
14804     // compliance: we should warn earlier for offsetof expressions with
14805     // array subscripts that aren't ICEs, and if the array subscripts
14806     // are ICEs, the value of the offsetof must be an integer constant.
14807     return CheckEvalInICE(E, Ctx);
14808   }
14809   case Expr::UnaryExprOrTypeTraitExprClass: {
14810     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
14811     if ((Exp->getKind() ==  UETT_SizeOf) &&
14812         Exp->getTypeOfArgument()->isVariableArrayType())
14813       return ICEDiag(IK_NotICE, E->getBeginLoc());
14814     return NoDiag();
14815   }
14816   case Expr::BinaryOperatorClass: {
14817     const BinaryOperator *Exp = cast<BinaryOperator>(E);
14818     switch (Exp->getOpcode()) {
14819     case BO_PtrMemD:
14820     case BO_PtrMemI:
14821     case BO_Assign:
14822     case BO_MulAssign:
14823     case BO_DivAssign:
14824     case BO_RemAssign:
14825     case BO_AddAssign:
14826     case BO_SubAssign:
14827     case BO_ShlAssign:
14828     case BO_ShrAssign:
14829     case BO_AndAssign:
14830     case BO_XorAssign:
14831     case BO_OrAssign:
14832       // C99 6.6/3 allows assignments within unevaluated subexpressions of
14833       // constant expressions, but they can never be ICEs because an ICE cannot
14834       // contain an lvalue operand.
14835       return ICEDiag(IK_NotICE, E->getBeginLoc());
14836 
14837     case BO_Mul:
14838     case BO_Div:
14839     case BO_Rem:
14840     case BO_Add:
14841     case BO_Sub:
14842     case BO_Shl:
14843     case BO_Shr:
14844     case BO_LT:
14845     case BO_GT:
14846     case BO_LE:
14847     case BO_GE:
14848     case BO_EQ:
14849     case BO_NE:
14850     case BO_And:
14851     case BO_Xor:
14852     case BO_Or:
14853     case BO_Comma:
14854     case BO_Cmp: {
14855       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
14856       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
14857       if (Exp->getOpcode() == BO_Div ||
14858           Exp->getOpcode() == BO_Rem) {
14859         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
14860         // we don't evaluate one.
14861         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
14862           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
14863           if (REval == 0)
14864             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14865           if (REval.isSigned() && REval.isAllOnesValue()) {
14866             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
14867             if (LEval.isMinSignedValue())
14868               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14869           }
14870         }
14871       }
14872       if (Exp->getOpcode() == BO_Comma) {
14873         if (Ctx.getLangOpts().C99) {
14874           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
14875           // if it isn't evaluated.
14876           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
14877             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14878         } else {
14879           // In both C89 and C++, commas in ICEs are illegal.
14880           return ICEDiag(IK_NotICE, E->getBeginLoc());
14881         }
14882       }
14883       return Worst(LHSResult, RHSResult);
14884     }
14885     case BO_LAnd:
14886     case BO_LOr: {
14887       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
14888       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
14889       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
14890         // Rare case where the RHS has a comma "side-effect"; we need
14891         // to actually check the condition to see whether the side
14892         // with the comma is evaluated.
14893         if ((Exp->getOpcode() == BO_LAnd) !=
14894             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
14895           return RHSResult;
14896         return NoDiag();
14897       }
14898 
14899       return Worst(LHSResult, RHSResult);
14900     }
14901     }
14902     llvm_unreachable("invalid binary operator kind");
14903   }
14904   case Expr::ImplicitCastExprClass:
14905   case Expr::CStyleCastExprClass:
14906   case Expr::CXXFunctionalCastExprClass:
14907   case Expr::CXXStaticCastExprClass:
14908   case Expr::CXXReinterpretCastExprClass:
14909   case Expr::CXXConstCastExprClass:
14910   case Expr::ObjCBridgedCastExprClass: {
14911     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
14912     if (isa<ExplicitCastExpr>(E)) {
14913       if (const FloatingLiteral *FL
14914             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
14915         unsigned DestWidth = Ctx.getIntWidth(E->getType());
14916         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
14917         APSInt IgnoredVal(DestWidth, !DestSigned);
14918         bool Ignored;
14919         // If the value does not fit in the destination type, the behavior is
14920         // undefined, so we are not required to treat it as a constant
14921         // expression.
14922         if (FL->getValue().convertToInteger(IgnoredVal,
14923                                             llvm::APFloat::rmTowardZero,
14924                                             &Ignored) & APFloat::opInvalidOp)
14925           return ICEDiag(IK_NotICE, E->getBeginLoc());
14926         return NoDiag();
14927       }
14928     }
14929     switch (cast<CastExpr>(E)->getCastKind()) {
14930     case CK_LValueToRValue:
14931     case CK_AtomicToNonAtomic:
14932     case CK_NonAtomicToAtomic:
14933     case CK_NoOp:
14934     case CK_IntegralToBoolean:
14935     case CK_IntegralCast:
14936       return CheckICE(SubExpr, Ctx);
14937     default:
14938       return ICEDiag(IK_NotICE, E->getBeginLoc());
14939     }
14940   }
14941   case Expr::BinaryConditionalOperatorClass: {
14942     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
14943     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
14944     if (CommonResult.Kind == IK_NotICE) return CommonResult;
14945     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
14946     if (FalseResult.Kind == IK_NotICE) return FalseResult;
14947     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
14948     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
14949         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
14950     return FalseResult;
14951   }
14952   case Expr::ConditionalOperatorClass: {
14953     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
14954     // If the condition (ignoring parens) is a __builtin_constant_p call,
14955     // then only the true side is actually considered in an integer constant
14956     // expression, and it is fully evaluated.  This is an important GNU
14957     // extension.  See GCC PR38377 for discussion.
14958     if (const CallExpr *CallCE
14959         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
14960       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
14961         return CheckEvalInICE(E, Ctx);
14962     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
14963     if (CondResult.Kind == IK_NotICE)
14964       return CondResult;
14965 
14966     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
14967     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
14968 
14969     if (TrueResult.Kind == IK_NotICE)
14970       return TrueResult;
14971     if (FalseResult.Kind == IK_NotICE)
14972       return FalseResult;
14973     if (CondResult.Kind == IK_ICEIfUnevaluated)
14974       return CondResult;
14975     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
14976       return NoDiag();
14977     // Rare case where the diagnostics depend on which side is evaluated
14978     // Note that if we get here, CondResult is 0, and at least one of
14979     // TrueResult and FalseResult is non-zero.
14980     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
14981       return FalseResult;
14982     return TrueResult;
14983   }
14984   case Expr::CXXDefaultArgExprClass:
14985     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
14986   case Expr::CXXDefaultInitExprClass:
14987     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
14988   case Expr::ChooseExprClass: {
14989     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
14990   }
14991   case Expr::BuiltinBitCastExprClass: {
14992     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
14993       return ICEDiag(IK_NotICE, E->getBeginLoc());
14994     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
14995   }
14996   }
14997 
14998   llvm_unreachable("Invalid StmtClass!");
14999 }
15000 
15001 /// Evaluate an expression as a C++11 integral constant expression.
15002 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15003                                                     const Expr *E,
15004                                                     llvm::APSInt *Value,
15005                                                     SourceLocation *Loc) {
15006   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15007     if (Loc) *Loc = E->getExprLoc();
15008     return false;
15009   }
15010 
15011   APValue Result;
15012   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15013     return false;
15014 
15015   if (!Result.isInt()) {
15016     if (Loc) *Loc = E->getExprLoc();
15017     return false;
15018   }
15019 
15020   if (Value) *Value = Result.getInt();
15021   return true;
15022 }
15023 
15024 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
15025                                  SourceLocation *Loc) const {
15026   assert(!isValueDependent() &&
15027          "Expression evaluator can't be called on a dependent expression.");
15028 
15029   if (Ctx.getLangOpts().CPlusPlus11)
15030     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
15031 
15032   ICEDiag D = CheckICE(this, Ctx);
15033   if (D.Kind != IK_ICE) {
15034     if (Loc) *Loc = D.Loc;
15035     return false;
15036   }
15037   return true;
15038 }
15039 
15040 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx,
15041                                                     SourceLocation *Loc,
15042                                                     bool isEvaluated) const {
15043   assert(!isValueDependent() &&
15044          "Expression evaluator can't be called on a dependent expression.");
15045 
15046   APSInt Value;
15047 
15048   if (Ctx.getLangOpts().CPlusPlus11) {
15049     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
15050       return Value;
15051     return None;
15052   }
15053 
15054   if (!isIntegerConstantExpr(Ctx, Loc))
15055     return None;
15056 
15057   // The only possible side-effects here are due to UB discovered in the
15058   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
15059   // required to treat the expression as an ICE, so we produce the folded
15060   // value.
15061   EvalResult ExprResult;
15062   Expr::EvalStatus Status;
15063   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
15064   Info.InConstantContext = true;
15065 
15066   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
15067     llvm_unreachable("ICE cannot be evaluated!");
15068 
15069   return ExprResult.Val.getInt();
15070 }
15071 
15072 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
15073   assert(!isValueDependent() &&
15074          "Expression evaluator can't be called on a dependent expression.");
15075 
15076   return CheckICE(this, Ctx).Kind == IK_ICE;
15077 }
15078 
15079 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
15080                                SourceLocation *Loc) const {
15081   assert(!isValueDependent() &&
15082          "Expression evaluator can't be called on a dependent expression.");
15083 
15084   // We support this checking in C++98 mode in order to diagnose compatibility
15085   // issues.
15086   assert(Ctx.getLangOpts().CPlusPlus);
15087 
15088   // Build evaluation settings.
15089   Expr::EvalStatus Status;
15090   SmallVector<PartialDiagnosticAt, 8> Diags;
15091   Status.Diag = &Diags;
15092   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15093 
15094   APValue Scratch;
15095   bool IsConstExpr =
15096       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
15097       // FIXME: We don't produce a diagnostic for this, but the callers that
15098       // call us on arbitrary full-expressions should generally not care.
15099       Info.discardCleanups() && !Status.HasSideEffects;
15100 
15101   if (!Diags.empty()) {
15102     IsConstExpr = false;
15103     if (Loc) *Loc = Diags[0].first;
15104   } else if (!IsConstExpr) {
15105     // FIXME: This shouldn't happen.
15106     if (Loc) *Loc = getExprLoc();
15107   }
15108 
15109   return IsConstExpr;
15110 }
15111 
15112 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
15113                                     const FunctionDecl *Callee,
15114                                     ArrayRef<const Expr*> Args,
15115                                     const Expr *This) const {
15116   assert(!isValueDependent() &&
15117          "Expression evaluator can't be called on a dependent expression.");
15118 
15119   Expr::EvalStatus Status;
15120   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
15121   Info.InConstantContext = true;
15122 
15123   LValue ThisVal;
15124   const LValue *ThisPtr = nullptr;
15125   if (This) {
15126 #ifndef NDEBUG
15127     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
15128     assert(MD && "Don't provide `this` for non-methods.");
15129     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
15130 #endif
15131     if (!This->isValueDependent() &&
15132         EvaluateObjectArgument(Info, This, ThisVal) &&
15133         !Info.EvalStatus.HasSideEffects)
15134       ThisPtr = &ThisVal;
15135 
15136     // Ignore any side-effects from a failed evaluation. This is safe because
15137     // they can't interfere with any other argument evaluation.
15138     Info.EvalStatus.HasSideEffects = false;
15139   }
15140 
15141   ArgVector ArgValues(Args.size());
15142   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
15143        I != E; ++I) {
15144     if ((*I)->isValueDependent() ||
15145         !Evaluate(ArgValues[I - Args.begin()], Info, *I) ||
15146         Info.EvalStatus.HasSideEffects)
15147       // If evaluation fails, throw away the argument entirely.
15148       ArgValues[I - Args.begin()] = APValue();
15149 
15150     // Ignore any side-effects from a failed evaluation. This is safe because
15151     // they can't interfere with any other argument evaluation.
15152     Info.EvalStatus.HasSideEffects = false;
15153   }
15154 
15155   // Parameter cleanups happen in the caller and are not part of this
15156   // evaluation.
15157   Info.discardCleanups();
15158   Info.EvalStatus.HasSideEffects = false;
15159 
15160   // Build fake call to Callee.
15161   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
15162                        ArgValues.data());
15163   // FIXME: Missing ExprWithCleanups in enable_if conditions?
15164   FullExpressionRAII Scope(Info);
15165   return Evaluate(Value, Info, this) && Scope.destroy() &&
15166          !Info.EvalStatus.HasSideEffects;
15167 }
15168 
15169 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
15170                                    SmallVectorImpl<
15171                                      PartialDiagnosticAt> &Diags) {
15172   // FIXME: It would be useful to check constexpr function templates, but at the
15173   // moment the constant expression evaluator cannot cope with the non-rigorous
15174   // ASTs which we build for dependent expressions.
15175   if (FD->isDependentContext())
15176     return true;
15177 
15178   // Bail out if a constexpr constructor has an initializer that contains an
15179   // error. We deliberately don't produce a diagnostic, as we have produced a
15180   // relevant diagnostic when parsing the error initializer.
15181   if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15182     for (const auto *InitExpr : Ctor->inits()) {
15183       if (InitExpr->getInit() && InitExpr->getInit()->containsErrors())
15184         return false;
15185     }
15186   }
15187   Expr::EvalStatus Status;
15188   Status.Diag = &Diags;
15189 
15190   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
15191   Info.InConstantContext = true;
15192   Info.CheckingPotentialConstantExpression = true;
15193 
15194   // The constexpr VM attempts to compile all methods to bytecode here.
15195   if (Info.EnableNewConstInterp) {
15196     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
15197     return Diags.empty();
15198   }
15199 
15200   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
15201   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
15202 
15203   // Fabricate an arbitrary expression on the stack and pretend that it
15204   // is a temporary being used as the 'this' pointer.
15205   LValue This;
15206   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
15207   This.set({&VIE, Info.CurrentCall->Index});
15208 
15209   ArrayRef<const Expr*> Args;
15210 
15211   APValue Scratch;
15212   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
15213     // Evaluate the call as a constant initializer, to allow the construction
15214     // of objects of non-literal types.
15215     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
15216     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
15217   } else {
15218     SourceLocation Loc = FD->getLocation();
15219     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
15220                        Args, FD->getBody(), Info, Scratch, nullptr);
15221   }
15222 
15223   return Diags.empty();
15224 }
15225 
15226 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
15227                                               const FunctionDecl *FD,
15228                                               SmallVectorImpl<
15229                                                 PartialDiagnosticAt> &Diags) {
15230   assert(!E->isValueDependent() &&
15231          "Expression evaluator can't be called on a dependent expression.");
15232 
15233   Expr::EvalStatus Status;
15234   Status.Diag = &Diags;
15235 
15236   EvalInfo Info(FD->getASTContext(), Status,
15237                 EvalInfo::EM_ConstantExpressionUnevaluated);
15238   Info.InConstantContext = true;
15239   Info.CheckingPotentialConstantExpression = true;
15240 
15241   // Fabricate a call stack frame to give the arguments a plausible cover story.
15242   ArrayRef<const Expr*> Args;
15243   ArgVector ArgValues(0);
15244   bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
15245   (void)Success;
15246   assert(Success &&
15247          "Failed to set up arguments for potential constant evaluation");
15248   CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
15249 
15250   APValue ResultScratch;
15251   Evaluate(ResultScratch, Info, E);
15252   return Diags.empty();
15253 }
15254 
15255 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
15256                                  unsigned Type) const {
15257   if (!getType()->isPointerType())
15258     return false;
15259 
15260   Expr::EvalStatus Status;
15261   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15262   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
15263 }
15264