1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Expr constant evaluator.
10 //
11 // Constant expression evaluation produces four main results:
12 //
13 //  * A success/failure flag indicating whether constant folding was successful.
14 //    This is the 'bool' return value used by most of the code in this file. A
15 //    'false' return value indicates that constant folding has failed, and any
16 //    appropriate diagnostic has already been produced.
17 //
18 //  * An evaluated result, valid only if constant folding has not failed.
19 //
20 //  * A flag indicating if evaluation encountered (unevaluated) side-effects.
21 //    These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22 //    where it is possible to determine the evaluated result regardless.
23 //
24 //  * A set of notes indicating why the evaluation was not a constant expression
25 //    (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26 //    too, why the expression could not be folded.
27 //
28 // If we are checking for a potential constant expression, failure to constant
29 // fold a potential constant sub-expression will be indicated by a 'false'
30 // return value (the expression could not be folded) and no diagnostic (the
31 // expression is not necessarily non-constant).
32 //
33 //===----------------------------------------------------------------------===//
34 
35 #include "Interp/Context.h"
36 #include "Interp/Frame.h"
37 #include "Interp/State.h"
38 #include "clang/AST/APValue.h"
39 #include "clang/AST/ASTContext.h"
40 #include "clang/AST/ASTDiagnostic.h"
41 #include "clang/AST/ASTLambda.h"
42 #include "clang/AST/Attr.h"
43 #include "clang/AST/CXXInheritance.h"
44 #include "clang/AST/CharUnits.h"
45 #include "clang/AST/CurrentSourceLocExprScope.h"
46 #include "clang/AST/Expr.h"
47 #include "clang/AST/OSLog.h"
48 #include "clang/AST/OptionalDiagnostic.h"
49 #include "clang/AST/RecordLayout.h"
50 #include "clang/AST/StmtVisitor.h"
51 #include "clang/AST/TypeLoc.h"
52 #include "clang/Basic/Builtins.h"
53 #include "clang/Basic/FixedPoint.h"
54 #include "clang/Basic/TargetInfo.h"
55 #include "llvm/ADT/Optional.h"
56 #include "llvm/ADT/SmallBitVector.h"
57 #include "llvm/Support/SaveAndRestore.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include <cstring>
60 #include <functional>
61 
62 #define DEBUG_TYPE "exprconstant"
63 
64 using namespace clang;
65 using llvm::APInt;
66 using llvm::APSInt;
67 using llvm::APFloat;
68 using llvm::Optional;
69 
70 namespace {
71   struct LValue;
72   class CallStackFrame;
73   class EvalInfo;
74 
75   using SourceLocExprScopeGuard =
76       CurrentSourceLocExprScope::SourceLocExprScopeGuard;
77 
78   static QualType getType(APValue::LValueBase B) {
79     if (!B) return QualType();
80     if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
81       // FIXME: It's unclear where we're supposed to take the type from, and
82       // this actually matters for arrays of unknown bound. Eg:
83       //
84       // extern int arr[]; void f() { extern int arr[3]; };
85       // constexpr int *p = &arr[1]; // valid?
86       //
87       // For now, we take the array bound from the most recent declaration.
88       for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
89            Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
90         QualType T = Redecl->getType();
91         if (!T->isIncompleteArrayType())
92           return T;
93       }
94       return D->getType();
95     }
96 
97     if (B.is<TypeInfoLValue>())
98       return B.getTypeInfoType();
99 
100     if (B.is<DynamicAllocLValue>())
101       return B.getDynamicAllocType();
102 
103     const Expr *Base = B.get<const Expr*>();
104 
105     // For a materialized temporary, the type of the temporary we materialized
106     // may not be the type of the expression.
107     if (const MaterializeTemporaryExpr *MTE =
108             dyn_cast<MaterializeTemporaryExpr>(Base)) {
109       SmallVector<const Expr *, 2> CommaLHSs;
110       SmallVector<SubobjectAdjustment, 2> Adjustments;
111       const Expr *Temp = MTE->getSubExpr();
112       const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
113                                                                Adjustments);
114       // Keep any cv-qualifiers from the reference if we generated a temporary
115       // for it directly. Otherwise use the type after adjustment.
116       if (!Adjustments.empty())
117         return Inner->getType();
118     }
119 
120     return Base->getType();
121   }
122 
123   /// Get an LValue path entry, which is known to not be an array index, as a
124   /// field declaration.
125   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
126     return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
127   }
128   /// Get an LValue path entry, which is known to not be an array index, as a
129   /// base class declaration.
130   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
131     return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
132   }
133   /// Determine whether this LValue path entry for a base class names a virtual
134   /// base class.
135   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
136     return E.getAsBaseOrMember().getInt();
137   }
138 
139   /// Given an expression, determine the type used to store the result of
140   /// evaluating that expression.
141   static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
142     if (E->isRValue())
143       return E->getType();
144     return Ctx.getLValueReferenceType(E->getType());
145   }
146 
147   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
148   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
149     const FunctionDecl *Callee = CE->getDirectCallee();
150     return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
151   }
152 
153   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
154   /// This will look through a single cast.
155   ///
156   /// Returns null if we couldn't unwrap a function with alloc_size.
157   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
158     if (!E->getType()->isPointerType())
159       return nullptr;
160 
161     E = E->IgnoreParens();
162     // If we're doing a variable assignment from e.g. malloc(N), there will
163     // probably be a cast of some kind. In exotic cases, we might also see a
164     // top-level ExprWithCleanups. Ignore them either way.
165     if (const auto *FE = dyn_cast<FullExpr>(E))
166       E = FE->getSubExpr()->IgnoreParens();
167 
168     if (const auto *Cast = dyn_cast<CastExpr>(E))
169       E = Cast->getSubExpr()->IgnoreParens();
170 
171     if (const auto *CE = dyn_cast<CallExpr>(E))
172       return getAllocSizeAttr(CE) ? CE : nullptr;
173     return nullptr;
174   }
175 
176   /// Determines whether or not the given Base contains a call to a function
177   /// with the alloc_size attribute.
178   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
179     const auto *E = Base.dyn_cast<const Expr *>();
180     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
181   }
182 
183   /// The bound to claim that an array of unknown bound has.
184   /// The value in MostDerivedArraySize is undefined in this case. So, set it
185   /// to an arbitrary value that's likely to loudly break things if it's used.
186   static const uint64_t AssumedSizeForUnsizedArray =
187       std::numeric_limits<uint64_t>::max() / 2;
188 
189   /// Determines if an LValue with the given LValueBase will have an unsized
190   /// array in its designator.
191   /// Find the path length and type of the most-derived subobject in the given
192   /// path, and find the size of the containing array, if any.
193   static unsigned
194   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
195                            ArrayRef<APValue::LValuePathEntry> Path,
196                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
197                            bool &FirstEntryIsUnsizedArray) {
198     // This only accepts LValueBases from APValues, and APValues don't support
199     // arrays that lack size info.
200     assert(!isBaseAnAllocSizeCall(Base) &&
201            "Unsized arrays shouldn't appear here");
202     unsigned MostDerivedLength = 0;
203     Type = getType(Base);
204 
205     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
206       if (Type->isArrayType()) {
207         const ArrayType *AT = Ctx.getAsArrayType(Type);
208         Type = AT->getElementType();
209         MostDerivedLength = I + 1;
210         IsArray = true;
211 
212         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
213           ArraySize = CAT->getSize().getZExtValue();
214         } else {
215           assert(I == 0 && "unexpected unsized array designator");
216           FirstEntryIsUnsizedArray = true;
217           ArraySize = AssumedSizeForUnsizedArray;
218         }
219       } else if (Type->isAnyComplexType()) {
220         const ComplexType *CT = Type->castAs<ComplexType>();
221         Type = CT->getElementType();
222         ArraySize = 2;
223         MostDerivedLength = I + 1;
224         IsArray = true;
225       } else if (const FieldDecl *FD = getAsField(Path[I])) {
226         Type = FD->getType();
227         ArraySize = 0;
228         MostDerivedLength = I + 1;
229         IsArray = false;
230       } else {
231         // Path[I] describes a base class.
232         ArraySize = 0;
233         IsArray = false;
234       }
235     }
236     return MostDerivedLength;
237   }
238 
239   /// A path from a glvalue to a subobject of that glvalue.
240   struct SubobjectDesignator {
241     /// True if the subobject was named in a manner not supported by C++11. Such
242     /// lvalues can still be folded, but they are not core constant expressions
243     /// and we cannot perform lvalue-to-rvalue conversions on them.
244     unsigned Invalid : 1;
245 
246     /// Is this a pointer one past the end of an object?
247     unsigned IsOnePastTheEnd : 1;
248 
249     /// Indicator of whether the first entry is an unsized array.
250     unsigned FirstEntryIsAnUnsizedArray : 1;
251 
252     /// Indicator of whether the most-derived object is an array element.
253     unsigned MostDerivedIsArrayElement : 1;
254 
255     /// The length of the path to the most-derived object of which this is a
256     /// subobject.
257     unsigned MostDerivedPathLength : 28;
258 
259     /// The size of the array of which the most-derived object is an element.
260     /// This will always be 0 if the most-derived object is not an array
261     /// element. 0 is not an indicator of whether or not the most-derived object
262     /// is an array, however, because 0-length arrays are allowed.
263     ///
264     /// If the current array is an unsized array, the value of this is
265     /// undefined.
266     uint64_t MostDerivedArraySize;
267 
268     /// The type of the most derived object referred to by this address.
269     QualType MostDerivedType;
270 
271     typedef APValue::LValuePathEntry PathEntry;
272 
273     /// The entries on the path from the glvalue to the designated subobject.
274     SmallVector<PathEntry, 8> Entries;
275 
276     SubobjectDesignator() : Invalid(true) {}
277 
278     explicit SubobjectDesignator(QualType T)
279         : Invalid(false), IsOnePastTheEnd(false),
280           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
281           MostDerivedPathLength(0), MostDerivedArraySize(0),
282           MostDerivedType(T) {}
283 
284     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
285         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
286           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
287           MostDerivedPathLength(0), MostDerivedArraySize(0) {
288       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
289       if (!Invalid) {
290         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
291         ArrayRef<PathEntry> VEntries = V.getLValuePath();
292         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
293         if (V.getLValueBase()) {
294           bool IsArray = false;
295           bool FirstIsUnsizedArray = false;
296           MostDerivedPathLength = findMostDerivedSubobject(
297               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
298               MostDerivedType, IsArray, FirstIsUnsizedArray);
299           MostDerivedIsArrayElement = IsArray;
300           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
301         }
302       }
303     }
304 
305     void truncate(ASTContext &Ctx, APValue::LValueBase Base,
306                   unsigned NewLength) {
307       if (Invalid)
308         return;
309 
310       assert(Base && "cannot truncate path for null pointer");
311       assert(NewLength <= Entries.size() && "not a truncation");
312 
313       if (NewLength == Entries.size())
314         return;
315       Entries.resize(NewLength);
316 
317       bool IsArray = false;
318       bool FirstIsUnsizedArray = false;
319       MostDerivedPathLength = findMostDerivedSubobject(
320           Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
321           FirstIsUnsizedArray);
322       MostDerivedIsArrayElement = IsArray;
323       FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
324     }
325 
326     void setInvalid() {
327       Invalid = true;
328       Entries.clear();
329     }
330 
331     /// Determine whether the most derived subobject is an array without a
332     /// known bound.
333     bool isMostDerivedAnUnsizedArray() const {
334       assert(!Invalid && "Calling this makes no sense on invalid designators");
335       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
336     }
337 
338     /// Determine what the most derived array's size is. Results in an assertion
339     /// failure if the most derived array lacks a size.
340     uint64_t getMostDerivedArraySize() const {
341       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
342       return MostDerivedArraySize;
343     }
344 
345     /// Determine whether this is a one-past-the-end pointer.
346     bool isOnePastTheEnd() const {
347       assert(!Invalid);
348       if (IsOnePastTheEnd)
349         return true;
350       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
351           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
352               MostDerivedArraySize)
353         return true;
354       return false;
355     }
356 
357     /// Get the range of valid index adjustments in the form
358     ///   {maximum value that can be subtracted from this pointer,
359     ///    maximum value that can be added to this pointer}
360     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
361       if (Invalid || isMostDerivedAnUnsizedArray())
362         return {0, 0};
363 
364       // [expr.add]p4: For the purposes of these operators, a pointer to a
365       // nonarray object behaves the same as a pointer to the first element of
366       // an array of length one with the type of the object as its element type.
367       bool IsArray = MostDerivedPathLength == Entries.size() &&
368                      MostDerivedIsArrayElement;
369       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
370                                     : (uint64_t)IsOnePastTheEnd;
371       uint64_t ArraySize =
372           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
373       return {ArrayIndex, ArraySize - ArrayIndex};
374     }
375 
376     /// Check that this refers to a valid subobject.
377     bool isValidSubobject() const {
378       if (Invalid)
379         return false;
380       return !isOnePastTheEnd();
381     }
382     /// Check that this refers to a valid subobject, and if not, produce a
383     /// relevant diagnostic and set the designator as invalid.
384     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
385 
386     /// Get the type of the designated object.
387     QualType getType(ASTContext &Ctx) const {
388       assert(!Invalid && "invalid designator has no subobject type");
389       return MostDerivedPathLength == Entries.size()
390                  ? MostDerivedType
391                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
392     }
393 
394     /// Update this designator to refer to the first element within this array.
395     void addArrayUnchecked(const ConstantArrayType *CAT) {
396       Entries.push_back(PathEntry::ArrayIndex(0));
397 
398       // This is a most-derived object.
399       MostDerivedType = CAT->getElementType();
400       MostDerivedIsArrayElement = true;
401       MostDerivedArraySize = CAT->getSize().getZExtValue();
402       MostDerivedPathLength = Entries.size();
403     }
404     /// Update this designator to refer to the first element within the array of
405     /// elements of type T. This is an array of unknown size.
406     void addUnsizedArrayUnchecked(QualType ElemTy) {
407       Entries.push_back(PathEntry::ArrayIndex(0));
408 
409       MostDerivedType = ElemTy;
410       MostDerivedIsArrayElement = true;
411       // The value in MostDerivedArraySize is undefined in this case. So, set it
412       // to an arbitrary value that's likely to loudly break things if it's
413       // used.
414       MostDerivedArraySize = AssumedSizeForUnsizedArray;
415       MostDerivedPathLength = Entries.size();
416     }
417     /// Update this designator to refer to the given base or member of this
418     /// object.
419     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
420       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
421 
422       // If this isn't a base class, it's a new most-derived object.
423       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
424         MostDerivedType = FD->getType();
425         MostDerivedIsArrayElement = false;
426         MostDerivedArraySize = 0;
427         MostDerivedPathLength = Entries.size();
428       }
429     }
430     /// Update this designator to refer to the given complex component.
431     void addComplexUnchecked(QualType EltTy, bool Imag) {
432       Entries.push_back(PathEntry::ArrayIndex(Imag));
433 
434       // This is technically a most-derived object, though in practice this
435       // is unlikely to matter.
436       MostDerivedType = EltTy;
437       MostDerivedIsArrayElement = true;
438       MostDerivedArraySize = 2;
439       MostDerivedPathLength = Entries.size();
440     }
441     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
442     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
443                                    const APSInt &N);
444     /// Add N to the address of this subobject.
445     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
446       if (Invalid || !N) return;
447       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
448       if (isMostDerivedAnUnsizedArray()) {
449         diagnoseUnsizedArrayPointerArithmetic(Info, E);
450         // Can't verify -- trust that the user is doing the right thing (or if
451         // not, trust that the caller will catch the bad behavior).
452         // FIXME: Should we reject if this overflows, at least?
453         Entries.back() = PathEntry::ArrayIndex(
454             Entries.back().getAsArrayIndex() + TruncatedN);
455         return;
456       }
457 
458       // [expr.add]p4: For the purposes of these operators, a pointer to a
459       // nonarray object behaves the same as a pointer to the first element of
460       // an array of length one with the type of the object as its element type.
461       bool IsArray = MostDerivedPathLength == Entries.size() &&
462                      MostDerivedIsArrayElement;
463       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
464                                     : (uint64_t)IsOnePastTheEnd;
465       uint64_t ArraySize =
466           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
467 
468       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
469         // Calculate the actual index in a wide enough type, so we can include
470         // it in the note.
471         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
472         (llvm::APInt&)N += ArrayIndex;
473         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
474         diagnosePointerArithmetic(Info, E, N);
475         setInvalid();
476         return;
477       }
478 
479       ArrayIndex += TruncatedN;
480       assert(ArrayIndex <= ArraySize &&
481              "bounds check succeeded for out-of-bounds index");
482 
483       if (IsArray)
484         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
485       else
486         IsOnePastTheEnd = (ArrayIndex != 0);
487     }
488   };
489 
490   /// A stack frame in the constexpr call stack.
491   class CallStackFrame : public interp::Frame {
492   public:
493     EvalInfo &Info;
494 
495     /// Parent - The caller of this stack frame.
496     CallStackFrame *Caller;
497 
498     /// Callee - The function which was called.
499     const FunctionDecl *Callee;
500 
501     /// This - The binding for the this pointer in this call, if any.
502     const LValue *This;
503 
504     /// Arguments - Parameter bindings for this function call, indexed by
505     /// parameters' function scope indices.
506     APValue *Arguments;
507 
508     /// Source location information about the default argument or default
509     /// initializer expression we're evaluating, if any.
510     CurrentSourceLocExprScope CurSourceLocExprScope;
511 
512     // Note that we intentionally use std::map here so that references to
513     // values are stable.
514     typedef std::pair<const void *, unsigned> MapKeyTy;
515     typedef std::map<MapKeyTy, APValue> MapTy;
516     /// Temporaries - Temporary lvalues materialized within this stack frame.
517     MapTy Temporaries;
518 
519     /// CallLoc - The location of the call expression for this call.
520     SourceLocation CallLoc;
521 
522     /// Index - The call index of this call.
523     unsigned Index;
524 
525     /// The stack of integers for tracking version numbers for temporaries.
526     SmallVector<unsigned, 2> TempVersionStack = {1};
527     unsigned CurTempVersion = TempVersionStack.back();
528 
529     unsigned getTempVersion() const { return TempVersionStack.back(); }
530 
531     void pushTempVersion() {
532       TempVersionStack.push_back(++CurTempVersion);
533     }
534 
535     void popTempVersion() {
536       TempVersionStack.pop_back();
537     }
538 
539     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
540     // on the overall stack usage of deeply-recursing constexpr evaluations.
541     // (We should cache this map rather than recomputing it repeatedly.)
542     // But let's try this and see how it goes; we can look into caching the map
543     // as a later change.
544 
545     /// LambdaCaptureFields - Mapping from captured variables/this to
546     /// corresponding data members in the closure class.
547     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
548     FieldDecl *LambdaThisCaptureField;
549 
550     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
551                    const FunctionDecl *Callee, const LValue *This,
552                    APValue *Arguments);
553     ~CallStackFrame();
554 
555     // Return the temporary for Key whose version number is Version.
556     APValue *getTemporary(const void *Key, unsigned Version) {
557       MapKeyTy KV(Key, Version);
558       auto LB = Temporaries.lower_bound(KV);
559       if (LB != Temporaries.end() && LB->first == KV)
560         return &LB->second;
561       // Pair (Key,Version) wasn't found in the map. Check that no elements
562       // in the map have 'Key' as their key.
563       assert((LB == Temporaries.end() || LB->first.first != Key) &&
564              (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
565              "Element with key 'Key' found in map");
566       return nullptr;
567     }
568 
569     // Return the current temporary for Key in the map.
570     APValue *getCurrentTemporary(const void *Key) {
571       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
572       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
573         return &std::prev(UB)->second;
574       return nullptr;
575     }
576 
577     // Return the version number of the current temporary for Key.
578     unsigned getCurrentTemporaryVersion(const void *Key) const {
579       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
580       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
581         return std::prev(UB)->first.second;
582       return 0;
583     }
584 
585     /// Allocate storage for an object of type T in this stack frame.
586     /// Populates LV with a handle to the created object. Key identifies
587     /// the temporary within the stack frame, and must not be reused without
588     /// bumping the temporary version number.
589     template<typename KeyT>
590     APValue &createTemporary(const KeyT *Key, QualType T,
591                              bool IsLifetimeExtended, LValue &LV);
592 
593     void describe(llvm::raw_ostream &OS) override;
594 
595     Frame *getCaller() const override { return Caller; }
596     SourceLocation getCallLocation() const override { return CallLoc; }
597     const FunctionDecl *getCallee() const override { return Callee; }
598 
599     bool isStdFunction() const {
600       for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
601         if (DC->isStdNamespace())
602           return true;
603       return false;
604     }
605   };
606 
607   /// Temporarily override 'this'.
608   class ThisOverrideRAII {
609   public:
610     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
611         : Frame(Frame), OldThis(Frame.This) {
612       if (Enable)
613         Frame.This = NewThis;
614     }
615     ~ThisOverrideRAII() {
616       Frame.This = OldThis;
617     }
618   private:
619     CallStackFrame &Frame;
620     const LValue *OldThis;
621   };
622 }
623 
624 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
625                               const LValue &This, QualType ThisType);
626 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
627                               APValue::LValueBase LVBase, APValue &Value,
628                               QualType T);
629 
630 namespace {
631   /// A cleanup, and a flag indicating whether it is lifetime-extended.
632   class Cleanup {
633     llvm::PointerIntPair<APValue*, 1, bool> Value;
634     APValue::LValueBase Base;
635     QualType T;
636 
637   public:
638     Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
639             bool IsLifetimeExtended)
640         : Value(Val, IsLifetimeExtended), Base(Base), T(T) {}
641 
642     bool isLifetimeExtended() const { return Value.getInt(); }
643     bool endLifetime(EvalInfo &Info, bool RunDestructors) {
644       if (RunDestructors) {
645         SourceLocation Loc;
646         if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
647           Loc = VD->getLocation();
648         else if (const Expr *E = Base.dyn_cast<const Expr*>())
649           Loc = E->getExprLoc();
650         return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
651       }
652       *Value.getPointer() = APValue();
653       return true;
654     }
655 
656     bool hasSideEffect() {
657       return T.isDestructedType();
658     }
659   };
660 
661   /// A reference to an object whose construction we are currently evaluating.
662   struct ObjectUnderConstruction {
663     APValue::LValueBase Base;
664     ArrayRef<APValue::LValuePathEntry> Path;
665     friend bool operator==(const ObjectUnderConstruction &LHS,
666                            const ObjectUnderConstruction &RHS) {
667       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
668     }
669     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
670       return llvm::hash_combine(Obj.Base, Obj.Path);
671     }
672   };
673   enum class ConstructionPhase {
674     None,
675     Bases,
676     AfterBases,
677     Destroying,
678     DestroyingBases
679   };
680 }
681 
682 namespace llvm {
683 template<> struct DenseMapInfo<ObjectUnderConstruction> {
684   using Base = DenseMapInfo<APValue::LValueBase>;
685   static ObjectUnderConstruction getEmptyKey() {
686     return {Base::getEmptyKey(), {}}; }
687   static ObjectUnderConstruction getTombstoneKey() {
688     return {Base::getTombstoneKey(), {}};
689   }
690   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
691     return hash_value(Object);
692   }
693   static bool isEqual(const ObjectUnderConstruction &LHS,
694                       const ObjectUnderConstruction &RHS) {
695     return LHS == RHS;
696   }
697 };
698 }
699 
700 namespace {
701   /// A dynamically-allocated heap object.
702   struct DynAlloc {
703     /// The value of this heap-allocated object.
704     APValue Value;
705     /// The allocating expression; used for diagnostics. Either a CXXNewExpr
706     /// or a CallExpr (the latter is for direct calls to operator new inside
707     /// std::allocator<T>::allocate).
708     const Expr *AllocExpr = nullptr;
709 
710     enum Kind {
711       New,
712       ArrayNew,
713       StdAllocator
714     };
715 
716     /// Get the kind of the allocation. This must match between allocation
717     /// and deallocation.
718     Kind getKind() const {
719       if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
720         return NE->isArray() ? ArrayNew : New;
721       assert(isa<CallExpr>(AllocExpr));
722       return StdAllocator;
723     }
724   };
725 
726   struct DynAllocOrder {
727     bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
728       return L.getIndex() < R.getIndex();
729     }
730   };
731 
732   /// EvalInfo - This is a private struct used by the evaluator to capture
733   /// information about a subexpression as it is folded.  It retains information
734   /// about the AST context, but also maintains information about the folded
735   /// expression.
736   ///
737   /// If an expression could be evaluated, it is still possible it is not a C
738   /// "integer constant expression" or constant expression.  If not, this struct
739   /// captures information about how and why not.
740   ///
741   /// One bit of information passed *into* the request for constant folding
742   /// indicates whether the subexpression is "evaluated" or not according to C
743   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
744   /// evaluate the expression regardless of what the RHS is, but C only allows
745   /// certain things in certain situations.
746   class EvalInfo : public interp::State {
747   public:
748     ASTContext &Ctx;
749 
750     /// EvalStatus - Contains information about the evaluation.
751     Expr::EvalStatus &EvalStatus;
752 
753     /// CurrentCall - The top of the constexpr call stack.
754     CallStackFrame *CurrentCall;
755 
756     /// CallStackDepth - The number of calls in the call stack right now.
757     unsigned CallStackDepth;
758 
759     /// NextCallIndex - The next call index to assign.
760     unsigned NextCallIndex;
761 
762     /// StepsLeft - The remaining number of evaluation steps we're permitted
763     /// to perform. This is essentially a limit for the number of statements
764     /// we will evaluate.
765     unsigned StepsLeft;
766 
767     /// Enable the experimental new constant interpreter. If an expression is
768     /// not supported by the interpreter, an error is triggered.
769     bool EnableNewConstInterp;
770 
771     /// BottomFrame - The frame in which evaluation started. This must be
772     /// initialized after CurrentCall and CallStackDepth.
773     CallStackFrame BottomFrame;
774 
775     /// A stack of values whose lifetimes end at the end of some surrounding
776     /// evaluation frame.
777     llvm::SmallVector<Cleanup, 16> CleanupStack;
778 
779     /// EvaluatingDecl - This is the declaration whose initializer is being
780     /// evaluated, if any.
781     APValue::LValueBase EvaluatingDecl;
782 
783     enum class EvaluatingDeclKind {
784       None,
785       /// We're evaluating the construction of EvaluatingDecl.
786       Ctor,
787       /// We're evaluating the destruction of EvaluatingDecl.
788       Dtor,
789     };
790     EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
791 
792     /// EvaluatingDeclValue - This is the value being constructed for the
793     /// declaration whose initializer is being evaluated, if any.
794     APValue *EvaluatingDeclValue;
795 
796     /// Set of objects that are currently being constructed.
797     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
798         ObjectsUnderConstruction;
799 
800     /// Current heap allocations, along with the location where each was
801     /// allocated. We use std::map here because we need stable addresses
802     /// for the stored APValues.
803     std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
804 
805     /// The number of heap allocations performed so far in this evaluation.
806     unsigned NumHeapAllocs = 0;
807 
808     struct EvaluatingConstructorRAII {
809       EvalInfo &EI;
810       ObjectUnderConstruction Object;
811       bool DidInsert;
812       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
813                                 bool HasBases)
814           : EI(EI), Object(Object) {
815         DidInsert =
816             EI.ObjectsUnderConstruction
817                 .insert({Object, HasBases ? ConstructionPhase::Bases
818                                           : ConstructionPhase::AfterBases})
819                 .second;
820       }
821       void finishedConstructingBases() {
822         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
823       }
824       ~EvaluatingConstructorRAII() {
825         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
826       }
827     };
828 
829     struct EvaluatingDestructorRAII {
830       EvalInfo &EI;
831       ObjectUnderConstruction Object;
832       bool DidInsert;
833       EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
834           : EI(EI), Object(Object) {
835         DidInsert = EI.ObjectsUnderConstruction
836                         .insert({Object, ConstructionPhase::Destroying})
837                         .second;
838       }
839       void startedDestroyingBases() {
840         EI.ObjectsUnderConstruction[Object] =
841             ConstructionPhase::DestroyingBases;
842       }
843       ~EvaluatingDestructorRAII() {
844         if (DidInsert)
845           EI.ObjectsUnderConstruction.erase(Object);
846       }
847     };
848 
849     ConstructionPhase
850     isEvaluatingCtorDtor(APValue::LValueBase Base,
851                          ArrayRef<APValue::LValuePathEntry> Path) {
852       return ObjectsUnderConstruction.lookup({Base, Path});
853     }
854 
855     /// If we're currently speculatively evaluating, the outermost call stack
856     /// depth at which we can mutate state, otherwise 0.
857     unsigned SpeculativeEvaluationDepth = 0;
858 
859     /// The current array initialization index, if we're performing array
860     /// initialization.
861     uint64_t ArrayInitIndex = -1;
862 
863     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
864     /// notes attached to it will also be stored, otherwise they will not be.
865     bool HasActiveDiagnostic;
866 
867     /// Have we emitted a diagnostic explaining why we couldn't constant
868     /// fold (not just why it's not strictly a constant expression)?
869     bool HasFoldFailureDiagnostic;
870 
871     /// Whether or not we're in a context where the front end requires a
872     /// constant value.
873     bool InConstantContext;
874 
875     /// Whether we're checking that an expression is a potential constant
876     /// expression. If so, do not fail on constructs that could become constant
877     /// later on (such as a use of an undefined global).
878     bool CheckingPotentialConstantExpression = false;
879 
880     /// Whether we're checking for an expression that has undefined behavior.
881     /// If so, we will produce warnings if we encounter an operation that is
882     /// always undefined.
883     bool CheckingForUndefinedBehavior = false;
884 
885     enum EvaluationMode {
886       /// Evaluate as a constant expression. Stop if we find that the expression
887       /// is not a constant expression.
888       EM_ConstantExpression,
889 
890       /// Evaluate as a constant expression. Stop if we find that the expression
891       /// is not a constant expression. Some expressions can be retried in the
892       /// optimizer if we don't constant fold them here, but in an unevaluated
893       /// context we try to fold them immediately since the optimizer never
894       /// gets a chance to look at it.
895       EM_ConstantExpressionUnevaluated,
896 
897       /// Fold the expression to a constant. Stop if we hit a side-effect that
898       /// we can't model.
899       EM_ConstantFold,
900 
901       /// Evaluate in any way we know how. Don't worry about side-effects that
902       /// can't be modeled.
903       EM_IgnoreSideEffects,
904     } EvalMode;
905 
906     /// Are we checking whether the expression is a potential constant
907     /// expression?
908     bool checkingPotentialConstantExpression() const override  {
909       return CheckingPotentialConstantExpression;
910     }
911 
912     /// Are we checking an expression for overflow?
913     // FIXME: We should check for any kind of undefined or suspicious behavior
914     // in such constructs, not just overflow.
915     bool checkingForUndefinedBehavior() const override {
916       return CheckingForUndefinedBehavior;
917     }
918 
919     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
920         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
921           CallStackDepth(0), NextCallIndex(1),
922           StepsLeft(C.getLangOpts().ConstexprStepLimit),
923           EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
924           BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
925           EvaluatingDecl((const ValueDecl *)nullptr),
926           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
927           HasFoldFailureDiagnostic(false), InConstantContext(false),
928           EvalMode(Mode) {}
929 
930     ~EvalInfo() {
931       discardCleanups();
932     }
933 
934     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
935                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
936       EvaluatingDecl = Base;
937       IsEvaluatingDecl = EDK;
938       EvaluatingDeclValue = &Value;
939     }
940 
941     bool CheckCallLimit(SourceLocation Loc) {
942       // Don't perform any constexpr calls (other than the call we're checking)
943       // when checking a potential constant expression.
944       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
945         return false;
946       if (NextCallIndex == 0) {
947         // NextCallIndex has wrapped around.
948         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
949         return false;
950       }
951       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
952         return true;
953       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
954         << getLangOpts().ConstexprCallDepth;
955       return false;
956     }
957 
958     std::pair<CallStackFrame *, unsigned>
959     getCallFrameAndDepth(unsigned CallIndex) {
960       assert(CallIndex && "no call index in getCallFrameAndDepth");
961       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
962       // be null in this loop.
963       unsigned Depth = CallStackDepth;
964       CallStackFrame *Frame = CurrentCall;
965       while (Frame->Index > CallIndex) {
966         Frame = Frame->Caller;
967         --Depth;
968       }
969       if (Frame->Index == CallIndex)
970         return {Frame, Depth};
971       return {nullptr, 0};
972     }
973 
974     bool nextStep(const Stmt *S) {
975       if (!StepsLeft) {
976         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
977         return false;
978       }
979       --StepsLeft;
980       return true;
981     }
982 
983     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
984 
985     Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
986       Optional<DynAlloc*> Result;
987       auto It = HeapAllocs.find(DA);
988       if (It != HeapAllocs.end())
989         Result = &It->second;
990       return Result;
991     }
992 
993     /// Information about a stack frame for std::allocator<T>::[de]allocate.
994     struct StdAllocatorCaller {
995       unsigned FrameIndex;
996       QualType ElemType;
997       explicit operator bool() const { return FrameIndex != 0; };
998     };
999 
1000     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1001       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1002            Call = Call->Caller) {
1003         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1004         if (!MD)
1005           continue;
1006         const IdentifierInfo *FnII = MD->getIdentifier();
1007         if (!FnII || !FnII->isStr(FnName))
1008           continue;
1009 
1010         const auto *CTSD =
1011             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1012         if (!CTSD)
1013           continue;
1014 
1015         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1016         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1017         if (CTSD->isInStdNamespace() && ClassII &&
1018             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1019             TAL[0].getKind() == TemplateArgument::Type)
1020           return {Call->Index, TAL[0].getAsType()};
1021       }
1022 
1023       return {};
1024     }
1025 
1026     void performLifetimeExtension() {
1027       // Disable the cleanups for lifetime-extended temporaries.
1028       CleanupStack.erase(
1029           std::remove_if(CleanupStack.begin(), CleanupStack.end(),
1030                          [](Cleanup &C) { return C.isLifetimeExtended(); }),
1031           CleanupStack.end());
1032      }
1033 
1034     /// Throw away any remaining cleanups at the end of evaluation. If any
1035     /// cleanups would have had a side-effect, note that as an unmodeled
1036     /// side-effect and return false. Otherwise, return true.
1037     bool discardCleanups() {
1038       for (Cleanup &C : CleanupStack) {
1039         if (C.hasSideEffect() && !noteSideEffect()) {
1040           CleanupStack.clear();
1041           return false;
1042         }
1043       }
1044       CleanupStack.clear();
1045       return true;
1046     }
1047 
1048   private:
1049     interp::Frame *getCurrentFrame() override { return CurrentCall; }
1050     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1051 
1052     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1053     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1054 
1055     void setFoldFailureDiagnostic(bool Flag) override {
1056       HasFoldFailureDiagnostic = Flag;
1057     }
1058 
1059     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1060 
1061     ASTContext &getCtx() const override { return Ctx; }
1062 
1063     // If we have a prior diagnostic, it will be noting that the expression
1064     // isn't a constant expression. This diagnostic is more important,
1065     // unless we require this evaluation to produce a constant expression.
1066     //
1067     // FIXME: We might want to show both diagnostics to the user in
1068     // EM_ConstantFold mode.
1069     bool hasPriorDiagnostic() override {
1070       if (!EvalStatus.Diag->empty()) {
1071         switch (EvalMode) {
1072         case EM_ConstantFold:
1073         case EM_IgnoreSideEffects:
1074           if (!HasFoldFailureDiagnostic)
1075             break;
1076           // We've already failed to fold something. Keep that diagnostic.
1077           LLVM_FALLTHROUGH;
1078         case EM_ConstantExpression:
1079         case EM_ConstantExpressionUnevaluated:
1080           setActiveDiagnostic(false);
1081           return true;
1082         }
1083       }
1084       return false;
1085     }
1086 
1087     unsigned getCallStackDepth() override { return CallStackDepth; }
1088 
1089   public:
1090     /// Should we continue evaluation after encountering a side-effect that we
1091     /// couldn't model?
1092     bool keepEvaluatingAfterSideEffect() {
1093       switch (EvalMode) {
1094       case EM_IgnoreSideEffects:
1095         return true;
1096 
1097       case EM_ConstantExpression:
1098       case EM_ConstantExpressionUnevaluated:
1099       case EM_ConstantFold:
1100         // By default, assume any side effect might be valid in some other
1101         // evaluation of this expression from a different context.
1102         return checkingPotentialConstantExpression() ||
1103                checkingForUndefinedBehavior();
1104       }
1105       llvm_unreachable("Missed EvalMode case");
1106     }
1107 
1108     /// Note that we have had a side-effect, and determine whether we should
1109     /// keep evaluating.
1110     bool noteSideEffect() {
1111       EvalStatus.HasSideEffects = true;
1112       return keepEvaluatingAfterSideEffect();
1113     }
1114 
1115     /// Should we continue evaluation after encountering undefined behavior?
1116     bool keepEvaluatingAfterUndefinedBehavior() {
1117       switch (EvalMode) {
1118       case EM_IgnoreSideEffects:
1119       case EM_ConstantFold:
1120         return true;
1121 
1122       case EM_ConstantExpression:
1123       case EM_ConstantExpressionUnevaluated:
1124         return checkingForUndefinedBehavior();
1125       }
1126       llvm_unreachable("Missed EvalMode case");
1127     }
1128 
1129     /// Note that we hit something that was technically undefined behavior, but
1130     /// that we can evaluate past it (such as signed overflow or floating-point
1131     /// division by zero.)
1132     bool noteUndefinedBehavior() override {
1133       EvalStatus.HasUndefinedBehavior = true;
1134       return keepEvaluatingAfterUndefinedBehavior();
1135     }
1136 
1137     /// Should we continue evaluation as much as possible after encountering a
1138     /// construct which can't be reduced to a value?
1139     bool keepEvaluatingAfterFailure() const override {
1140       if (!StepsLeft)
1141         return false;
1142 
1143       switch (EvalMode) {
1144       case EM_ConstantExpression:
1145       case EM_ConstantExpressionUnevaluated:
1146       case EM_ConstantFold:
1147       case EM_IgnoreSideEffects:
1148         return checkingPotentialConstantExpression() ||
1149                checkingForUndefinedBehavior();
1150       }
1151       llvm_unreachable("Missed EvalMode case");
1152     }
1153 
1154     /// Notes that we failed to evaluate an expression that other expressions
1155     /// directly depend on, and determine if we should keep evaluating. This
1156     /// should only be called if we actually intend to keep evaluating.
1157     ///
1158     /// Call noteSideEffect() instead if we may be able to ignore the value that
1159     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1160     ///
1161     /// (Foo(), 1)      // use noteSideEffect
1162     /// (Foo() || true) // use noteSideEffect
1163     /// Foo() + 1       // use noteFailure
1164     LLVM_NODISCARD bool noteFailure() {
1165       // Failure when evaluating some expression often means there is some
1166       // subexpression whose evaluation was skipped. Therefore, (because we
1167       // don't track whether we skipped an expression when unwinding after an
1168       // evaluation failure) every evaluation failure that bubbles up from a
1169       // subexpression implies that a side-effect has potentially happened. We
1170       // skip setting the HasSideEffects flag to true until we decide to
1171       // continue evaluating after that point, which happens here.
1172       bool KeepGoing = keepEvaluatingAfterFailure();
1173       EvalStatus.HasSideEffects |= KeepGoing;
1174       return KeepGoing;
1175     }
1176 
1177     class ArrayInitLoopIndex {
1178       EvalInfo &Info;
1179       uint64_t OuterIndex;
1180 
1181     public:
1182       ArrayInitLoopIndex(EvalInfo &Info)
1183           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1184         Info.ArrayInitIndex = 0;
1185       }
1186       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1187 
1188       operator uint64_t&() { return Info.ArrayInitIndex; }
1189     };
1190   };
1191 
1192   /// Object used to treat all foldable expressions as constant expressions.
1193   struct FoldConstant {
1194     EvalInfo &Info;
1195     bool Enabled;
1196     bool HadNoPriorDiags;
1197     EvalInfo::EvaluationMode OldMode;
1198 
1199     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1200       : Info(Info),
1201         Enabled(Enabled),
1202         HadNoPriorDiags(Info.EvalStatus.Diag &&
1203                         Info.EvalStatus.Diag->empty() &&
1204                         !Info.EvalStatus.HasSideEffects),
1205         OldMode(Info.EvalMode) {
1206       if (Enabled)
1207         Info.EvalMode = EvalInfo::EM_ConstantFold;
1208     }
1209     void keepDiagnostics() { Enabled = false; }
1210     ~FoldConstant() {
1211       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1212           !Info.EvalStatus.HasSideEffects)
1213         Info.EvalStatus.Diag->clear();
1214       Info.EvalMode = OldMode;
1215     }
1216   };
1217 
1218   /// RAII object used to set the current evaluation mode to ignore
1219   /// side-effects.
1220   struct IgnoreSideEffectsRAII {
1221     EvalInfo &Info;
1222     EvalInfo::EvaluationMode OldMode;
1223     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1224         : Info(Info), OldMode(Info.EvalMode) {
1225       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1226     }
1227 
1228     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1229   };
1230 
1231   /// RAII object used to optionally suppress diagnostics and side-effects from
1232   /// a speculative evaluation.
1233   class SpeculativeEvaluationRAII {
1234     EvalInfo *Info = nullptr;
1235     Expr::EvalStatus OldStatus;
1236     unsigned OldSpeculativeEvaluationDepth;
1237 
1238     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1239       Info = Other.Info;
1240       OldStatus = Other.OldStatus;
1241       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1242       Other.Info = nullptr;
1243     }
1244 
1245     void maybeRestoreState() {
1246       if (!Info)
1247         return;
1248 
1249       Info->EvalStatus = OldStatus;
1250       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1251     }
1252 
1253   public:
1254     SpeculativeEvaluationRAII() = default;
1255 
1256     SpeculativeEvaluationRAII(
1257         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1258         : Info(&Info), OldStatus(Info.EvalStatus),
1259           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1260       Info.EvalStatus.Diag = NewDiag;
1261       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1262     }
1263 
1264     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1265     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1266       moveFromAndCancel(std::move(Other));
1267     }
1268 
1269     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1270       maybeRestoreState();
1271       moveFromAndCancel(std::move(Other));
1272       return *this;
1273     }
1274 
1275     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1276   };
1277 
1278   /// RAII object wrapping a full-expression or block scope, and handling
1279   /// the ending of the lifetime of temporaries created within it.
1280   template<bool IsFullExpression>
1281   class ScopeRAII {
1282     EvalInfo &Info;
1283     unsigned OldStackSize;
1284   public:
1285     ScopeRAII(EvalInfo &Info)
1286         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1287       // Push a new temporary version. This is needed to distinguish between
1288       // temporaries created in different iterations of a loop.
1289       Info.CurrentCall->pushTempVersion();
1290     }
1291     bool destroy(bool RunDestructors = true) {
1292       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1293       OldStackSize = -1U;
1294       return OK;
1295     }
1296     ~ScopeRAII() {
1297       if (OldStackSize != -1U)
1298         destroy(false);
1299       // Body moved to a static method to encourage the compiler to inline away
1300       // instances of this class.
1301       Info.CurrentCall->popTempVersion();
1302     }
1303   private:
1304     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1305                         unsigned OldStackSize) {
1306       assert(OldStackSize <= Info.CleanupStack.size() &&
1307              "running cleanups out of order?");
1308 
1309       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1310       // for a full-expression scope.
1311       bool Success = true;
1312       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1313         if (!(IsFullExpression &&
1314               Info.CleanupStack[I - 1].isLifetimeExtended())) {
1315           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1316             Success = false;
1317             break;
1318           }
1319         }
1320       }
1321 
1322       // Compact lifetime-extended cleanups.
1323       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1324       if (IsFullExpression)
1325         NewEnd =
1326             std::remove_if(NewEnd, Info.CleanupStack.end(),
1327                            [](Cleanup &C) { return !C.isLifetimeExtended(); });
1328       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1329       return Success;
1330     }
1331   };
1332   typedef ScopeRAII<false> BlockScopeRAII;
1333   typedef ScopeRAII<true> FullExpressionRAII;
1334 }
1335 
1336 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1337                                          CheckSubobjectKind CSK) {
1338   if (Invalid)
1339     return false;
1340   if (isOnePastTheEnd()) {
1341     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1342       << CSK;
1343     setInvalid();
1344     return false;
1345   }
1346   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1347   // must actually be at least one array element; even a VLA cannot have a
1348   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1349   return true;
1350 }
1351 
1352 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1353                                                                 const Expr *E) {
1354   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1355   // Do not set the designator as invalid: we can represent this situation,
1356   // and correct handling of __builtin_object_size requires us to do so.
1357 }
1358 
1359 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1360                                                     const Expr *E,
1361                                                     const APSInt &N) {
1362   // If we're complaining, we must be able to statically determine the size of
1363   // the most derived array.
1364   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1365     Info.CCEDiag(E, diag::note_constexpr_array_index)
1366       << N << /*array*/ 0
1367       << static_cast<unsigned>(getMostDerivedArraySize());
1368   else
1369     Info.CCEDiag(E, diag::note_constexpr_array_index)
1370       << N << /*non-array*/ 1;
1371   setInvalid();
1372 }
1373 
1374 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1375                                const FunctionDecl *Callee, const LValue *This,
1376                                APValue *Arguments)
1377     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1378       Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1379   Info.CurrentCall = this;
1380   ++Info.CallStackDepth;
1381 }
1382 
1383 CallStackFrame::~CallStackFrame() {
1384   assert(Info.CurrentCall == this && "calls retired out of order");
1385   --Info.CallStackDepth;
1386   Info.CurrentCall = Caller;
1387 }
1388 
1389 static bool isRead(AccessKinds AK) {
1390   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1391 }
1392 
1393 static bool isModification(AccessKinds AK) {
1394   switch (AK) {
1395   case AK_Read:
1396   case AK_ReadObjectRepresentation:
1397   case AK_MemberCall:
1398   case AK_DynamicCast:
1399   case AK_TypeId:
1400     return false;
1401   case AK_Assign:
1402   case AK_Increment:
1403   case AK_Decrement:
1404   case AK_Construct:
1405   case AK_Destroy:
1406     return true;
1407   }
1408   llvm_unreachable("unknown access kind");
1409 }
1410 
1411 static bool isAnyAccess(AccessKinds AK) {
1412   return isRead(AK) || isModification(AK);
1413 }
1414 
1415 /// Is this an access per the C++ definition?
1416 static bool isFormalAccess(AccessKinds AK) {
1417   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1418 }
1419 
1420 /// Is this kind of axcess valid on an indeterminate object value?
1421 static bool isValidIndeterminateAccess(AccessKinds AK) {
1422   switch (AK) {
1423   case AK_Read:
1424   case AK_Increment:
1425   case AK_Decrement:
1426     // These need the object's value.
1427     return false;
1428 
1429   case AK_ReadObjectRepresentation:
1430   case AK_Assign:
1431   case AK_Construct:
1432   case AK_Destroy:
1433     // Construction and destruction don't need the value.
1434     return true;
1435 
1436   case AK_MemberCall:
1437   case AK_DynamicCast:
1438   case AK_TypeId:
1439     // These aren't really meaningful on scalars.
1440     return true;
1441   }
1442   llvm_unreachable("unknown access kind");
1443 }
1444 
1445 namespace {
1446   struct ComplexValue {
1447   private:
1448     bool IsInt;
1449 
1450   public:
1451     APSInt IntReal, IntImag;
1452     APFloat FloatReal, FloatImag;
1453 
1454     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1455 
1456     void makeComplexFloat() { IsInt = false; }
1457     bool isComplexFloat() const { return !IsInt; }
1458     APFloat &getComplexFloatReal() { return FloatReal; }
1459     APFloat &getComplexFloatImag() { return FloatImag; }
1460 
1461     void makeComplexInt() { IsInt = true; }
1462     bool isComplexInt() const { return IsInt; }
1463     APSInt &getComplexIntReal() { return IntReal; }
1464     APSInt &getComplexIntImag() { return IntImag; }
1465 
1466     void moveInto(APValue &v) const {
1467       if (isComplexFloat())
1468         v = APValue(FloatReal, FloatImag);
1469       else
1470         v = APValue(IntReal, IntImag);
1471     }
1472     void setFrom(const APValue &v) {
1473       assert(v.isComplexFloat() || v.isComplexInt());
1474       if (v.isComplexFloat()) {
1475         makeComplexFloat();
1476         FloatReal = v.getComplexFloatReal();
1477         FloatImag = v.getComplexFloatImag();
1478       } else {
1479         makeComplexInt();
1480         IntReal = v.getComplexIntReal();
1481         IntImag = v.getComplexIntImag();
1482       }
1483     }
1484   };
1485 
1486   struct LValue {
1487     APValue::LValueBase Base;
1488     CharUnits Offset;
1489     SubobjectDesignator Designator;
1490     bool IsNullPtr : 1;
1491     bool InvalidBase : 1;
1492 
1493     const APValue::LValueBase getLValueBase() const { return Base; }
1494     CharUnits &getLValueOffset() { return Offset; }
1495     const CharUnits &getLValueOffset() const { return Offset; }
1496     SubobjectDesignator &getLValueDesignator() { return Designator; }
1497     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1498     bool isNullPointer() const { return IsNullPtr;}
1499 
1500     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1501     unsigned getLValueVersion() const { return Base.getVersion(); }
1502 
1503     void moveInto(APValue &V) const {
1504       if (Designator.Invalid)
1505         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1506       else {
1507         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1508         V = APValue(Base, Offset, Designator.Entries,
1509                     Designator.IsOnePastTheEnd, IsNullPtr);
1510       }
1511     }
1512     void setFrom(ASTContext &Ctx, const APValue &V) {
1513       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1514       Base = V.getLValueBase();
1515       Offset = V.getLValueOffset();
1516       InvalidBase = false;
1517       Designator = SubobjectDesignator(Ctx, V);
1518       IsNullPtr = V.isNullPointer();
1519     }
1520 
1521     void set(APValue::LValueBase B, bool BInvalid = false) {
1522 #ifndef NDEBUG
1523       // We only allow a few types of invalid bases. Enforce that here.
1524       if (BInvalid) {
1525         const auto *E = B.get<const Expr *>();
1526         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1527                "Unexpected type of invalid base");
1528       }
1529 #endif
1530 
1531       Base = B;
1532       Offset = CharUnits::fromQuantity(0);
1533       InvalidBase = BInvalid;
1534       Designator = SubobjectDesignator(getType(B));
1535       IsNullPtr = false;
1536     }
1537 
1538     void setNull(ASTContext &Ctx, QualType PointerTy) {
1539       Base = (Expr *)nullptr;
1540       Offset =
1541           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1542       InvalidBase = false;
1543       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1544       IsNullPtr = true;
1545     }
1546 
1547     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1548       set(B, true);
1549     }
1550 
1551     std::string toString(ASTContext &Ctx, QualType T) const {
1552       APValue Printable;
1553       moveInto(Printable);
1554       return Printable.getAsString(Ctx, T);
1555     }
1556 
1557   private:
1558     // Check that this LValue is not based on a null pointer. If it is, produce
1559     // a diagnostic and mark the designator as invalid.
1560     template <typename GenDiagType>
1561     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1562       if (Designator.Invalid)
1563         return false;
1564       if (IsNullPtr) {
1565         GenDiag();
1566         Designator.setInvalid();
1567         return false;
1568       }
1569       return true;
1570     }
1571 
1572   public:
1573     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1574                           CheckSubobjectKind CSK) {
1575       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1576         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1577       });
1578     }
1579 
1580     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1581                                        AccessKinds AK) {
1582       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1583         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1584       });
1585     }
1586 
1587     // Check this LValue refers to an object. If not, set the designator to be
1588     // invalid and emit a diagnostic.
1589     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1590       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1591              Designator.checkSubobject(Info, E, CSK);
1592     }
1593 
1594     void addDecl(EvalInfo &Info, const Expr *E,
1595                  const Decl *D, bool Virtual = false) {
1596       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1597         Designator.addDeclUnchecked(D, Virtual);
1598     }
1599     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1600       if (!Designator.Entries.empty()) {
1601         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1602         Designator.setInvalid();
1603         return;
1604       }
1605       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1606         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1607         Designator.FirstEntryIsAnUnsizedArray = true;
1608         Designator.addUnsizedArrayUnchecked(ElemTy);
1609       }
1610     }
1611     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1612       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1613         Designator.addArrayUnchecked(CAT);
1614     }
1615     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1616       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1617         Designator.addComplexUnchecked(EltTy, Imag);
1618     }
1619     void clearIsNullPointer() {
1620       IsNullPtr = false;
1621     }
1622     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1623                               const APSInt &Index, CharUnits ElementSize) {
1624       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1625       // but we're not required to diagnose it and it's valid in C++.)
1626       if (!Index)
1627         return;
1628 
1629       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1630       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1631       // offsets.
1632       uint64_t Offset64 = Offset.getQuantity();
1633       uint64_t ElemSize64 = ElementSize.getQuantity();
1634       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1635       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1636 
1637       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1638         Designator.adjustIndex(Info, E, Index);
1639       clearIsNullPointer();
1640     }
1641     void adjustOffset(CharUnits N) {
1642       Offset += N;
1643       if (N.getQuantity())
1644         clearIsNullPointer();
1645     }
1646   };
1647 
1648   struct MemberPtr {
1649     MemberPtr() {}
1650     explicit MemberPtr(const ValueDecl *Decl) :
1651       DeclAndIsDerivedMember(Decl, false), Path() {}
1652 
1653     /// The member or (direct or indirect) field referred to by this member
1654     /// pointer, or 0 if this is a null member pointer.
1655     const ValueDecl *getDecl() const {
1656       return DeclAndIsDerivedMember.getPointer();
1657     }
1658     /// Is this actually a member of some type derived from the relevant class?
1659     bool isDerivedMember() const {
1660       return DeclAndIsDerivedMember.getInt();
1661     }
1662     /// Get the class which the declaration actually lives in.
1663     const CXXRecordDecl *getContainingRecord() const {
1664       return cast<CXXRecordDecl>(
1665           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1666     }
1667 
1668     void moveInto(APValue &V) const {
1669       V = APValue(getDecl(), isDerivedMember(), Path);
1670     }
1671     void setFrom(const APValue &V) {
1672       assert(V.isMemberPointer());
1673       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1674       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1675       Path.clear();
1676       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1677       Path.insert(Path.end(), P.begin(), P.end());
1678     }
1679 
1680     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1681     /// whether the member is a member of some class derived from the class type
1682     /// of the member pointer.
1683     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1684     /// Path - The path of base/derived classes from the member declaration's
1685     /// class (exclusive) to the class type of the member pointer (inclusive).
1686     SmallVector<const CXXRecordDecl*, 4> Path;
1687 
1688     /// Perform a cast towards the class of the Decl (either up or down the
1689     /// hierarchy).
1690     bool castBack(const CXXRecordDecl *Class) {
1691       assert(!Path.empty());
1692       const CXXRecordDecl *Expected;
1693       if (Path.size() >= 2)
1694         Expected = Path[Path.size() - 2];
1695       else
1696         Expected = getContainingRecord();
1697       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1698         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1699         // if B does not contain the original member and is not a base or
1700         // derived class of the class containing the original member, the result
1701         // of the cast is undefined.
1702         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1703         // (D::*). We consider that to be a language defect.
1704         return false;
1705       }
1706       Path.pop_back();
1707       return true;
1708     }
1709     /// Perform a base-to-derived member pointer cast.
1710     bool castToDerived(const CXXRecordDecl *Derived) {
1711       if (!getDecl())
1712         return true;
1713       if (!isDerivedMember()) {
1714         Path.push_back(Derived);
1715         return true;
1716       }
1717       if (!castBack(Derived))
1718         return false;
1719       if (Path.empty())
1720         DeclAndIsDerivedMember.setInt(false);
1721       return true;
1722     }
1723     /// Perform a derived-to-base member pointer cast.
1724     bool castToBase(const CXXRecordDecl *Base) {
1725       if (!getDecl())
1726         return true;
1727       if (Path.empty())
1728         DeclAndIsDerivedMember.setInt(true);
1729       if (isDerivedMember()) {
1730         Path.push_back(Base);
1731         return true;
1732       }
1733       return castBack(Base);
1734     }
1735   };
1736 
1737   /// Compare two member pointers, which are assumed to be of the same type.
1738   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1739     if (!LHS.getDecl() || !RHS.getDecl())
1740       return !LHS.getDecl() && !RHS.getDecl();
1741     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1742       return false;
1743     return LHS.Path == RHS.Path;
1744   }
1745 }
1746 
1747 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1748 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1749                             const LValue &This, const Expr *E,
1750                             bool AllowNonLiteralTypes = false);
1751 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1752                            bool InvalidBaseOK = false);
1753 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1754                             bool InvalidBaseOK = false);
1755 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1756                                   EvalInfo &Info);
1757 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1758 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1759 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1760                                     EvalInfo &Info);
1761 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1762 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1763 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1764                            EvalInfo &Info);
1765 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1766 
1767 /// Evaluate an integer or fixed point expression into an APResult.
1768 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1769                                         EvalInfo &Info);
1770 
1771 /// Evaluate only a fixed point expression into an APResult.
1772 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1773                                EvalInfo &Info);
1774 
1775 //===----------------------------------------------------------------------===//
1776 // Misc utilities
1777 //===----------------------------------------------------------------------===//
1778 
1779 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1780 /// preserving its value (by extending by up to one bit as needed).
1781 static void negateAsSigned(APSInt &Int) {
1782   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1783     Int = Int.extend(Int.getBitWidth() + 1);
1784     Int.setIsSigned(true);
1785   }
1786   Int = -Int;
1787 }
1788 
1789 template<typename KeyT>
1790 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1791                                          bool IsLifetimeExtended, LValue &LV) {
1792   unsigned Version = getTempVersion();
1793   APValue::LValueBase Base(Key, Index, Version);
1794   LV.set(Base);
1795   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1796   assert(Result.isAbsent() && "temporary created multiple times");
1797 
1798   // If we're creating a temporary immediately in the operand of a speculative
1799   // evaluation, don't register a cleanup to be run outside the speculative
1800   // evaluation context, since we won't actually be able to initialize this
1801   // object.
1802   if (Index <= Info.SpeculativeEvaluationDepth) {
1803     if (T.isDestructedType())
1804       Info.noteSideEffect();
1805   } else {
1806     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, IsLifetimeExtended));
1807   }
1808   return Result;
1809 }
1810 
1811 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1812   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1813     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1814     return nullptr;
1815   }
1816 
1817   DynamicAllocLValue DA(NumHeapAllocs++);
1818   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1819   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1820                                    std::forward_as_tuple(DA), std::tuple<>());
1821   assert(Result.second && "reused a heap alloc index?");
1822   Result.first->second.AllocExpr = E;
1823   return &Result.first->second.Value;
1824 }
1825 
1826 /// Produce a string describing the given constexpr call.
1827 void CallStackFrame::describe(raw_ostream &Out) {
1828   unsigned ArgIndex = 0;
1829   bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1830                       !isa<CXXConstructorDecl>(Callee) &&
1831                       cast<CXXMethodDecl>(Callee)->isInstance();
1832 
1833   if (!IsMemberCall)
1834     Out << *Callee << '(';
1835 
1836   if (This && IsMemberCall) {
1837     APValue Val;
1838     This->moveInto(Val);
1839     Val.printPretty(Out, Info.Ctx,
1840                     This->Designator.MostDerivedType);
1841     // FIXME: Add parens around Val if needed.
1842     Out << "->" << *Callee << '(';
1843     IsMemberCall = false;
1844   }
1845 
1846   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1847        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1848     if (ArgIndex > (unsigned)IsMemberCall)
1849       Out << ", ";
1850 
1851     const ParmVarDecl *Param = *I;
1852     const APValue &Arg = Arguments[ArgIndex];
1853     Arg.printPretty(Out, Info.Ctx, Param->getType());
1854 
1855     if (ArgIndex == 0 && IsMemberCall)
1856       Out << "->" << *Callee << '(';
1857   }
1858 
1859   Out << ')';
1860 }
1861 
1862 /// Evaluate an expression to see if it had side-effects, and discard its
1863 /// result.
1864 /// \return \c true if the caller should keep evaluating.
1865 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1866   APValue Scratch;
1867   if (!Evaluate(Scratch, Info, E))
1868     // We don't need the value, but we might have skipped a side effect here.
1869     return Info.noteSideEffect();
1870   return true;
1871 }
1872 
1873 /// Should this call expression be treated as a string literal?
1874 static bool IsStringLiteralCall(const CallExpr *E) {
1875   unsigned Builtin = E->getBuiltinCallee();
1876   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1877           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1878 }
1879 
1880 static bool IsGlobalLValue(APValue::LValueBase B) {
1881   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1882   // constant expression of pointer type that evaluates to...
1883 
1884   // ... a null pointer value, or a prvalue core constant expression of type
1885   // std::nullptr_t.
1886   if (!B) return true;
1887 
1888   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1889     // ... the address of an object with static storage duration,
1890     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1891       return VD->hasGlobalStorage();
1892     // ... the address of a function,
1893     return isa<FunctionDecl>(D);
1894   }
1895 
1896   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1897     return true;
1898 
1899   const Expr *E = B.get<const Expr*>();
1900   switch (E->getStmtClass()) {
1901   default:
1902     return false;
1903   case Expr::CompoundLiteralExprClass: {
1904     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1905     return CLE->isFileScope() && CLE->isLValue();
1906   }
1907   case Expr::MaterializeTemporaryExprClass:
1908     // A materialized temporary might have been lifetime-extended to static
1909     // storage duration.
1910     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1911   // A string literal has static storage duration.
1912   case Expr::StringLiteralClass:
1913   case Expr::PredefinedExprClass:
1914   case Expr::ObjCStringLiteralClass:
1915   case Expr::ObjCEncodeExprClass:
1916   case Expr::CXXUuidofExprClass:
1917     return true;
1918   case Expr::ObjCBoxedExprClass:
1919     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
1920   case Expr::CallExprClass:
1921     return IsStringLiteralCall(cast<CallExpr>(E));
1922   // For GCC compatibility, &&label has static storage duration.
1923   case Expr::AddrLabelExprClass:
1924     return true;
1925   // A Block literal expression may be used as the initialization value for
1926   // Block variables at global or local static scope.
1927   case Expr::BlockExprClass:
1928     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1929   case Expr::ImplicitValueInitExprClass:
1930     // FIXME:
1931     // We can never form an lvalue with an implicit value initialization as its
1932     // base through expression evaluation, so these only appear in one case: the
1933     // implicit variable declaration we invent when checking whether a constexpr
1934     // constructor can produce a constant expression. We must assume that such
1935     // an expression might be a global lvalue.
1936     return true;
1937   }
1938 }
1939 
1940 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1941   return LVal.Base.dyn_cast<const ValueDecl*>();
1942 }
1943 
1944 static bool IsLiteralLValue(const LValue &Value) {
1945   if (Value.getLValueCallIndex())
1946     return false;
1947   const Expr *E = Value.Base.dyn_cast<const Expr*>();
1948   return E && !isa<MaterializeTemporaryExpr>(E);
1949 }
1950 
1951 static bool IsWeakLValue(const LValue &Value) {
1952   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1953   return Decl && Decl->isWeak();
1954 }
1955 
1956 static bool isZeroSized(const LValue &Value) {
1957   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1958   if (Decl && isa<VarDecl>(Decl)) {
1959     QualType Ty = Decl->getType();
1960     if (Ty->isArrayType())
1961       return Ty->isIncompleteType() ||
1962              Decl->getASTContext().getTypeSize(Ty) == 0;
1963   }
1964   return false;
1965 }
1966 
1967 static bool HasSameBase(const LValue &A, const LValue &B) {
1968   if (!A.getLValueBase())
1969     return !B.getLValueBase();
1970   if (!B.getLValueBase())
1971     return false;
1972 
1973   if (A.getLValueBase().getOpaqueValue() !=
1974       B.getLValueBase().getOpaqueValue()) {
1975     const Decl *ADecl = GetLValueBaseDecl(A);
1976     if (!ADecl)
1977       return false;
1978     const Decl *BDecl = GetLValueBaseDecl(B);
1979     if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1980       return false;
1981   }
1982 
1983   return IsGlobalLValue(A.getLValueBase()) ||
1984          (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       NoteLValueLocation(Info, Base);
2054     } else {
2055       Info.FFDiag(Loc);
2056     }
2057     // Don't allow references to temporaries to escape.
2058     return false;
2059   }
2060   assert((Info.checkingPotentialConstantExpression() ||
2061           LVal.getLValueCallIndex() == 0) &&
2062          "have call index for global lvalue");
2063 
2064   if (Base.is<DynamicAllocLValue>()) {
2065     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2066         << IsReferenceType << !Designator.Entries.empty();
2067     NoteLValueLocation(Info, Base);
2068     return false;
2069   }
2070 
2071   if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
2072     if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
2073       // Check if this is a thread-local variable.
2074       if (Var->getTLSKind())
2075         // FIXME: Diagnostic!
2076         return false;
2077 
2078       // A dllimport variable never acts like a constant.
2079       if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
2080         // FIXME: Diagnostic!
2081         return false;
2082     }
2083     if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
2084       // __declspec(dllimport) must be handled very carefully:
2085       // We must never initialize an expression with the thunk in C++.
2086       // Doing otherwise would allow the same id-expression to yield
2087       // different addresses for the same function in different translation
2088       // units.  However, this means that we must dynamically initialize the
2089       // expression with the contents of the import address table at runtime.
2090       //
2091       // The C language has no notion of ODR; furthermore, it has no notion of
2092       // dynamic initialization.  This means that we are permitted to
2093       // perform initialization with the address of the thunk.
2094       if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
2095           FD->hasAttr<DLLImportAttr>())
2096         // FIXME: Diagnostic!
2097         return false;
2098     }
2099   } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(
2100                  Base.dyn_cast<const Expr *>())) {
2101     if (CheckedTemps.insert(MTE).second) {
2102       QualType TempType = getType(Base);
2103       if (TempType.isDestructedType()) {
2104         Info.FFDiag(MTE->getExprLoc(),
2105                     diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor)
2106             << TempType;
2107         return false;
2108       }
2109 
2110       APValue *V = MTE->getOrCreateValue(false);
2111       assert(V && "evasluation result refers to uninitialised temporary");
2112       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2113                                  Info, MTE->getExprLoc(), TempType, *V,
2114                                  Usage, SourceLocation(), CheckedTemps))
2115         return false;
2116     }
2117   }
2118 
2119   // Allow address constant expressions to be past-the-end pointers. This is
2120   // an extension: the standard requires them to point to an object.
2121   if (!IsReferenceType)
2122     return true;
2123 
2124   // A reference constant expression must refer to an object.
2125   if (!Base) {
2126     // FIXME: diagnostic
2127     Info.CCEDiag(Loc);
2128     return true;
2129   }
2130 
2131   // Does this refer one past the end of some object?
2132   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2133     const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2134     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2135       << !Designator.Entries.empty() << !!VD << VD;
2136     NoteLValueLocation(Info, Base);
2137   }
2138 
2139   return true;
2140 }
2141 
2142 /// Member pointers are constant expressions unless they point to a
2143 /// non-virtual dllimport member function.
2144 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2145                                                  SourceLocation Loc,
2146                                                  QualType Type,
2147                                                  const APValue &Value,
2148                                                  Expr::ConstExprUsage Usage) {
2149   const ValueDecl *Member = Value.getMemberPointerDecl();
2150   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2151   if (!FD)
2152     return true;
2153   if (FD->isConsteval()) {
2154     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2155     Info.Note(FD->getLocation(), diag::note_declared_at);
2156     return false;
2157   }
2158   return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
2159          !FD->hasAttr<DLLImportAttr>();
2160 }
2161 
2162 /// Check that this core constant expression is of literal type, and if not,
2163 /// produce an appropriate diagnostic.
2164 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2165                              const LValue *This = nullptr) {
2166   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
2167     return true;
2168 
2169   // C++1y: A constant initializer for an object o [...] may also invoke
2170   // constexpr constructors for o and its subobjects even if those objects
2171   // are of non-literal class types.
2172   //
2173   // C++11 missed this detail for aggregates, so classes like this:
2174   //   struct foo_t { union { int i; volatile int j; } u; };
2175   // are not (obviously) initializable like so:
2176   //   __attribute__((__require_constant_initialization__))
2177   //   static const foo_t x = {{0}};
2178   // because "i" is a subobject with non-literal initialization (due to the
2179   // volatile member of the union). See:
2180   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2181   // Therefore, we use the C++1y behavior.
2182   if (This && Info.EvaluatingDecl == This->getLValueBase())
2183     return true;
2184 
2185   // Prvalue constant expressions must be of literal types.
2186   if (Info.getLangOpts().CPlusPlus11)
2187     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2188       << E->getType();
2189   else
2190     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2191   return false;
2192 }
2193 
2194 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2195                                   EvalInfo &Info, SourceLocation DiagLoc,
2196                                   QualType Type, const APValue &Value,
2197                                   Expr::ConstExprUsage Usage,
2198                                   SourceLocation SubobjectLoc,
2199                                   CheckedTemporaries &CheckedTemps) {
2200   if (!Value.hasValue()) {
2201     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2202       << true << Type;
2203     if (SubobjectLoc.isValid())
2204       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2205     return false;
2206   }
2207 
2208   // We allow _Atomic(T) to be initialized from anything that T can be
2209   // initialized from.
2210   if (const AtomicType *AT = Type->getAs<AtomicType>())
2211     Type = AT->getValueType();
2212 
2213   // Core issue 1454: For a literal constant expression of array or class type,
2214   // each subobject of its value shall have been initialized by a constant
2215   // expression.
2216   if (Value.isArray()) {
2217     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2218     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2219       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2220                                  Value.getArrayInitializedElt(I), Usage,
2221                                  SubobjectLoc, CheckedTemps))
2222         return false;
2223     }
2224     if (!Value.hasArrayFiller())
2225       return true;
2226     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2227                                  Value.getArrayFiller(), Usage, SubobjectLoc,
2228                                  CheckedTemps);
2229   }
2230   if (Value.isUnion() && Value.getUnionField()) {
2231     return CheckEvaluationResult(
2232         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2233         Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(),
2234         CheckedTemps);
2235   }
2236   if (Value.isStruct()) {
2237     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2238     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2239       unsigned BaseIndex = 0;
2240       for (const CXXBaseSpecifier &BS : CD->bases()) {
2241         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2242                                    Value.getStructBase(BaseIndex), Usage,
2243                                    BS.getBeginLoc(), CheckedTemps))
2244           return false;
2245         ++BaseIndex;
2246       }
2247     }
2248     for (const auto *I : RD->fields()) {
2249       if (I->isUnnamedBitfield())
2250         continue;
2251 
2252       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2253                                  Value.getStructField(I->getFieldIndex()),
2254                                  Usage, I->getLocation(), CheckedTemps))
2255         return false;
2256     }
2257   }
2258 
2259   if (Value.isLValue() &&
2260       CERK == CheckEvaluationResultKind::ConstantExpression) {
2261     LValue LVal;
2262     LVal.setFrom(Info.Ctx, Value);
2263     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage,
2264                                          CheckedTemps);
2265   }
2266 
2267   if (Value.isMemberPointer() &&
2268       CERK == CheckEvaluationResultKind::ConstantExpression)
2269     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
2270 
2271   // Everything else is fine.
2272   return true;
2273 }
2274 
2275 /// Check that this core constant expression value is a valid value for a
2276 /// constant expression. If not, report an appropriate diagnostic. Does not
2277 /// check that the expression is of literal type.
2278 static bool
2279 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2280                         const APValue &Value,
2281                         Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
2282   CheckedTemporaries CheckedTemps;
2283   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2284                                Info, DiagLoc, Type, Value, Usage,
2285                                SourceLocation(), CheckedTemps);
2286 }
2287 
2288 /// Check that this evaluated value is fully-initialized and can be loaded by
2289 /// an lvalue-to-rvalue conversion.
2290 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2291                                   QualType Type, const APValue &Value) {
2292   CheckedTemporaries CheckedTemps;
2293   return CheckEvaluationResult(
2294       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2295       Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps);
2296 }
2297 
2298 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2299 /// "the allocated storage is deallocated within the evaluation".
2300 static bool CheckMemoryLeaks(EvalInfo &Info) {
2301   if (!Info.HeapAllocs.empty()) {
2302     // We can still fold to a constant despite a compile-time memory leak,
2303     // so long as the heap allocation isn't referenced in the result (we check
2304     // that in CheckConstantExpression).
2305     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2306                  diag::note_constexpr_memory_leak)
2307         << unsigned(Info.HeapAllocs.size() - 1);
2308   }
2309   return true;
2310 }
2311 
2312 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2313   // A null base expression indicates a null pointer.  These are always
2314   // evaluatable, and they are false unless the offset is zero.
2315   if (!Value.getLValueBase()) {
2316     Result = !Value.getLValueOffset().isZero();
2317     return true;
2318   }
2319 
2320   // We have a non-null base.  These are generally known to be true, but if it's
2321   // a weak declaration it can be null at runtime.
2322   Result = true;
2323   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2324   return !Decl || !Decl->isWeak();
2325 }
2326 
2327 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2328   switch (Val.getKind()) {
2329   case APValue::None:
2330   case APValue::Indeterminate:
2331     return false;
2332   case APValue::Int:
2333     Result = Val.getInt().getBoolValue();
2334     return true;
2335   case APValue::FixedPoint:
2336     Result = Val.getFixedPoint().getBoolValue();
2337     return true;
2338   case APValue::Float:
2339     Result = !Val.getFloat().isZero();
2340     return true;
2341   case APValue::ComplexInt:
2342     Result = Val.getComplexIntReal().getBoolValue() ||
2343              Val.getComplexIntImag().getBoolValue();
2344     return true;
2345   case APValue::ComplexFloat:
2346     Result = !Val.getComplexFloatReal().isZero() ||
2347              !Val.getComplexFloatImag().isZero();
2348     return true;
2349   case APValue::LValue:
2350     return EvalPointerValueAsBool(Val, Result);
2351   case APValue::MemberPointer:
2352     Result = Val.getMemberPointerDecl();
2353     return true;
2354   case APValue::Vector:
2355   case APValue::Array:
2356   case APValue::Struct:
2357   case APValue::Union:
2358   case APValue::AddrLabelDiff:
2359     return false;
2360   }
2361 
2362   llvm_unreachable("unknown APValue kind");
2363 }
2364 
2365 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2366                                        EvalInfo &Info) {
2367   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2368   APValue Val;
2369   if (!Evaluate(Val, Info, E))
2370     return false;
2371   return HandleConversionToBool(Val, Result);
2372 }
2373 
2374 template<typename T>
2375 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2376                            const T &SrcValue, QualType DestType) {
2377   Info.CCEDiag(E, diag::note_constexpr_overflow)
2378     << SrcValue << DestType;
2379   return Info.noteUndefinedBehavior();
2380 }
2381 
2382 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2383                                  QualType SrcType, const APFloat &Value,
2384                                  QualType DestType, APSInt &Result) {
2385   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2386   // Determine whether we are converting to unsigned or signed.
2387   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2388 
2389   Result = APSInt(DestWidth, !DestSigned);
2390   bool ignored;
2391   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2392       & APFloat::opInvalidOp)
2393     return HandleOverflow(Info, E, Value, DestType);
2394   return true;
2395 }
2396 
2397 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2398                                    QualType SrcType, QualType DestType,
2399                                    APFloat &Result) {
2400   APFloat Value = Result;
2401   bool ignored;
2402   Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2403                  APFloat::rmNearestTiesToEven, &ignored);
2404   return true;
2405 }
2406 
2407 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2408                                  QualType DestType, QualType SrcType,
2409                                  const APSInt &Value) {
2410   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2411   // Figure out if this is a truncate, extend or noop cast.
2412   // If the input is signed, do a sign extend, noop, or truncate.
2413   APSInt Result = Value.extOrTrunc(DestWidth);
2414   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2415   if (DestType->isBooleanType())
2416     Result = Value.getBoolValue();
2417   return Result;
2418 }
2419 
2420 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2421                                  QualType SrcType, const APSInt &Value,
2422                                  QualType DestType, APFloat &Result) {
2423   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2424   Result.convertFromAPInt(Value, Value.isSigned(),
2425                           APFloat::rmNearestTiesToEven);
2426   return true;
2427 }
2428 
2429 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2430                                   APValue &Value, const FieldDecl *FD) {
2431   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2432 
2433   if (!Value.isInt()) {
2434     // Trying to store a pointer-cast-to-integer into a bitfield.
2435     // FIXME: In this case, we should provide the diagnostic for casting
2436     // a pointer to an integer.
2437     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2438     Info.FFDiag(E);
2439     return false;
2440   }
2441 
2442   APSInt &Int = Value.getInt();
2443   unsigned OldBitWidth = Int.getBitWidth();
2444   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2445   if (NewBitWidth < OldBitWidth)
2446     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2447   return true;
2448 }
2449 
2450 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2451                                   llvm::APInt &Res) {
2452   APValue SVal;
2453   if (!Evaluate(SVal, Info, E))
2454     return false;
2455   if (SVal.isInt()) {
2456     Res = SVal.getInt();
2457     return true;
2458   }
2459   if (SVal.isFloat()) {
2460     Res = SVal.getFloat().bitcastToAPInt();
2461     return true;
2462   }
2463   if (SVal.isVector()) {
2464     QualType VecTy = E->getType();
2465     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2466     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2467     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2468     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2469     Res = llvm::APInt::getNullValue(VecSize);
2470     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2471       APValue &Elt = SVal.getVectorElt(i);
2472       llvm::APInt EltAsInt;
2473       if (Elt.isInt()) {
2474         EltAsInt = Elt.getInt();
2475       } else if (Elt.isFloat()) {
2476         EltAsInt = Elt.getFloat().bitcastToAPInt();
2477       } else {
2478         // Don't try to handle vectors of anything other than int or float
2479         // (not sure if it's possible to hit this case).
2480         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2481         return false;
2482       }
2483       unsigned BaseEltSize = EltAsInt.getBitWidth();
2484       if (BigEndian)
2485         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2486       else
2487         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2488     }
2489     return true;
2490   }
2491   // Give up if the input isn't an int, float, or vector.  For example, we
2492   // reject "(v4i16)(intptr_t)&a".
2493   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2494   return false;
2495 }
2496 
2497 /// Perform the given integer operation, which is known to need at most BitWidth
2498 /// bits, and check for overflow in the original type (if that type was not an
2499 /// unsigned type).
2500 template<typename Operation>
2501 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2502                                  const APSInt &LHS, const APSInt &RHS,
2503                                  unsigned BitWidth, Operation Op,
2504                                  APSInt &Result) {
2505   if (LHS.isUnsigned()) {
2506     Result = Op(LHS, RHS);
2507     return true;
2508   }
2509 
2510   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2511   Result = Value.trunc(LHS.getBitWidth());
2512   if (Result.extend(BitWidth) != Value) {
2513     if (Info.checkingForUndefinedBehavior())
2514       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2515                                        diag::warn_integer_constant_overflow)
2516           << Result.toString(10) << E->getType();
2517     else
2518       return HandleOverflow(Info, E, Value, E->getType());
2519   }
2520   return true;
2521 }
2522 
2523 /// Perform the given binary integer operation.
2524 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2525                               BinaryOperatorKind Opcode, APSInt RHS,
2526                               APSInt &Result) {
2527   switch (Opcode) {
2528   default:
2529     Info.FFDiag(E);
2530     return false;
2531   case BO_Mul:
2532     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2533                                 std::multiplies<APSInt>(), Result);
2534   case BO_Add:
2535     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2536                                 std::plus<APSInt>(), Result);
2537   case BO_Sub:
2538     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2539                                 std::minus<APSInt>(), Result);
2540   case BO_And: Result = LHS & RHS; return true;
2541   case BO_Xor: Result = LHS ^ RHS; return true;
2542   case BO_Or:  Result = LHS | RHS; return true;
2543   case BO_Div:
2544   case BO_Rem:
2545     if (RHS == 0) {
2546       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2547       return false;
2548     }
2549     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2550     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2551     // this operation and gives the two's complement result.
2552     if (RHS.isNegative() && RHS.isAllOnesValue() &&
2553         LHS.isSigned() && LHS.isMinSignedValue())
2554       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2555                             E->getType());
2556     return true;
2557   case BO_Shl: {
2558     if (Info.getLangOpts().OpenCL)
2559       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2560       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2561                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2562                     RHS.isUnsigned());
2563     else if (RHS.isSigned() && RHS.isNegative()) {
2564       // During constant-folding, a negative shift is an opposite shift. Such
2565       // a shift is not a constant expression.
2566       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2567       RHS = -RHS;
2568       goto shift_right;
2569     }
2570   shift_left:
2571     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2572     // the shifted type.
2573     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2574     if (SA != RHS) {
2575       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2576         << RHS << E->getType() << LHS.getBitWidth();
2577     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) {
2578       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2579       // operand, and must not overflow the corresponding unsigned type.
2580       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2581       // E1 x 2^E2 module 2^N.
2582       if (LHS.isNegative())
2583         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2584       else if (LHS.countLeadingZeros() < SA)
2585         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2586     }
2587     Result = LHS << SA;
2588     return true;
2589   }
2590   case BO_Shr: {
2591     if (Info.getLangOpts().OpenCL)
2592       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2593       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2594                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2595                     RHS.isUnsigned());
2596     else if (RHS.isSigned() && RHS.isNegative()) {
2597       // During constant-folding, a negative shift is an opposite shift. Such a
2598       // shift is not a constant expression.
2599       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2600       RHS = -RHS;
2601       goto shift_left;
2602     }
2603   shift_right:
2604     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2605     // shifted type.
2606     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2607     if (SA != RHS)
2608       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2609         << RHS << E->getType() << LHS.getBitWidth();
2610     Result = LHS >> SA;
2611     return true;
2612   }
2613 
2614   case BO_LT: Result = LHS < RHS; return true;
2615   case BO_GT: Result = LHS > RHS; return true;
2616   case BO_LE: Result = LHS <= RHS; return true;
2617   case BO_GE: Result = LHS >= RHS; return true;
2618   case BO_EQ: Result = LHS == RHS; return true;
2619   case BO_NE: Result = LHS != RHS; return true;
2620   case BO_Cmp:
2621     llvm_unreachable("BO_Cmp should be handled elsewhere");
2622   }
2623 }
2624 
2625 /// Perform the given binary floating-point operation, in-place, on LHS.
2626 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2627                                   APFloat &LHS, BinaryOperatorKind Opcode,
2628                                   const APFloat &RHS) {
2629   switch (Opcode) {
2630   default:
2631     Info.FFDiag(E);
2632     return false;
2633   case BO_Mul:
2634     LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2635     break;
2636   case BO_Add:
2637     LHS.add(RHS, APFloat::rmNearestTiesToEven);
2638     break;
2639   case BO_Sub:
2640     LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2641     break;
2642   case BO_Div:
2643     // [expr.mul]p4:
2644     //   If the second operand of / or % is zero the behavior is undefined.
2645     if (RHS.isZero())
2646       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2647     LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2648     break;
2649   }
2650 
2651   // [expr.pre]p4:
2652   //   If during the evaluation of an expression, the result is not
2653   //   mathematically defined [...], the behavior is undefined.
2654   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2655   if (LHS.isNaN()) {
2656     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2657     return Info.noteUndefinedBehavior();
2658   }
2659   return true;
2660 }
2661 
2662 /// Cast an lvalue referring to a base subobject to a derived class, by
2663 /// truncating the lvalue's path to the given length.
2664 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2665                                const RecordDecl *TruncatedType,
2666                                unsigned TruncatedElements) {
2667   SubobjectDesignator &D = Result.Designator;
2668 
2669   // Check we actually point to a derived class object.
2670   if (TruncatedElements == D.Entries.size())
2671     return true;
2672   assert(TruncatedElements >= D.MostDerivedPathLength &&
2673          "not casting to a derived class");
2674   if (!Result.checkSubobject(Info, E, CSK_Derived))
2675     return false;
2676 
2677   // Truncate the path to the subobject, and remove any derived-to-base offsets.
2678   const RecordDecl *RD = TruncatedType;
2679   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2680     if (RD->isInvalidDecl()) return false;
2681     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2682     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2683     if (isVirtualBaseClass(D.Entries[I]))
2684       Result.Offset -= Layout.getVBaseClassOffset(Base);
2685     else
2686       Result.Offset -= Layout.getBaseClassOffset(Base);
2687     RD = Base;
2688   }
2689   D.Entries.resize(TruncatedElements);
2690   return true;
2691 }
2692 
2693 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2694                                    const CXXRecordDecl *Derived,
2695                                    const CXXRecordDecl *Base,
2696                                    const ASTRecordLayout *RL = nullptr) {
2697   if (!RL) {
2698     if (Derived->isInvalidDecl()) return false;
2699     RL = &Info.Ctx.getASTRecordLayout(Derived);
2700   }
2701 
2702   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2703   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2704   return true;
2705 }
2706 
2707 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2708                              const CXXRecordDecl *DerivedDecl,
2709                              const CXXBaseSpecifier *Base) {
2710   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2711 
2712   if (!Base->isVirtual())
2713     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2714 
2715   SubobjectDesignator &D = Obj.Designator;
2716   if (D.Invalid)
2717     return false;
2718 
2719   // Extract most-derived object and corresponding type.
2720   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2721   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2722     return false;
2723 
2724   // Find the virtual base class.
2725   if (DerivedDecl->isInvalidDecl()) return false;
2726   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2727   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2728   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2729   return true;
2730 }
2731 
2732 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2733                                  QualType Type, LValue &Result) {
2734   for (CastExpr::path_const_iterator PathI = E->path_begin(),
2735                                      PathE = E->path_end();
2736        PathI != PathE; ++PathI) {
2737     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2738                           *PathI))
2739       return false;
2740     Type = (*PathI)->getType();
2741   }
2742   return true;
2743 }
2744 
2745 /// Cast an lvalue referring to a derived class to a known base subobject.
2746 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2747                             const CXXRecordDecl *DerivedRD,
2748                             const CXXRecordDecl *BaseRD) {
2749   CXXBasePaths Paths(/*FindAmbiguities=*/false,
2750                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
2751   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2752     llvm_unreachable("Class must be derived from the passed in base class!");
2753 
2754   for (CXXBasePathElement &Elem : Paths.front())
2755     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2756       return false;
2757   return true;
2758 }
2759 
2760 /// Update LVal to refer to the given field, which must be a member of the type
2761 /// currently described by LVal.
2762 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2763                                const FieldDecl *FD,
2764                                const ASTRecordLayout *RL = nullptr) {
2765   if (!RL) {
2766     if (FD->getParent()->isInvalidDecl()) return false;
2767     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2768   }
2769 
2770   unsigned I = FD->getFieldIndex();
2771   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2772   LVal.addDecl(Info, E, FD);
2773   return true;
2774 }
2775 
2776 /// Update LVal to refer to the given indirect field.
2777 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2778                                        LValue &LVal,
2779                                        const IndirectFieldDecl *IFD) {
2780   for (const auto *C : IFD->chain())
2781     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2782       return false;
2783   return true;
2784 }
2785 
2786 /// Get the size of the given type in char units.
2787 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2788                          QualType Type, CharUnits &Size) {
2789   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2790   // extension.
2791   if (Type->isVoidType() || Type->isFunctionType()) {
2792     Size = CharUnits::One();
2793     return true;
2794   }
2795 
2796   if (Type->isDependentType()) {
2797     Info.FFDiag(Loc);
2798     return false;
2799   }
2800 
2801   if (!Type->isConstantSizeType()) {
2802     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2803     // FIXME: Better diagnostic.
2804     Info.FFDiag(Loc);
2805     return false;
2806   }
2807 
2808   Size = Info.Ctx.getTypeSizeInChars(Type);
2809   return true;
2810 }
2811 
2812 /// Update a pointer value to model pointer arithmetic.
2813 /// \param Info - Information about the ongoing evaluation.
2814 /// \param E - The expression being evaluated, for diagnostic purposes.
2815 /// \param LVal - The pointer value to be updated.
2816 /// \param EltTy - The pointee type represented by LVal.
2817 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2818 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2819                                         LValue &LVal, QualType EltTy,
2820                                         APSInt Adjustment) {
2821   CharUnits SizeOfPointee;
2822   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2823     return false;
2824 
2825   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2826   return true;
2827 }
2828 
2829 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2830                                         LValue &LVal, QualType EltTy,
2831                                         int64_t Adjustment) {
2832   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2833                                      APSInt::get(Adjustment));
2834 }
2835 
2836 /// Update an lvalue to refer to a component of a complex number.
2837 /// \param Info - Information about the ongoing evaluation.
2838 /// \param LVal - The lvalue to be updated.
2839 /// \param EltTy - The complex number's component type.
2840 /// \param Imag - False for the real component, true for the imaginary.
2841 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2842                                        LValue &LVal, QualType EltTy,
2843                                        bool Imag) {
2844   if (Imag) {
2845     CharUnits SizeOfComponent;
2846     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2847       return false;
2848     LVal.Offset += SizeOfComponent;
2849   }
2850   LVal.addComplex(Info, E, EltTy, Imag);
2851   return true;
2852 }
2853 
2854 /// Try to evaluate the initializer for a variable declaration.
2855 ///
2856 /// \param Info   Information about the ongoing evaluation.
2857 /// \param E      An expression to be used when printing diagnostics.
2858 /// \param VD     The variable whose initializer should be obtained.
2859 /// \param Frame  The frame in which the variable was created. Must be null
2860 ///               if this variable is not local to the evaluation.
2861 /// \param Result Filled in with a pointer to the value of the variable.
2862 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2863                                 const VarDecl *VD, CallStackFrame *Frame,
2864                                 APValue *&Result, const LValue *LVal) {
2865 
2866   // If this is a parameter to an active constexpr function call, perform
2867   // argument substitution.
2868   if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2869     // Assume arguments of a potential constant expression are unknown
2870     // constant expressions.
2871     if (Info.checkingPotentialConstantExpression())
2872       return false;
2873     if (!Frame || !Frame->Arguments) {
2874       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2875       return false;
2876     }
2877     Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2878     return true;
2879   }
2880 
2881   // If this is a local variable, dig out its value.
2882   if (Frame) {
2883     Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2884                   : Frame->getCurrentTemporary(VD);
2885     if (!Result) {
2886       // Assume variables referenced within a lambda's call operator that were
2887       // not declared within the call operator are captures and during checking
2888       // of a potential constant expression, assume they are unknown constant
2889       // expressions.
2890       assert(isLambdaCallOperator(Frame->Callee) &&
2891              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2892              "missing value for local variable");
2893       if (Info.checkingPotentialConstantExpression())
2894         return false;
2895       // FIXME: implement capture evaluation during constant expr evaluation.
2896       Info.FFDiag(E->getBeginLoc(),
2897                   diag::note_unimplemented_constexpr_lambda_feature_ast)
2898           << "captures not currently allowed";
2899       return false;
2900     }
2901     return true;
2902   }
2903 
2904   // Dig out the initializer, and use the declaration which it's attached to.
2905   const Expr *Init = VD->getAnyInitializer(VD);
2906   if (!Init || Init->isValueDependent()) {
2907     // If we're checking a potential constant expression, the variable could be
2908     // initialized later.
2909     if (!Info.checkingPotentialConstantExpression())
2910       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2911     return false;
2912   }
2913 
2914   // If we're currently evaluating the initializer of this declaration, use that
2915   // in-flight value.
2916   if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2917     Result = Info.EvaluatingDeclValue;
2918     return true;
2919   }
2920 
2921   // Never evaluate the initializer of a weak variable. We can't be sure that
2922   // this is the definition which will be used.
2923   if (VD->isWeak()) {
2924     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2925     return false;
2926   }
2927 
2928   // Check that we can fold the initializer. In C++, we will have already done
2929   // this in the cases where it matters for conformance.
2930   SmallVector<PartialDiagnosticAt, 8> Notes;
2931   if (!VD->evaluateValue(Notes)) {
2932     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2933               Notes.size() + 1) << VD;
2934     Info.Note(VD->getLocation(), diag::note_declared_at);
2935     Info.addNotes(Notes);
2936     return false;
2937   } else if (!VD->checkInitIsICE()) {
2938     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2939                  Notes.size() + 1) << VD;
2940     Info.Note(VD->getLocation(), diag::note_declared_at);
2941     Info.addNotes(Notes);
2942   }
2943 
2944   Result = VD->getEvaluatedValue();
2945   return true;
2946 }
2947 
2948 static bool IsConstNonVolatile(QualType T) {
2949   Qualifiers Quals = T.getQualifiers();
2950   return Quals.hasConst() && !Quals.hasVolatile();
2951 }
2952 
2953 /// Get the base index of the given base class within an APValue representing
2954 /// the given derived class.
2955 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2956                              const CXXRecordDecl *Base) {
2957   Base = Base->getCanonicalDecl();
2958   unsigned Index = 0;
2959   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2960          E = Derived->bases_end(); I != E; ++I, ++Index) {
2961     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2962       return Index;
2963   }
2964 
2965   llvm_unreachable("base class missing from derived class's bases list");
2966 }
2967 
2968 /// Extract the value of a character from a string literal.
2969 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2970                                             uint64_t Index) {
2971   assert(!isa<SourceLocExpr>(Lit) &&
2972          "SourceLocExpr should have already been converted to a StringLiteral");
2973 
2974   // FIXME: Support MakeStringConstant
2975   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2976     std::string Str;
2977     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2978     assert(Index <= Str.size() && "Index too large");
2979     return APSInt::getUnsigned(Str.c_str()[Index]);
2980   }
2981 
2982   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2983     Lit = PE->getFunctionName();
2984   const StringLiteral *S = cast<StringLiteral>(Lit);
2985   const ConstantArrayType *CAT =
2986       Info.Ctx.getAsConstantArrayType(S->getType());
2987   assert(CAT && "string literal isn't an array");
2988   QualType CharType = CAT->getElementType();
2989   assert(CharType->isIntegerType() && "unexpected character type");
2990 
2991   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2992                CharType->isUnsignedIntegerType());
2993   if (Index < S->getLength())
2994     Value = S->getCodeUnit(Index);
2995   return Value;
2996 }
2997 
2998 // Expand a string literal into an array of characters.
2999 //
3000 // FIXME: This is inefficient; we should probably introduce something similar
3001 // to the LLVM ConstantDataArray to make this cheaper.
3002 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3003                                 APValue &Result,
3004                                 QualType AllocType = QualType()) {
3005   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3006       AllocType.isNull() ? S->getType() : AllocType);
3007   assert(CAT && "string literal isn't an array");
3008   QualType CharType = CAT->getElementType();
3009   assert(CharType->isIntegerType() && "unexpected character type");
3010 
3011   unsigned Elts = CAT->getSize().getZExtValue();
3012   Result = APValue(APValue::UninitArray(),
3013                    std::min(S->getLength(), Elts), Elts);
3014   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3015                CharType->isUnsignedIntegerType());
3016   if (Result.hasArrayFiller())
3017     Result.getArrayFiller() = APValue(Value);
3018   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3019     Value = S->getCodeUnit(I);
3020     Result.getArrayInitializedElt(I) = APValue(Value);
3021   }
3022 }
3023 
3024 // Expand an array so that it has more than Index filled elements.
3025 static void expandArray(APValue &Array, unsigned Index) {
3026   unsigned Size = Array.getArraySize();
3027   assert(Index < Size);
3028 
3029   // Always at least double the number of elements for which we store a value.
3030   unsigned OldElts = Array.getArrayInitializedElts();
3031   unsigned NewElts = std::max(Index+1, OldElts * 2);
3032   NewElts = std::min(Size, std::max(NewElts, 8u));
3033 
3034   // Copy the data across.
3035   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3036   for (unsigned I = 0; I != OldElts; ++I)
3037     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3038   for (unsigned I = OldElts; I != NewElts; ++I)
3039     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3040   if (NewValue.hasArrayFiller())
3041     NewValue.getArrayFiller() = Array.getArrayFiller();
3042   Array.swap(NewValue);
3043 }
3044 
3045 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3046 /// conversion. If it's of class type, we may assume that the copy operation
3047 /// is trivial. Note that this is never true for a union type with fields
3048 /// (because the copy always "reads" the active member) and always true for
3049 /// a non-class type.
3050 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3051 static bool isReadByLvalueToRvalueConversion(QualType T) {
3052   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3053   return !RD || isReadByLvalueToRvalueConversion(RD);
3054 }
3055 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3056   // FIXME: A trivial copy of a union copies the object representation, even if
3057   // the union is empty.
3058   if (RD->isUnion())
3059     return !RD->field_empty();
3060   if (RD->isEmpty())
3061     return false;
3062 
3063   for (auto *Field : RD->fields())
3064     if (!Field->isUnnamedBitfield() &&
3065         isReadByLvalueToRvalueConversion(Field->getType()))
3066       return true;
3067 
3068   for (auto &BaseSpec : RD->bases())
3069     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3070       return true;
3071 
3072   return false;
3073 }
3074 
3075 /// Diagnose an attempt to read from any unreadable field within the specified
3076 /// type, which might be a class type.
3077 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3078                                   QualType T) {
3079   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3080   if (!RD)
3081     return false;
3082 
3083   if (!RD->hasMutableFields())
3084     return false;
3085 
3086   for (auto *Field : RD->fields()) {
3087     // If we're actually going to read this field in some way, then it can't
3088     // be mutable. If we're in a union, then assigning to a mutable field
3089     // (even an empty one) can change the active member, so that's not OK.
3090     // FIXME: Add core issue number for the union case.
3091     if (Field->isMutable() &&
3092         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3093       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3094       Info.Note(Field->getLocation(), diag::note_declared_at);
3095       return true;
3096     }
3097 
3098     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3099       return true;
3100   }
3101 
3102   for (auto &BaseSpec : RD->bases())
3103     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3104       return true;
3105 
3106   // All mutable fields were empty, and thus not actually read.
3107   return false;
3108 }
3109 
3110 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3111                                         APValue::LValueBase Base,
3112                                         bool MutableSubobject = false) {
3113   // A temporary we created.
3114   if (Base.getCallIndex())
3115     return true;
3116 
3117   auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3118   if (!Evaluating)
3119     return false;
3120 
3121   auto *BaseD = Base.dyn_cast<const ValueDecl*>();
3122 
3123   switch (Info.IsEvaluatingDecl) {
3124   case EvalInfo::EvaluatingDeclKind::None:
3125     return false;
3126 
3127   case EvalInfo::EvaluatingDeclKind::Ctor:
3128     // The variable whose initializer we're evaluating.
3129     if (BaseD)
3130       return declaresSameEntity(Evaluating, BaseD);
3131 
3132     // A temporary lifetime-extended by the variable whose initializer we're
3133     // evaluating.
3134     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3135       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3136         return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating);
3137     return false;
3138 
3139   case EvalInfo::EvaluatingDeclKind::Dtor:
3140     // C++2a [expr.const]p6:
3141     //   [during constant destruction] the lifetime of a and its non-mutable
3142     //   subobjects (but not its mutable subobjects) [are] considered to start
3143     //   within e.
3144     //
3145     // FIXME: We can meaningfully extend this to cover non-const objects, but
3146     // we will need special handling: we should be able to access only
3147     // subobjects of such objects that are themselves declared const.
3148     if (!BaseD ||
3149         !(BaseD->getType().isConstQualified() ||
3150           BaseD->getType()->isReferenceType()) ||
3151         MutableSubobject)
3152       return false;
3153     return declaresSameEntity(Evaluating, BaseD);
3154   }
3155 
3156   llvm_unreachable("unknown evaluating decl kind");
3157 }
3158 
3159 namespace {
3160 /// A handle to a complete object (an object that is not a subobject of
3161 /// another object).
3162 struct CompleteObject {
3163   /// The identity of the object.
3164   APValue::LValueBase Base;
3165   /// The value of the complete object.
3166   APValue *Value;
3167   /// The type of the complete object.
3168   QualType Type;
3169 
3170   CompleteObject() : Value(nullptr) {}
3171   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3172       : Base(Base), Value(Value), Type(Type) {}
3173 
3174   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3175     // If this isn't a "real" access (eg, if it's just accessing the type
3176     // info), allow it. We assume the type doesn't change dynamically for
3177     // subobjects of constexpr objects (even though we'd hit UB here if it
3178     // did). FIXME: Is this right?
3179     if (!isAnyAccess(AK))
3180       return true;
3181 
3182     // In C++14 onwards, it is permitted to read a mutable member whose
3183     // lifetime began within the evaluation.
3184     // FIXME: Should we also allow this in C++11?
3185     if (!Info.getLangOpts().CPlusPlus14)
3186       return false;
3187     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3188   }
3189 
3190   explicit operator bool() const { return !Type.isNull(); }
3191 };
3192 } // end anonymous namespace
3193 
3194 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3195                                  bool IsMutable = false) {
3196   // C++ [basic.type.qualifier]p1:
3197   // - A const object is an object of type const T or a non-mutable subobject
3198   //   of a const object.
3199   if (ObjType.isConstQualified() && !IsMutable)
3200     SubobjType.addConst();
3201   // - A volatile object is an object of type const T or a subobject of a
3202   //   volatile object.
3203   if (ObjType.isVolatileQualified())
3204     SubobjType.addVolatile();
3205   return SubobjType;
3206 }
3207 
3208 /// Find the designated sub-object of an rvalue.
3209 template<typename SubobjectHandler>
3210 typename SubobjectHandler::result_type
3211 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3212               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3213   if (Sub.Invalid)
3214     // A diagnostic will have already been produced.
3215     return handler.failed();
3216   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3217     if (Info.getLangOpts().CPlusPlus11)
3218       Info.FFDiag(E, Sub.isOnePastTheEnd()
3219                          ? diag::note_constexpr_access_past_end
3220                          : diag::note_constexpr_access_unsized_array)
3221           << handler.AccessKind;
3222     else
3223       Info.FFDiag(E);
3224     return handler.failed();
3225   }
3226 
3227   APValue *O = Obj.Value;
3228   QualType ObjType = Obj.Type;
3229   const FieldDecl *LastField = nullptr;
3230   const FieldDecl *VolatileField = nullptr;
3231 
3232   // Walk the designator's path to find the subobject.
3233   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3234     // Reading an indeterminate value is undefined, but assigning over one is OK.
3235     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3236         (O->isIndeterminate() &&
3237          !isValidIndeterminateAccess(handler.AccessKind))) {
3238       if (!Info.checkingPotentialConstantExpression())
3239         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3240             << handler.AccessKind << O->isIndeterminate();
3241       return handler.failed();
3242     }
3243 
3244     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3245     //    const and volatile semantics are not applied on an object under
3246     //    {con,de}struction.
3247     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3248         ObjType->isRecordType() &&
3249         Info.isEvaluatingCtorDtor(
3250             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3251                                          Sub.Entries.begin() + I)) !=
3252                           ConstructionPhase::None) {
3253       ObjType = Info.Ctx.getCanonicalType(ObjType);
3254       ObjType.removeLocalConst();
3255       ObjType.removeLocalVolatile();
3256     }
3257 
3258     // If this is our last pass, check that the final object type is OK.
3259     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3260       // Accesses to volatile objects are prohibited.
3261       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3262         if (Info.getLangOpts().CPlusPlus) {
3263           int DiagKind;
3264           SourceLocation Loc;
3265           const NamedDecl *Decl = nullptr;
3266           if (VolatileField) {
3267             DiagKind = 2;
3268             Loc = VolatileField->getLocation();
3269             Decl = VolatileField;
3270           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3271             DiagKind = 1;
3272             Loc = VD->getLocation();
3273             Decl = VD;
3274           } else {
3275             DiagKind = 0;
3276             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3277               Loc = E->getExprLoc();
3278           }
3279           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3280               << handler.AccessKind << DiagKind << Decl;
3281           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3282         } else {
3283           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3284         }
3285         return handler.failed();
3286       }
3287 
3288       // If we are reading an object of class type, there may still be more
3289       // things we need to check: if there are any mutable subobjects, we
3290       // cannot perform this read. (This only happens when performing a trivial
3291       // copy or assignment.)
3292       if (ObjType->isRecordType() &&
3293           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3294           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3295         return handler.failed();
3296     }
3297 
3298     if (I == N) {
3299       if (!handler.found(*O, ObjType))
3300         return false;
3301 
3302       // If we modified a bit-field, truncate it to the right width.
3303       if (isModification(handler.AccessKind) &&
3304           LastField && LastField->isBitField() &&
3305           !truncateBitfieldValue(Info, E, *O, LastField))
3306         return false;
3307 
3308       return true;
3309     }
3310 
3311     LastField = nullptr;
3312     if (ObjType->isArrayType()) {
3313       // Next subobject is an array element.
3314       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3315       assert(CAT && "vla in literal type?");
3316       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3317       if (CAT->getSize().ule(Index)) {
3318         // Note, it should not be possible to form a pointer with a valid
3319         // designator which points more than one past the end of the array.
3320         if (Info.getLangOpts().CPlusPlus11)
3321           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3322             << handler.AccessKind;
3323         else
3324           Info.FFDiag(E);
3325         return handler.failed();
3326       }
3327 
3328       ObjType = CAT->getElementType();
3329 
3330       if (O->getArrayInitializedElts() > Index)
3331         O = &O->getArrayInitializedElt(Index);
3332       else if (!isRead(handler.AccessKind)) {
3333         expandArray(*O, Index);
3334         O = &O->getArrayInitializedElt(Index);
3335       } else
3336         O = &O->getArrayFiller();
3337     } else if (ObjType->isAnyComplexType()) {
3338       // Next subobject is a complex number.
3339       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3340       if (Index > 1) {
3341         if (Info.getLangOpts().CPlusPlus11)
3342           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3343             << handler.AccessKind;
3344         else
3345           Info.FFDiag(E);
3346         return handler.failed();
3347       }
3348 
3349       ObjType = getSubobjectType(
3350           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3351 
3352       assert(I == N - 1 && "extracting subobject of scalar?");
3353       if (O->isComplexInt()) {
3354         return handler.found(Index ? O->getComplexIntImag()
3355                                    : O->getComplexIntReal(), ObjType);
3356       } else {
3357         assert(O->isComplexFloat());
3358         return handler.found(Index ? O->getComplexFloatImag()
3359                                    : O->getComplexFloatReal(), ObjType);
3360       }
3361     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3362       if (Field->isMutable() &&
3363           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3364         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3365           << handler.AccessKind << Field;
3366         Info.Note(Field->getLocation(), diag::note_declared_at);
3367         return handler.failed();
3368       }
3369 
3370       // Next subobject is a class, struct or union field.
3371       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3372       if (RD->isUnion()) {
3373         const FieldDecl *UnionField = O->getUnionField();
3374         if (!UnionField ||
3375             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3376           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3377             // Placement new onto an inactive union member makes it active.
3378             O->setUnion(Field, APValue());
3379           } else {
3380             // FIXME: If O->getUnionValue() is absent, report that there's no
3381             // active union member rather than reporting the prior active union
3382             // member. We'll need to fix nullptr_t to not use APValue() as its
3383             // representation first.
3384             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3385                 << handler.AccessKind << Field << !UnionField << UnionField;
3386             return handler.failed();
3387           }
3388         }
3389         O = &O->getUnionValue();
3390       } else
3391         O = &O->getStructField(Field->getFieldIndex());
3392 
3393       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3394       LastField = Field;
3395       if (Field->getType().isVolatileQualified())
3396         VolatileField = Field;
3397     } else {
3398       // Next subobject is a base class.
3399       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3400       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3401       O = &O->getStructBase(getBaseIndex(Derived, Base));
3402 
3403       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3404     }
3405   }
3406 }
3407 
3408 namespace {
3409 struct ExtractSubobjectHandler {
3410   EvalInfo &Info;
3411   const Expr *E;
3412   APValue &Result;
3413   const AccessKinds AccessKind;
3414 
3415   typedef bool result_type;
3416   bool failed() { return false; }
3417   bool found(APValue &Subobj, QualType SubobjType) {
3418     Result = Subobj;
3419     if (AccessKind == AK_ReadObjectRepresentation)
3420       return true;
3421     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3422   }
3423   bool found(APSInt &Value, QualType SubobjType) {
3424     Result = APValue(Value);
3425     return true;
3426   }
3427   bool found(APFloat &Value, QualType SubobjType) {
3428     Result = APValue(Value);
3429     return true;
3430   }
3431 };
3432 } // end anonymous namespace
3433 
3434 /// Extract the designated sub-object of an rvalue.
3435 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3436                              const CompleteObject &Obj,
3437                              const SubobjectDesignator &Sub, APValue &Result,
3438                              AccessKinds AK = AK_Read) {
3439   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3440   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3441   return findSubobject(Info, E, Obj, Sub, Handler);
3442 }
3443 
3444 namespace {
3445 struct ModifySubobjectHandler {
3446   EvalInfo &Info;
3447   APValue &NewVal;
3448   const Expr *E;
3449 
3450   typedef bool result_type;
3451   static const AccessKinds AccessKind = AK_Assign;
3452 
3453   bool checkConst(QualType QT) {
3454     // Assigning to a const object has undefined behavior.
3455     if (QT.isConstQualified()) {
3456       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3457       return false;
3458     }
3459     return true;
3460   }
3461 
3462   bool failed() { return false; }
3463   bool found(APValue &Subobj, QualType SubobjType) {
3464     if (!checkConst(SubobjType))
3465       return false;
3466     // We've been given ownership of NewVal, so just swap it in.
3467     Subobj.swap(NewVal);
3468     return true;
3469   }
3470   bool found(APSInt &Value, QualType SubobjType) {
3471     if (!checkConst(SubobjType))
3472       return false;
3473     if (!NewVal.isInt()) {
3474       // Maybe trying to write a cast pointer value into a complex?
3475       Info.FFDiag(E);
3476       return false;
3477     }
3478     Value = NewVal.getInt();
3479     return true;
3480   }
3481   bool found(APFloat &Value, QualType SubobjType) {
3482     if (!checkConst(SubobjType))
3483       return false;
3484     Value = NewVal.getFloat();
3485     return true;
3486   }
3487 };
3488 } // end anonymous namespace
3489 
3490 const AccessKinds ModifySubobjectHandler::AccessKind;
3491 
3492 /// Update the designated sub-object of an rvalue to the given value.
3493 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3494                             const CompleteObject &Obj,
3495                             const SubobjectDesignator &Sub,
3496                             APValue &NewVal) {
3497   ModifySubobjectHandler Handler = { Info, NewVal, E };
3498   return findSubobject(Info, E, Obj, Sub, Handler);
3499 }
3500 
3501 /// Find the position where two subobject designators diverge, or equivalently
3502 /// the length of the common initial subsequence.
3503 static unsigned FindDesignatorMismatch(QualType ObjType,
3504                                        const SubobjectDesignator &A,
3505                                        const SubobjectDesignator &B,
3506                                        bool &WasArrayIndex) {
3507   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3508   for (/**/; I != N; ++I) {
3509     if (!ObjType.isNull() &&
3510         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3511       // Next subobject is an array element.
3512       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3513         WasArrayIndex = true;
3514         return I;
3515       }
3516       if (ObjType->isAnyComplexType())
3517         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3518       else
3519         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3520     } else {
3521       if (A.Entries[I].getAsBaseOrMember() !=
3522           B.Entries[I].getAsBaseOrMember()) {
3523         WasArrayIndex = false;
3524         return I;
3525       }
3526       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3527         // Next subobject is a field.
3528         ObjType = FD->getType();
3529       else
3530         // Next subobject is a base class.
3531         ObjType = QualType();
3532     }
3533   }
3534   WasArrayIndex = false;
3535   return I;
3536 }
3537 
3538 /// Determine whether the given subobject designators refer to elements of the
3539 /// same array object.
3540 static bool AreElementsOfSameArray(QualType ObjType,
3541                                    const SubobjectDesignator &A,
3542                                    const SubobjectDesignator &B) {
3543   if (A.Entries.size() != B.Entries.size())
3544     return false;
3545 
3546   bool IsArray = A.MostDerivedIsArrayElement;
3547   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3548     // A is a subobject of the array element.
3549     return false;
3550 
3551   // If A (and B) designates an array element, the last entry will be the array
3552   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3553   // of length 1' case, and the entire path must match.
3554   bool WasArrayIndex;
3555   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3556   return CommonLength >= A.Entries.size() - IsArray;
3557 }
3558 
3559 /// Find the complete object to which an LValue refers.
3560 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3561                                          AccessKinds AK, const LValue &LVal,
3562                                          QualType LValType) {
3563   if (LVal.InvalidBase) {
3564     Info.FFDiag(E);
3565     return CompleteObject();
3566   }
3567 
3568   if (!LVal.Base) {
3569     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3570     return CompleteObject();
3571   }
3572 
3573   CallStackFrame *Frame = nullptr;
3574   unsigned Depth = 0;
3575   if (LVal.getLValueCallIndex()) {
3576     std::tie(Frame, Depth) =
3577         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3578     if (!Frame) {
3579       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3580         << AK << LVal.Base.is<const ValueDecl*>();
3581       NoteLValueLocation(Info, LVal.Base);
3582       return CompleteObject();
3583     }
3584   }
3585 
3586   bool IsAccess = isAnyAccess(AK);
3587 
3588   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3589   // is not a constant expression (even if the object is non-volatile). We also
3590   // apply this rule to C++98, in order to conform to the expected 'volatile'
3591   // semantics.
3592   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3593     if (Info.getLangOpts().CPlusPlus)
3594       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3595         << AK << LValType;
3596     else
3597       Info.FFDiag(E);
3598     return CompleteObject();
3599   }
3600 
3601   // Compute value storage location and type of base object.
3602   APValue *BaseVal = nullptr;
3603   QualType BaseType = getType(LVal.Base);
3604 
3605   if (const ConstantExpr *CE =
3606           dyn_cast_or_null<ConstantExpr>(LVal.Base.dyn_cast<const Expr *>())) {
3607     /// Nested immediate invocation have been previously removed so if we found
3608     /// a ConstantExpr it can only be the EvaluatingDecl.
3609     assert(CE->isImmediateInvocation() && CE == Info.EvaluatingDecl);
3610     BaseVal = Info.EvaluatingDeclValue;
3611   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
3612     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3613     // In C++11, constexpr, non-volatile variables initialized with constant
3614     // expressions are constant expressions too. Inside constexpr functions,
3615     // parameters are constant expressions even if they're non-const.
3616     // In C++1y, objects local to a constant expression (those with a Frame) are
3617     // both readable and writable inside constant expressions.
3618     // In C, such things can also be folded, although they are not ICEs.
3619     const VarDecl *VD = dyn_cast<VarDecl>(D);
3620     if (VD) {
3621       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3622         VD = VDef;
3623     }
3624     if (!VD || VD->isInvalidDecl()) {
3625       Info.FFDiag(E);
3626       return CompleteObject();
3627     }
3628 
3629     // Unless we're looking at a local variable or argument in a constexpr call,
3630     // the variable we're reading must be const.
3631     if (!Frame) {
3632       if (Info.getLangOpts().CPlusPlus14 &&
3633           lifetimeStartedInEvaluation(Info, LVal.Base)) {
3634         // OK, we can read and modify an object if we're in the process of
3635         // evaluating its initializer, because its lifetime began in this
3636         // evaluation.
3637       } else if (isModification(AK)) {
3638         // All the remaining cases do not permit modification of the object.
3639         Info.FFDiag(E, diag::note_constexpr_modify_global);
3640         return CompleteObject();
3641       } else if (VD->isConstexpr()) {
3642         // OK, we can read this variable.
3643       } else if (BaseType->isIntegralOrEnumerationType()) {
3644         // In OpenCL if a variable is in constant address space it is a const
3645         // value.
3646         if (!(BaseType.isConstQualified() ||
3647               (Info.getLangOpts().OpenCL &&
3648                BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3649           if (!IsAccess)
3650             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3651           if (Info.getLangOpts().CPlusPlus) {
3652             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3653             Info.Note(VD->getLocation(), diag::note_declared_at);
3654           } else {
3655             Info.FFDiag(E);
3656           }
3657           return CompleteObject();
3658         }
3659       } else if (!IsAccess) {
3660         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3661       } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3662         // We support folding of const floating-point types, in order to make
3663         // static const data members of such types (supported as an extension)
3664         // more useful.
3665         if (Info.getLangOpts().CPlusPlus11) {
3666           Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3667           Info.Note(VD->getLocation(), diag::note_declared_at);
3668         } else {
3669           Info.CCEDiag(E);
3670         }
3671       } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3672         Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3673         // Keep evaluating to see what we can do.
3674       } else {
3675         // FIXME: Allow folding of values of any literal type in all languages.
3676         if (Info.checkingPotentialConstantExpression() &&
3677             VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3678           // The definition of this variable could be constexpr. We can't
3679           // access it right now, but may be able to in future.
3680         } else if (Info.getLangOpts().CPlusPlus11) {
3681           Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3682           Info.Note(VD->getLocation(), diag::note_declared_at);
3683         } else {
3684           Info.FFDiag(E);
3685         }
3686         return CompleteObject();
3687       }
3688     }
3689 
3690     if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
3691       return CompleteObject();
3692   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
3693     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
3694     if (!Alloc) {
3695       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
3696       return CompleteObject();
3697     }
3698     return CompleteObject(LVal.Base, &(*Alloc)->Value,
3699                           LVal.Base.getDynamicAllocType());
3700   } else {
3701     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3702 
3703     if (!Frame) {
3704       if (const MaterializeTemporaryExpr *MTE =
3705               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
3706         assert(MTE->getStorageDuration() == SD_Static &&
3707                "should have a frame for a non-global materialized temporary");
3708 
3709         // Per C++1y [expr.const]p2:
3710         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3711         //   - a [...] glvalue of integral or enumeration type that refers to
3712         //     a non-volatile const object [...]
3713         //   [...]
3714         //   - a [...] glvalue of literal type that refers to a non-volatile
3715         //     object whose lifetime began within the evaluation of e.
3716         //
3717         // C++11 misses the 'began within the evaluation of e' check and
3718         // instead allows all temporaries, including things like:
3719         //   int &&r = 1;
3720         //   int x = ++r;
3721         //   constexpr int k = r;
3722         // Therefore we use the C++14 rules in C++11 too.
3723         //
3724         // Note that temporaries whose lifetimes began while evaluating a
3725         // variable's constructor are not usable while evaluating the
3726         // corresponding destructor, not even if they're of const-qualified
3727         // types.
3728         if (!(BaseType.isConstQualified() &&
3729               BaseType->isIntegralOrEnumerationType()) &&
3730             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
3731           if (!IsAccess)
3732             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3733           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3734           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3735           return CompleteObject();
3736         }
3737 
3738         BaseVal = MTE->getOrCreateValue(false);
3739         assert(BaseVal && "got reference to unevaluated temporary");
3740       } else {
3741         if (!IsAccess)
3742           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3743         APValue Val;
3744         LVal.moveInto(Val);
3745         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3746             << AK
3747             << Val.getAsString(Info.Ctx,
3748                                Info.Ctx.getLValueReferenceType(LValType));
3749         NoteLValueLocation(Info, LVal.Base);
3750         return CompleteObject();
3751       }
3752     } else {
3753       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
3754       assert(BaseVal && "missing value for temporary");
3755     }
3756   }
3757 
3758   // In C++14, we can't safely access any mutable state when we might be
3759   // evaluating after an unmodeled side effect.
3760   //
3761   // FIXME: Not all local state is mutable. Allow local constant subobjects
3762   // to be read here (but take care with 'mutable' fields).
3763   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3764        Info.EvalStatus.HasSideEffects) ||
3765       (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
3766     return CompleteObject();
3767 
3768   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
3769 }
3770 
3771 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
3772 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3773 /// glvalue referred to by an entity of reference type.
3774 ///
3775 /// \param Info - Information about the ongoing evaluation.
3776 /// \param Conv - The expression for which we are performing the conversion.
3777 ///               Used for diagnostics.
3778 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3779 ///               case of a non-class type).
3780 /// \param LVal - The glvalue on which we are attempting to perform this action.
3781 /// \param RVal - The produced value will be placed here.
3782 /// \param WantObjectRepresentation - If true, we're looking for the object
3783 ///               representation rather than the value, and in particular,
3784 ///               there is no requirement that the result be fully initialized.
3785 static bool
3786 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
3787                                const LValue &LVal, APValue &RVal,
3788                                bool WantObjectRepresentation = false) {
3789   if (LVal.Designator.Invalid)
3790     return false;
3791 
3792   // Check for special cases where there is no existing APValue to look at.
3793   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3794 
3795   AccessKinds AK =
3796       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
3797 
3798   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
3799     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3800       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3801       // initializer until now for such expressions. Such an expression can't be
3802       // an ICE in C, so this only matters for fold.
3803       if (Type.isVolatileQualified()) {
3804         Info.FFDiag(Conv);
3805         return false;
3806       }
3807       APValue Lit;
3808       if (!Evaluate(Lit, Info, CLE->getInitializer()))
3809         return false;
3810       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
3811       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
3812     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3813       // Special-case character extraction so we don't have to construct an
3814       // APValue for the whole string.
3815       assert(LVal.Designator.Entries.size() <= 1 &&
3816              "Can only read characters from string literals");
3817       if (LVal.Designator.Entries.empty()) {
3818         // Fail for now for LValue to RValue conversion of an array.
3819         // (This shouldn't show up in C/C++, but it could be triggered by a
3820         // weird EvaluateAsRValue call from a tool.)
3821         Info.FFDiag(Conv);
3822         return false;
3823       }
3824       if (LVal.Designator.isOnePastTheEnd()) {
3825         if (Info.getLangOpts().CPlusPlus11)
3826           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
3827         else
3828           Info.FFDiag(Conv);
3829         return false;
3830       }
3831       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
3832       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3833       return true;
3834     }
3835   }
3836 
3837   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
3838   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
3839 }
3840 
3841 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3842 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3843                              QualType LValType, APValue &Val) {
3844   if (LVal.Designator.Invalid)
3845     return false;
3846 
3847   if (!Info.getLangOpts().CPlusPlus14) {
3848     Info.FFDiag(E);
3849     return false;
3850   }
3851 
3852   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3853   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3854 }
3855 
3856 namespace {
3857 struct CompoundAssignSubobjectHandler {
3858   EvalInfo &Info;
3859   const Expr *E;
3860   QualType PromotedLHSType;
3861   BinaryOperatorKind Opcode;
3862   const APValue &RHS;
3863 
3864   static const AccessKinds AccessKind = AK_Assign;
3865 
3866   typedef bool result_type;
3867 
3868   bool checkConst(QualType QT) {
3869     // Assigning to a const object has undefined behavior.
3870     if (QT.isConstQualified()) {
3871       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3872       return false;
3873     }
3874     return true;
3875   }
3876 
3877   bool failed() { return false; }
3878   bool found(APValue &Subobj, QualType SubobjType) {
3879     switch (Subobj.getKind()) {
3880     case APValue::Int:
3881       return found(Subobj.getInt(), SubobjType);
3882     case APValue::Float:
3883       return found(Subobj.getFloat(), SubobjType);
3884     case APValue::ComplexInt:
3885     case APValue::ComplexFloat:
3886       // FIXME: Implement complex compound assignment.
3887       Info.FFDiag(E);
3888       return false;
3889     case APValue::LValue:
3890       return foundPointer(Subobj, SubobjType);
3891     default:
3892       // FIXME: can this happen?
3893       Info.FFDiag(E);
3894       return false;
3895     }
3896   }
3897   bool found(APSInt &Value, QualType SubobjType) {
3898     if (!checkConst(SubobjType))
3899       return false;
3900 
3901     if (!SubobjType->isIntegerType()) {
3902       // We don't support compound assignment on integer-cast-to-pointer
3903       // values.
3904       Info.FFDiag(E);
3905       return false;
3906     }
3907 
3908     if (RHS.isInt()) {
3909       APSInt LHS =
3910           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3911       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3912         return false;
3913       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3914       return true;
3915     } else if (RHS.isFloat()) {
3916       APFloat FValue(0.0);
3917       return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3918                                   FValue) &&
3919              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3920              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3921                                   Value);
3922     }
3923 
3924     Info.FFDiag(E);
3925     return false;
3926   }
3927   bool found(APFloat &Value, QualType SubobjType) {
3928     return checkConst(SubobjType) &&
3929            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3930                                   Value) &&
3931            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3932            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3933   }
3934   bool foundPointer(APValue &Subobj, QualType SubobjType) {
3935     if (!checkConst(SubobjType))
3936       return false;
3937 
3938     QualType PointeeType;
3939     if (const PointerType *PT = SubobjType->getAs<PointerType>())
3940       PointeeType = PT->getPointeeType();
3941 
3942     if (PointeeType.isNull() || !RHS.isInt() ||
3943         (Opcode != BO_Add && Opcode != BO_Sub)) {
3944       Info.FFDiag(E);
3945       return false;
3946     }
3947 
3948     APSInt Offset = RHS.getInt();
3949     if (Opcode == BO_Sub)
3950       negateAsSigned(Offset);
3951 
3952     LValue LVal;
3953     LVal.setFrom(Info.Ctx, Subobj);
3954     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3955       return false;
3956     LVal.moveInto(Subobj);
3957     return true;
3958   }
3959 };
3960 } // end anonymous namespace
3961 
3962 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3963 
3964 /// Perform a compound assignment of LVal <op>= RVal.
3965 static bool handleCompoundAssignment(
3966     EvalInfo &Info, const Expr *E,
3967     const LValue &LVal, QualType LValType, QualType PromotedLValType,
3968     BinaryOperatorKind Opcode, const APValue &RVal) {
3969   if (LVal.Designator.Invalid)
3970     return false;
3971 
3972   if (!Info.getLangOpts().CPlusPlus14) {
3973     Info.FFDiag(E);
3974     return false;
3975   }
3976 
3977   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3978   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3979                                              RVal };
3980   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3981 }
3982 
3983 namespace {
3984 struct IncDecSubobjectHandler {
3985   EvalInfo &Info;
3986   const UnaryOperator *E;
3987   AccessKinds AccessKind;
3988   APValue *Old;
3989 
3990   typedef bool result_type;
3991 
3992   bool checkConst(QualType QT) {
3993     // Assigning to a const object has undefined behavior.
3994     if (QT.isConstQualified()) {
3995       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3996       return false;
3997     }
3998     return true;
3999   }
4000 
4001   bool failed() { return false; }
4002   bool found(APValue &Subobj, QualType SubobjType) {
4003     // Stash the old value. Also clear Old, so we don't clobber it later
4004     // if we're post-incrementing a complex.
4005     if (Old) {
4006       *Old = Subobj;
4007       Old = nullptr;
4008     }
4009 
4010     switch (Subobj.getKind()) {
4011     case APValue::Int:
4012       return found(Subobj.getInt(), SubobjType);
4013     case APValue::Float:
4014       return found(Subobj.getFloat(), SubobjType);
4015     case APValue::ComplexInt:
4016       return found(Subobj.getComplexIntReal(),
4017                    SubobjType->castAs<ComplexType>()->getElementType()
4018                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4019     case APValue::ComplexFloat:
4020       return found(Subobj.getComplexFloatReal(),
4021                    SubobjType->castAs<ComplexType>()->getElementType()
4022                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4023     case APValue::LValue:
4024       return foundPointer(Subobj, SubobjType);
4025     default:
4026       // FIXME: can this happen?
4027       Info.FFDiag(E);
4028       return false;
4029     }
4030   }
4031   bool found(APSInt &Value, QualType SubobjType) {
4032     if (!checkConst(SubobjType))
4033       return false;
4034 
4035     if (!SubobjType->isIntegerType()) {
4036       // We don't support increment / decrement on integer-cast-to-pointer
4037       // values.
4038       Info.FFDiag(E);
4039       return false;
4040     }
4041 
4042     if (Old) *Old = APValue(Value);
4043 
4044     // bool arithmetic promotes to int, and the conversion back to bool
4045     // doesn't reduce mod 2^n, so special-case it.
4046     if (SubobjType->isBooleanType()) {
4047       if (AccessKind == AK_Increment)
4048         Value = 1;
4049       else
4050         Value = !Value;
4051       return true;
4052     }
4053 
4054     bool WasNegative = Value.isNegative();
4055     if (AccessKind == AK_Increment) {
4056       ++Value;
4057 
4058       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4059         APSInt ActualValue(Value, /*IsUnsigned*/true);
4060         return HandleOverflow(Info, E, ActualValue, SubobjType);
4061       }
4062     } else {
4063       --Value;
4064 
4065       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4066         unsigned BitWidth = Value.getBitWidth();
4067         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4068         ActualValue.setBit(BitWidth);
4069         return HandleOverflow(Info, E, ActualValue, SubobjType);
4070       }
4071     }
4072     return true;
4073   }
4074   bool found(APFloat &Value, QualType SubobjType) {
4075     if (!checkConst(SubobjType))
4076       return false;
4077 
4078     if (Old) *Old = APValue(Value);
4079 
4080     APFloat One(Value.getSemantics(), 1);
4081     if (AccessKind == AK_Increment)
4082       Value.add(One, APFloat::rmNearestTiesToEven);
4083     else
4084       Value.subtract(One, APFloat::rmNearestTiesToEven);
4085     return true;
4086   }
4087   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4088     if (!checkConst(SubobjType))
4089       return false;
4090 
4091     QualType PointeeType;
4092     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4093       PointeeType = PT->getPointeeType();
4094     else {
4095       Info.FFDiag(E);
4096       return false;
4097     }
4098 
4099     LValue LVal;
4100     LVal.setFrom(Info.Ctx, Subobj);
4101     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4102                                      AccessKind == AK_Increment ? 1 : -1))
4103       return false;
4104     LVal.moveInto(Subobj);
4105     return true;
4106   }
4107 };
4108 } // end anonymous namespace
4109 
4110 /// Perform an increment or decrement on LVal.
4111 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4112                          QualType LValType, bool IsIncrement, APValue *Old) {
4113   if (LVal.Designator.Invalid)
4114     return false;
4115 
4116   if (!Info.getLangOpts().CPlusPlus14) {
4117     Info.FFDiag(E);
4118     return false;
4119   }
4120 
4121   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4122   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4123   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4124   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4125 }
4126 
4127 /// Build an lvalue for the object argument of a member function call.
4128 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4129                                    LValue &This) {
4130   if (Object->getType()->isPointerType() && Object->isRValue())
4131     return EvaluatePointer(Object, This, Info);
4132 
4133   if (Object->isGLValue())
4134     return EvaluateLValue(Object, This, Info);
4135 
4136   if (Object->getType()->isLiteralType(Info.Ctx))
4137     return EvaluateTemporary(Object, This, Info);
4138 
4139   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4140   return false;
4141 }
4142 
4143 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4144 /// lvalue referring to the result.
4145 ///
4146 /// \param Info - Information about the ongoing evaluation.
4147 /// \param LV - An lvalue referring to the base of the member pointer.
4148 /// \param RHS - The member pointer expression.
4149 /// \param IncludeMember - Specifies whether the member itself is included in
4150 ///        the resulting LValue subobject designator. This is not possible when
4151 ///        creating a bound member function.
4152 /// \return The field or method declaration to which the member pointer refers,
4153 ///         or 0 if evaluation fails.
4154 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4155                                                   QualType LVType,
4156                                                   LValue &LV,
4157                                                   const Expr *RHS,
4158                                                   bool IncludeMember = true) {
4159   MemberPtr MemPtr;
4160   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4161     return nullptr;
4162 
4163   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4164   // member value, the behavior is undefined.
4165   if (!MemPtr.getDecl()) {
4166     // FIXME: Specific diagnostic.
4167     Info.FFDiag(RHS);
4168     return nullptr;
4169   }
4170 
4171   if (MemPtr.isDerivedMember()) {
4172     // This is a member of some derived class. Truncate LV appropriately.
4173     // The end of the derived-to-base path for the base object must match the
4174     // derived-to-base path for the member pointer.
4175     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4176         LV.Designator.Entries.size()) {
4177       Info.FFDiag(RHS);
4178       return nullptr;
4179     }
4180     unsigned PathLengthToMember =
4181         LV.Designator.Entries.size() - MemPtr.Path.size();
4182     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4183       const CXXRecordDecl *LVDecl = getAsBaseClass(
4184           LV.Designator.Entries[PathLengthToMember + I]);
4185       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4186       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4187         Info.FFDiag(RHS);
4188         return nullptr;
4189       }
4190     }
4191 
4192     // Truncate the lvalue to the appropriate derived class.
4193     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4194                             PathLengthToMember))
4195       return nullptr;
4196   } else if (!MemPtr.Path.empty()) {
4197     // Extend the LValue path with the member pointer's path.
4198     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4199                                   MemPtr.Path.size() + IncludeMember);
4200 
4201     // Walk down to the appropriate base class.
4202     if (const PointerType *PT = LVType->getAs<PointerType>())
4203       LVType = PT->getPointeeType();
4204     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4205     assert(RD && "member pointer access on non-class-type expression");
4206     // The first class in the path is that of the lvalue.
4207     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4208       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4209       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4210         return nullptr;
4211       RD = Base;
4212     }
4213     // Finally cast to the class containing the member.
4214     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4215                                 MemPtr.getContainingRecord()))
4216       return nullptr;
4217   }
4218 
4219   // Add the member. Note that we cannot build bound member functions here.
4220   if (IncludeMember) {
4221     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4222       if (!HandleLValueMember(Info, RHS, LV, FD))
4223         return nullptr;
4224     } else if (const IndirectFieldDecl *IFD =
4225                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4226       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4227         return nullptr;
4228     } else {
4229       llvm_unreachable("can't construct reference to bound member function");
4230     }
4231   }
4232 
4233   return MemPtr.getDecl();
4234 }
4235 
4236 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4237                                                   const BinaryOperator *BO,
4238                                                   LValue &LV,
4239                                                   bool IncludeMember = true) {
4240   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4241 
4242   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4243     if (Info.noteFailure()) {
4244       MemberPtr MemPtr;
4245       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4246     }
4247     return nullptr;
4248   }
4249 
4250   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4251                                    BO->getRHS(), IncludeMember);
4252 }
4253 
4254 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4255 /// the provided lvalue, which currently refers to the base object.
4256 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4257                                     LValue &Result) {
4258   SubobjectDesignator &D = Result.Designator;
4259   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4260     return false;
4261 
4262   QualType TargetQT = E->getType();
4263   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4264     TargetQT = PT->getPointeeType();
4265 
4266   // Check this cast lands within the final derived-to-base subobject path.
4267   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4268     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4269       << D.MostDerivedType << TargetQT;
4270     return false;
4271   }
4272 
4273   // Check the type of the final cast. We don't need to check the path,
4274   // since a cast can only be formed if the path is unique.
4275   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4276   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4277   const CXXRecordDecl *FinalType;
4278   if (NewEntriesSize == D.MostDerivedPathLength)
4279     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4280   else
4281     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4282   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4283     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4284       << D.MostDerivedType << TargetQT;
4285     return false;
4286   }
4287 
4288   // Truncate the lvalue to the appropriate derived class.
4289   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4290 }
4291 
4292 /// Get the value to use for a default-initialized object of type T.
4293 static APValue getDefaultInitValue(QualType T) {
4294   if (auto *RD = T->getAsCXXRecordDecl()) {
4295     if (RD->isUnion())
4296       return APValue((const FieldDecl*)nullptr);
4297 
4298     APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
4299                    std::distance(RD->field_begin(), RD->field_end()));
4300 
4301     unsigned Index = 0;
4302     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4303            End = RD->bases_end(); I != End; ++I, ++Index)
4304       Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
4305 
4306     for (const auto *I : RD->fields()) {
4307       if (I->isUnnamedBitfield())
4308         continue;
4309       Struct.getStructField(I->getFieldIndex()) =
4310           getDefaultInitValue(I->getType());
4311     }
4312     return Struct;
4313   }
4314 
4315   if (auto *AT =
4316           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4317     APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4318     if (Array.hasArrayFiller())
4319       Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
4320     return Array;
4321   }
4322 
4323   return APValue::IndeterminateValue();
4324 }
4325 
4326 namespace {
4327 enum EvalStmtResult {
4328   /// Evaluation failed.
4329   ESR_Failed,
4330   /// Hit a 'return' statement.
4331   ESR_Returned,
4332   /// Evaluation succeeded.
4333   ESR_Succeeded,
4334   /// Hit a 'continue' statement.
4335   ESR_Continue,
4336   /// Hit a 'break' statement.
4337   ESR_Break,
4338   /// Still scanning for 'case' or 'default' statement.
4339   ESR_CaseNotFound
4340 };
4341 }
4342 
4343 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4344   // We don't need to evaluate the initializer for a static local.
4345   if (!VD->hasLocalStorage())
4346     return true;
4347 
4348   LValue Result;
4349   APValue &Val =
4350       Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result);
4351 
4352   const Expr *InitE = VD->getInit();
4353   if (!InitE) {
4354     Val = getDefaultInitValue(VD->getType());
4355     return true;
4356   }
4357 
4358   if (InitE->isValueDependent())
4359     return false;
4360 
4361   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4362     // Wipe out any partially-computed value, to allow tracking that this
4363     // evaluation failed.
4364     Val = APValue();
4365     return false;
4366   }
4367 
4368   return true;
4369 }
4370 
4371 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4372   bool OK = true;
4373 
4374   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4375     OK &= EvaluateVarDecl(Info, VD);
4376 
4377   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4378     for (auto *BD : DD->bindings())
4379       if (auto *VD = BD->getHoldingVar())
4380         OK &= EvaluateDecl(Info, VD);
4381 
4382   return OK;
4383 }
4384 
4385 
4386 /// Evaluate a condition (either a variable declaration or an expression).
4387 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4388                          const Expr *Cond, bool &Result) {
4389   FullExpressionRAII Scope(Info);
4390   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4391     return false;
4392   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4393     return false;
4394   return Scope.destroy();
4395 }
4396 
4397 namespace {
4398 /// A location where the result (returned value) of evaluating a
4399 /// statement should be stored.
4400 struct StmtResult {
4401   /// The APValue that should be filled in with the returned value.
4402   APValue &Value;
4403   /// The location containing the result, if any (used to support RVO).
4404   const LValue *Slot;
4405 };
4406 
4407 struct TempVersionRAII {
4408   CallStackFrame &Frame;
4409 
4410   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4411     Frame.pushTempVersion();
4412   }
4413 
4414   ~TempVersionRAII() {
4415     Frame.popTempVersion();
4416   }
4417 };
4418 
4419 }
4420 
4421 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4422                                    const Stmt *S,
4423                                    const SwitchCase *SC = nullptr);
4424 
4425 /// Evaluate the body of a loop, and translate the result as appropriate.
4426 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4427                                        const Stmt *Body,
4428                                        const SwitchCase *Case = nullptr) {
4429   BlockScopeRAII Scope(Info);
4430 
4431   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4432   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4433     ESR = ESR_Failed;
4434 
4435   switch (ESR) {
4436   case ESR_Break:
4437     return ESR_Succeeded;
4438   case ESR_Succeeded:
4439   case ESR_Continue:
4440     return ESR_Continue;
4441   case ESR_Failed:
4442   case ESR_Returned:
4443   case ESR_CaseNotFound:
4444     return ESR;
4445   }
4446   llvm_unreachable("Invalid EvalStmtResult!");
4447 }
4448 
4449 /// Evaluate a switch statement.
4450 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4451                                      const SwitchStmt *SS) {
4452   BlockScopeRAII Scope(Info);
4453 
4454   // Evaluate the switch condition.
4455   APSInt Value;
4456   {
4457     if (const Stmt *Init = SS->getInit()) {
4458       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4459       if (ESR != ESR_Succeeded) {
4460         if (ESR != ESR_Failed && !Scope.destroy())
4461           ESR = ESR_Failed;
4462         return ESR;
4463       }
4464     }
4465 
4466     FullExpressionRAII CondScope(Info);
4467     if (SS->getConditionVariable() &&
4468         !EvaluateDecl(Info, SS->getConditionVariable()))
4469       return ESR_Failed;
4470     if (!EvaluateInteger(SS->getCond(), Value, Info))
4471       return ESR_Failed;
4472     if (!CondScope.destroy())
4473       return ESR_Failed;
4474   }
4475 
4476   // Find the switch case corresponding to the value of the condition.
4477   // FIXME: Cache this lookup.
4478   const SwitchCase *Found = nullptr;
4479   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4480        SC = SC->getNextSwitchCase()) {
4481     if (isa<DefaultStmt>(SC)) {
4482       Found = SC;
4483       continue;
4484     }
4485 
4486     const CaseStmt *CS = cast<CaseStmt>(SC);
4487     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4488     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4489                               : LHS;
4490     if (LHS <= Value && Value <= RHS) {
4491       Found = SC;
4492       break;
4493     }
4494   }
4495 
4496   if (!Found)
4497     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4498 
4499   // Search the switch body for the switch case and evaluate it from there.
4500   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4501   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4502     return ESR_Failed;
4503 
4504   switch (ESR) {
4505   case ESR_Break:
4506     return ESR_Succeeded;
4507   case ESR_Succeeded:
4508   case ESR_Continue:
4509   case ESR_Failed:
4510   case ESR_Returned:
4511     return ESR;
4512   case ESR_CaseNotFound:
4513     // This can only happen if the switch case is nested within a statement
4514     // expression. We have no intention of supporting that.
4515     Info.FFDiag(Found->getBeginLoc(),
4516                 diag::note_constexpr_stmt_expr_unsupported);
4517     return ESR_Failed;
4518   }
4519   llvm_unreachable("Invalid EvalStmtResult!");
4520 }
4521 
4522 // Evaluate a statement.
4523 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4524                                    const Stmt *S, const SwitchCase *Case) {
4525   if (!Info.nextStep(S))
4526     return ESR_Failed;
4527 
4528   // If we're hunting down a 'case' or 'default' label, recurse through
4529   // substatements until we hit the label.
4530   if (Case) {
4531     switch (S->getStmtClass()) {
4532     case Stmt::CompoundStmtClass:
4533       // FIXME: Precompute which substatement of a compound statement we
4534       // would jump to, and go straight there rather than performing a
4535       // linear scan each time.
4536     case Stmt::LabelStmtClass:
4537     case Stmt::AttributedStmtClass:
4538     case Stmt::DoStmtClass:
4539       break;
4540 
4541     case Stmt::CaseStmtClass:
4542     case Stmt::DefaultStmtClass:
4543       if (Case == S)
4544         Case = nullptr;
4545       break;
4546 
4547     case Stmt::IfStmtClass: {
4548       // FIXME: Precompute which side of an 'if' we would jump to, and go
4549       // straight there rather than scanning both sides.
4550       const IfStmt *IS = cast<IfStmt>(S);
4551 
4552       // Wrap the evaluation in a block scope, in case it's a DeclStmt
4553       // preceded by our switch label.
4554       BlockScopeRAII Scope(Info);
4555 
4556       // Step into the init statement in case it brings an (uninitialized)
4557       // variable into scope.
4558       if (const Stmt *Init = IS->getInit()) {
4559         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4560         if (ESR != ESR_CaseNotFound) {
4561           assert(ESR != ESR_Succeeded);
4562           return ESR;
4563         }
4564       }
4565 
4566       // Condition variable must be initialized if it exists.
4567       // FIXME: We can skip evaluating the body if there's a condition
4568       // variable, as there can't be any case labels within it.
4569       // (The same is true for 'for' statements.)
4570 
4571       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4572       if (ESR == ESR_Failed)
4573         return ESR;
4574       if (ESR != ESR_CaseNotFound)
4575         return Scope.destroy() ? ESR : ESR_Failed;
4576       if (!IS->getElse())
4577         return ESR_CaseNotFound;
4578 
4579       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
4580       if (ESR == ESR_Failed)
4581         return ESR;
4582       if (ESR != ESR_CaseNotFound)
4583         return Scope.destroy() ? ESR : ESR_Failed;
4584       return ESR_CaseNotFound;
4585     }
4586 
4587     case Stmt::WhileStmtClass: {
4588       EvalStmtResult ESR =
4589           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4590       if (ESR != ESR_Continue)
4591         return ESR;
4592       break;
4593     }
4594 
4595     case Stmt::ForStmtClass: {
4596       const ForStmt *FS = cast<ForStmt>(S);
4597       BlockScopeRAII Scope(Info);
4598 
4599       // Step into the init statement in case it brings an (uninitialized)
4600       // variable into scope.
4601       if (const Stmt *Init = FS->getInit()) {
4602         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4603         if (ESR != ESR_CaseNotFound) {
4604           assert(ESR != ESR_Succeeded);
4605           return ESR;
4606         }
4607       }
4608 
4609       EvalStmtResult ESR =
4610           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4611       if (ESR != ESR_Continue)
4612         return ESR;
4613       if (FS->getInc()) {
4614         FullExpressionRAII IncScope(Info);
4615         if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
4616           return ESR_Failed;
4617       }
4618       break;
4619     }
4620 
4621     case Stmt::DeclStmtClass: {
4622       // Start the lifetime of any uninitialized variables we encounter. They
4623       // might be used by the selected branch of the switch.
4624       const DeclStmt *DS = cast<DeclStmt>(S);
4625       for (const auto *D : DS->decls()) {
4626         if (const auto *VD = dyn_cast<VarDecl>(D)) {
4627           if (VD->hasLocalStorage() && !VD->getInit())
4628             if (!EvaluateVarDecl(Info, VD))
4629               return ESR_Failed;
4630           // FIXME: If the variable has initialization that can't be jumped
4631           // over, bail out of any immediately-surrounding compound-statement
4632           // too. There can't be any case labels here.
4633         }
4634       }
4635       return ESR_CaseNotFound;
4636     }
4637 
4638     default:
4639       return ESR_CaseNotFound;
4640     }
4641   }
4642 
4643   switch (S->getStmtClass()) {
4644   default:
4645     if (const Expr *E = dyn_cast<Expr>(S)) {
4646       // Don't bother evaluating beyond an expression-statement which couldn't
4647       // be evaluated.
4648       // FIXME: Do we need the FullExpressionRAII object here?
4649       // VisitExprWithCleanups should create one when necessary.
4650       FullExpressionRAII Scope(Info);
4651       if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
4652         return ESR_Failed;
4653       return ESR_Succeeded;
4654     }
4655 
4656     Info.FFDiag(S->getBeginLoc());
4657     return ESR_Failed;
4658 
4659   case Stmt::NullStmtClass:
4660     return ESR_Succeeded;
4661 
4662   case Stmt::DeclStmtClass: {
4663     const DeclStmt *DS = cast<DeclStmt>(S);
4664     for (const auto *D : DS->decls()) {
4665       // Each declaration initialization is its own full-expression.
4666       FullExpressionRAII Scope(Info);
4667       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
4668         return ESR_Failed;
4669       if (!Scope.destroy())
4670         return ESR_Failed;
4671     }
4672     return ESR_Succeeded;
4673   }
4674 
4675   case Stmt::ReturnStmtClass: {
4676     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
4677     FullExpressionRAII Scope(Info);
4678     if (RetExpr &&
4679         !(Result.Slot
4680               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4681               : Evaluate(Result.Value, Info, RetExpr)))
4682       return ESR_Failed;
4683     return Scope.destroy() ? ESR_Returned : ESR_Failed;
4684   }
4685 
4686   case Stmt::CompoundStmtClass: {
4687     BlockScopeRAII Scope(Info);
4688 
4689     const CompoundStmt *CS = cast<CompoundStmt>(S);
4690     for (const auto *BI : CS->body()) {
4691       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
4692       if (ESR == ESR_Succeeded)
4693         Case = nullptr;
4694       else if (ESR != ESR_CaseNotFound) {
4695         if (ESR != ESR_Failed && !Scope.destroy())
4696           return ESR_Failed;
4697         return ESR;
4698       }
4699     }
4700     if (Case)
4701       return ESR_CaseNotFound;
4702     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4703   }
4704 
4705   case Stmt::IfStmtClass: {
4706     const IfStmt *IS = cast<IfStmt>(S);
4707 
4708     // Evaluate the condition, as either a var decl or as an expression.
4709     BlockScopeRAII Scope(Info);
4710     if (const Stmt *Init = IS->getInit()) {
4711       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4712       if (ESR != ESR_Succeeded) {
4713         if (ESR != ESR_Failed && !Scope.destroy())
4714           return ESR_Failed;
4715         return ESR;
4716       }
4717     }
4718     bool Cond;
4719     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4720       return ESR_Failed;
4721 
4722     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4723       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4724       if (ESR != ESR_Succeeded) {
4725         if (ESR != ESR_Failed && !Scope.destroy())
4726           return ESR_Failed;
4727         return ESR;
4728       }
4729     }
4730     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4731   }
4732 
4733   case Stmt::WhileStmtClass: {
4734     const WhileStmt *WS = cast<WhileStmt>(S);
4735     while (true) {
4736       BlockScopeRAII Scope(Info);
4737       bool Continue;
4738       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4739                         Continue))
4740         return ESR_Failed;
4741       if (!Continue)
4742         break;
4743 
4744       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4745       if (ESR != ESR_Continue) {
4746         if (ESR != ESR_Failed && !Scope.destroy())
4747           return ESR_Failed;
4748         return ESR;
4749       }
4750       if (!Scope.destroy())
4751         return ESR_Failed;
4752     }
4753     return ESR_Succeeded;
4754   }
4755 
4756   case Stmt::DoStmtClass: {
4757     const DoStmt *DS = cast<DoStmt>(S);
4758     bool Continue;
4759     do {
4760       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4761       if (ESR != ESR_Continue)
4762         return ESR;
4763       Case = nullptr;
4764 
4765       FullExpressionRAII CondScope(Info);
4766       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
4767           !CondScope.destroy())
4768         return ESR_Failed;
4769     } while (Continue);
4770     return ESR_Succeeded;
4771   }
4772 
4773   case Stmt::ForStmtClass: {
4774     const ForStmt *FS = cast<ForStmt>(S);
4775     BlockScopeRAII ForScope(Info);
4776     if (FS->getInit()) {
4777       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4778       if (ESR != ESR_Succeeded) {
4779         if (ESR != ESR_Failed && !ForScope.destroy())
4780           return ESR_Failed;
4781         return ESR;
4782       }
4783     }
4784     while (true) {
4785       BlockScopeRAII IterScope(Info);
4786       bool Continue = true;
4787       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4788                                          FS->getCond(), Continue))
4789         return ESR_Failed;
4790       if (!Continue)
4791         break;
4792 
4793       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4794       if (ESR != ESR_Continue) {
4795         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
4796           return ESR_Failed;
4797         return ESR;
4798       }
4799 
4800       if (FS->getInc()) {
4801         FullExpressionRAII IncScope(Info);
4802         if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
4803           return ESR_Failed;
4804       }
4805 
4806       if (!IterScope.destroy())
4807         return ESR_Failed;
4808     }
4809     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
4810   }
4811 
4812   case Stmt::CXXForRangeStmtClass: {
4813     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4814     BlockScopeRAII Scope(Info);
4815 
4816     // Evaluate the init-statement if present.
4817     if (FS->getInit()) {
4818       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4819       if (ESR != ESR_Succeeded) {
4820         if (ESR != ESR_Failed && !Scope.destroy())
4821           return ESR_Failed;
4822         return ESR;
4823       }
4824     }
4825 
4826     // Initialize the __range variable.
4827     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4828     if (ESR != ESR_Succeeded) {
4829       if (ESR != ESR_Failed && !Scope.destroy())
4830         return ESR_Failed;
4831       return ESR;
4832     }
4833 
4834     // Create the __begin and __end iterators.
4835     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4836     if (ESR != ESR_Succeeded) {
4837       if (ESR != ESR_Failed && !Scope.destroy())
4838         return ESR_Failed;
4839       return ESR;
4840     }
4841     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4842     if (ESR != ESR_Succeeded) {
4843       if (ESR != ESR_Failed && !Scope.destroy())
4844         return ESR_Failed;
4845       return ESR;
4846     }
4847 
4848     while (true) {
4849       // Condition: __begin != __end.
4850       {
4851         bool Continue = true;
4852         FullExpressionRAII CondExpr(Info);
4853         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4854           return ESR_Failed;
4855         if (!Continue)
4856           break;
4857       }
4858 
4859       // User's variable declaration, initialized by *__begin.
4860       BlockScopeRAII InnerScope(Info);
4861       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4862       if (ESR != ESR_Succeeded) {
4863         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
4864           return ESR_Failed;
4865         return ESR;
4866       }
4867 
4868       // Loop body.
4869       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4870       if (ESR != ESR_Continue) {
4871         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
4872           return ESR_Failed;
4873         return ESR;
4874       }
4875 
4876       // Increment: ++__begin
4877       if (!EvaluateIgnoredValue(Info, FS->getInc()))
4878         return ESR_Failed;
4879 
4880       if (!InnerScope.destroy())
4881         return ESR_Failed;
4882     }
4883 
4884     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4885   }
4886 
4887   case Stmt::SwitchStmtClass:
4888     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4889 
4890   case Stmt::ContinueStmtClass:
4891     return ESR_Continue;
4892 
4893   case Stmt::BreakStmtClass:
4894     return ESR_Break;
4895 
4896   case Stmt::LabelStmtClass:
4897     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4898 
4899   case Stmt::AttributedStmtClass:
4900     // As a general principle, C++11 attributes can be ignored without
4901     // any semantic impact.
4902     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4903                         Case);
4904 
4905   case Stmt::CaseStmtClass:
4906   case Stmt::DefaultStmtClass:
4907     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4908   case Stmt::CXXTryStmtClass:
4909     // Evaluate try blocks by evaluating all sub statements.
4910     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
4911   }
4912 }
4913 
4914 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4915 /// default constructor. If so, we'll fold it whether or not it's marked as
4916 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4917 /// so we need special handling.
4918 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4919                                            const CXXConstructorDecl *CD,
4920                                            bool IsValueInitialization) {
4921   if (!CD->isTrivial() || !CD->isDefaultConstructor())
4922     return false;
4923 
4924   // Value-initialization does not call a trivial default constructor, so such a
4925   // call is a core constant expression whether or not the constructor is
4926   // constexpr.
4927   if (!CD->isConstexpr() && !IsValueInitialization) {
4928     if (Info.getLangOpts().CPlusPlus11) {
4929       // FIXME: If DiagDecl is an implicitly-declared special member function,
4930       // we should be much more explicit about why it's not constexpr.
4931       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4932         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4933       Info.Note(CD->getLocation(), diag::note_declared_at);
4934     } else {
4935       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4936     }
4937   }
4938   return true;
4939 }
4940 
4941 /// CheckConstexprFunction - Check that a function can be called in a constant
4942 /// expression.
4943 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4944                                    const FunctionDecl *Declaration,
4945                                    const FunctionDecl *Definition,
4946                                    const Stmt *Body) {
4947   // Potential constant expressions can contain calls to declared, but not yet
4948   // defined, constexpr functions.
4949   if (Info.checkingPotentialConstantExpression() && !Definition &&
4950       Declaration->isConstexpr())
4951     return false;
4952 
4953   // Bail out if the function declaration itself is invalid.  We will
4954   // have produced a relevant diagnostic while parsing it, so just
4955   // note the problematic sub-expression.
4956   if (Declaration->isInvalidDecl()) {
4957     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4958     return false;
4959   }
4960 
4961   // DR1872: An instantiated virtual constexpr function can't be called in a
4962   // constant expression (prior to C++20). We can still constant-fold such a
4963   // call.
4964   if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
4965       cast<CXXMethodDecl>(Declaration)->isVirtual())
4966     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
4967 
4968   if (Definition && Definition->isInvalidDecl()) {
4969     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4970     return false;
4971   }
4972 
4973   // Can we evaluate this function call?
4974   if (Definition && Definition->isConstexpr() && Body)
4975     return true;
4976 
4977   if (Info.getLangOpts().CPlusPlus11) {
4978     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4979 
4980     // If this function is not constexpr because it is an inherited
4981     // non-constexpr constructor, diagnose that directly.
4982     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4983     if (CD && CD->isInheritingConstructor()) {
4984       auto *Inherited = CD->getInheritedConstructor().getConstructor();
4985       if (!Inherited->isConstexpr())
4986         DiagDecl = CD = Inherited;
4987     }
4988 
4989     // FIXME: If DiagDecl is an implicitly-declared special member function
4990     // or an inheriting constructor, we should be much more explicit about why
4991     // it's not constexpr.
4992     if (CD && CD->isInheritingConstructor())
4993       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4994         << CD->getInheritedConstructor().getConstructor()->getParent();
4995     else
4996       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4997         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4998     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4999   } else {
5000     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5001   }
5002   return false;
5003 }
5004 
5005 namespace {
5006 struct CheckDynamicTypeHandler {
5007   AccessKinds AccessKind;
5008   typedef bool result_type;
5009   bool failed() { return false; }
5010   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5011   bool found(APSInt &Value, QualType SubobjType) { return true; }
5012   bool found(APFloat &Value, QualType SubobjType) { return true; }
5013 };
5014 } // end anonymous namespace
5015 
5016 /// Check that we can access the notional vptr of an object / determine its
5017 /// dynamic type.
5018 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5019                              AccessKinds AK, bool Polymorphic) {
5020   if (This.Designator.Invalid)
5021     return false;
5022 
5023   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5024 
5025   if (!Obj)
5026     return false;
5027 
5028   if (!Obj.Value) {
5029     // The object is not usable in constant expressions, so we can't inspect
5030     // its value to see if it's in-lifetime or what the active union members
5031     // are. We can still check for a one-past-the-end lvalue.
5032     if (This.Designator.isOnePastTheEnd() ||
5033         This.Designator.isMostDerivedAnUnsizedArray()) {
5034       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5035                          ? diag::note_constexpr_access_past_end
5036                          : diag::note_constexpr_access_unsized_array)
5037           << AK;
5038       return false;
5039     } else if (Polymorphic) {
5040       // Conservatively refuse to perform a polymorphic operation if we would
5041       // not be able to read a notional 'vptr' value.
5042       APValue Val;
5043       This.moveInto(Val);
5044       QualType StarThisType =
5045           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5046       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5047           << AK << Val.getAsString(Info.Ctx, StarThisType);
5048       return false;
5049     }
5050     return true;
5051   }
5052 
5053   CheckDynamicTypeHandler Handler{AK};
5054   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5055 }
5056 
5057 /// Check that the pointee of the 'this' pointer in a member function call is
5058 /// either within its lifetime or in its period of construction or destruction.
5059 static bool
5060 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5061                                      const LValue &This,
5062                                      const CXXMethodDecl *NamedMember) {
5063   return checkDynamicType(
5064       Info, E, This,
5065       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5066 }
5067 
5068 struct DynamicType {
5069   /// The dynamic class type of the object.
5070   const CXXRecordDecl *Type;
5071   /// The corresponding path length in the lvalue.
5072   unsigned PathLength;
5073 };
5074 
5075 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5076                                              unsigned PathLength) {
5077   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5078       Designator.Entries.size() && "invalid path length");
5079   return (PathLength == Designator.MostDerivedPathLength)
5080              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5081              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5082 }
5083 
5084 /// Determine the dynamic type of an object.
5085 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5086                                                 LValue &This, AccessKinds AK) {
5087   // If we don't have an lvalue denoting an object of class type, there is no
5088   // meaningful dynamic type. (We consider objects of non-class type to have no
5089   // dynamic type.)
5090   if (!checkDynamicType(Info, E, This, AK, true))
5091     return None;
5092 
5093   // Refuse to compute a dynamic type in the presence of virtual bases. This
5094   // shouldn't happen other than in constant-folding situations, since literal
5095   // types can't have virtual bases.
5096   //
5097   // Note that consumers of DynamicType assume that the type has no virtual
5098   // bases, and will need modifications if this restriction is relaxed.
5099   const CXXRecordDecl *Class =
5100       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5101   if (!Class || Class->getNumVBases()) {
5102     Info.FFDiag(E);
5103     return None;
5104   }
5105 
5106   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5107   // binary search here instead. But the overwhelmingly common case is that
5108   // we're not in the middle of a constructor, so it probably doesn't matter
5109   // in practice.
5110   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5111   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5112        PathLength <= Path.size(); ++PathLength) {
5113     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5114                                       Path.slice(0, PathLength))) {
5115     case ConstructionPhase::Bases:
5116     case ConstructionPhase::DestroyingBases:
5117       // We're constructing or destroying a base class. This is not the dynamic
5118       // type.
5119       break;
5120 
5121     case ConstructionPhase::None:
5122     case ConstructionPhase::AfterBases:
5123     case ConstructionPhase::Destroying:
5124       // We've finished constructing the base classes and not yet started
5125       // destroying them again, so this is the dynamic type.
5126       return DynamicType{getBaseClassType(This.Designator, PathLength),
5127                          PathLength};
5128     }
5129   }
5130 
5131   // CWG issue 1517: we're constructing a base class of the object described by
5132   // 'This', so that object has not yet begun its period of construction and
5133   // any polymorphic operation on it results in undefined behavior.
5134   Info.FFDiag(E);
5135   return None;
5136 }
5137 
5138 /// Perform virtual dispatch.
5139 static const CXXMethodDecl *HandleVirtualDispatch(
5140     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5141     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5142   Optional<DynamicType> DynType = ComputeDynamicType(
5143       Info, E, This,
5144       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5145   if (!DynType)
5146     return nullptr;
5147 
5148   // Find the final overrider. It must be declared in one of the classes on the
5149   // path from the dynamic type to the static type.
5150   // FIXME: If we ever allow literal types to have virtual base classes, that
5151   // won't be true.
5152   const CXXMethodDecl *Callee = Found;
5153   unsigned PathLength = DynType->PathLength;
5154   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5155     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5156     const CXXMethodDecl *Overrider =
5157         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5158     if (Overrider) {
5159       Callee = Overrider;
5160       break;
5161     }
5162   }
5163 
5164   // C++2a [class.abstract]p6:
5165   //   the effect of making a virtual call to a pure virtual function [...] is
5166   //   undefined
5167   if (Callee->isPure()) {
5168     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5169     Info.Note(Callee->getLocation(), diag::note_declared_at);
5170     return nullptr;
5171   }
5172 
5173   // If necessary, walk the rest of the path to determine the sequence of
5174   // covariant adjustment steps to apply.
5175   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5176                                        Found->getReturnType())) {
5177     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5178     for (unsigned CovariantPathLength = PathLength + 1;
5179          CovariantPathLength != This.Designator.Entries.size();
5180          ++CovariantPathLength) {
5181       const CXXRecordDecl *NextClass =
5182           getBaseClassType(This.Designator, CovariantPathLength);
5183       const CXXMethodDecl *Next =
5184           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5185       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5186                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5187         CovariantAdjustmentPath.push_back(Next->getReturnType());
5188     }
5189     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5190                                          CovariantAdjustmentPath.back()))
5191       CovariantAdjustmentPath.push_back(Found->getReturnType());
5192   }
5193 
5194   // Perform 'this' adjustment.
5195   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5196     return nullptr;
5197 
5198   return Callee;
5199 }
5200 
5201 /// Perform the adjustment from a value returned by a virtual function to
5202 /// a value of the statically expected type, which may be a pointer or
5203 /// reference to a base class of the returned type.
5204 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5205                                             APValue &Result,
5206                                             ArrayRef<QualType> Path) {
5207   assert(Result.isLValue() &&
5208          "unexpected kind of APValue for covariant return");
5209   if (Result.isNullPointer())
5210     return true;
5211 
5212   LValue LVal;
5213   LVal.setFrom(Info.Ctx, Result);
5214 
5215   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5216   for (unsigned I = 1; I != Path.size(); ++I) {
5217     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5218     assert(OldClass && NewClass && "unexpected kind of covariant return");
5219     if (OldClass != NewClass &&
5220         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5221       return false;
5222     OldClass = NewClass;
5223   }
5224 
5225   LVal.moveInto(Result);
5226   return true;
5227 }
5228 
5229 /// Determine whether \p Base, which is known to be a direct base class of
5230 /// \p Derived, is a public base class.
5231 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5232                               const CXXRecordDecl *Base) {
5233   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5234     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5235     if (BaseClass && declaresSameEntity(BaseClass, Base))
5236       return BaseSpec.getAccessSpecifier() == AS_public;
5237   }
5238   llvm_unreachable("Base is not a direct base of Derived");
5239 }
5240 
5241 /// Apply the given dynamic cast operation on the provided lvalue.
5242 ///
5243 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5244 /// to find a suitable target subobject.
5245 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5246                               LValue &Ptr) {
5247   // We can't do anything with a non-symbolic pointer value.
5248   SubobjectDesignator &D = Ptr.Designator;
5249   if (D.Invalid)
5250     return false;
5251 
5252   // C++ [expr.dynamic.cast]p6:
5253   //   If v is a null pointer value, the result is a null pointer value.
5254   if (Ptr.isNullPointer() && !E->isGLValue())
5255     return true;
5256 
5257   // For all the other cases, we need the pointer to point to an object within
5258   // its lifetime / period of construction / destruction, and we need to know
5259   // its dynamic type.
5260   Optional<DynamicType> DynType =
5261       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5262   if (!DynType)
5263     return false;
5264 
5265   // C++ [expr.dynamic.cast]p7:
5266   //   If T is "pointer to cv void", then the result is a pointer to the most
5267   //   derived object
5268   if (E->getType()->isVoidPointerType())
5269     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5270 
5271   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5272   assert(C && "dynamic_cast target is not void pointer nor class");
5273   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5274 
5275   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5276     // C++ [expr.dynamic.cast]p9:
5277     if (!E->isGLValue()) {
5278       //   The value of a failed cast to pointer type is the null pointer value
5279       //   of the required result type.
5280       Ptr.setNull(Info.Ctx, E->getType());
5281       return true;
5282     }
5283 
5284     //   A failed cast to reference type throws [...] std::bad_cast.
5285     unsigned DiagKind;
5286     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5287                    DynType->Type->isDerivedFrom(C)))
5288       DiagKind = 0;
5289     else if (!Paths || Paths->begin() == Paths->end())
5290       DiagKind = 1;
5291     else if (Paths->isAmbiguous(CQT))
5292       DiagKind = 2;
5293     else {
5294       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5295       DiagKind = 3;
5296     }
5297     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5298         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5299         << Info.Ctx.getRecordType(DynType->Type)
5300         << E->getType().getUnqualifiedType();
5301     return false;
5302   };
5303 
5304   // Runtime check, phase 1:
5305   //   Walk from the base subobject towards the derived object looking for the
5306   //   target type.
5307   for (int PathLength = Ptr.Designator.Entries.size();
5308        PathLength >= (int)DynType->PathLength; --PathLength) {
5309     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5310     if (declaresSameEntity(Class, C))
5311       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5312     // We can only walk across public inheritance edges.
5313     if (PathLength > (int)DynType->PathLength &&
5314         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5315                            Class))
5316       return RuntimeCheckFailed(nullptr);
5317   }
5318 
5319   // Runtime check, phase 2:
5320   //   Search the dynamic type for an unambiguous public base of type C.
5321   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5322                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5323   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5324       Paths.front().Access == AS_public) {
5325     // Downcast to the dynamic type...
5326     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5327       return false;
5328     // ... then upcast to the chosen base class subobject.
5329     for (CXXBasePathElement &Elem : Paths.front())
5330       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5331         return false;
5332     return true;
5333   }
5334 
5335   // Otherwise, the runtime check fails.
5336   return RuntimeCheckFailed(&Paths);
5337 }
5338 
5339 namespace {
5340 struct StartLifetimeOfUnionMemberHandler {
5341   const FieldDecl *Field;
5342 
5343   static const AccessKinds AccessKind = AK_Assign;
5344 
5345   typedef bool result_type;
5346   bool failed() { return false; }
5347   bool found(APValue &Subobj, QualType SubobjType) {
5348     // We are supposed to perform no initialization but begin the lifetime of
5349     // the object. We interpret that as meaning to do what default
5350     // initialization of the object would do if all constructors involved were
5351     // trivial:
5352     //  * All base, non-variant member, and array element subobjects' lifetimes
5353     //    begin
5354     //  * No variant members' lifetimes begin
5355     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5356     assert(SubobjType->isUnionType());
5357     if (!declaresSameEntity(Subobj.getUnionField(), Field) ||
5358         !Subobj.getUnionValue().hasValue())
5359       Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
5360     return true;
5361   }
5362   bool found(APSInt &Value, QualType SubobjType) {
5363     llvm_unreachable("wrong value kind for union object");
5364   }
5365   bool found(APFloat &Value, QualType SubobjType) {
5366     llvm_unreachable("wrong value kind for union object");
5367   }
5368 };
5369 } // end anonymous namespace
5370 
5371 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5372 
5373 /// Handle a builtin simple-assignment or a call to a trivial assignment
5374 /// operator whose left-hand side might involve a union member access. If it
5375 /// does, implicitly start the lifetime of any accessed union elements per
5376 /// C++20 [class.union]5.
5377 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5378                                           const LValue &LHS) {
5379   if (LHS.InvalidBase || LHS.Designator.Invalid)
5380     return false;
5381 
5382   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5383   // C++ [class.union]p5:
5384   //   define the set S(E) of subexpressions of E as follows:
5385   unsigned PathLength = LHS.Designator.Entries.size();
5386   for (const Expr *E = LHSExpr; E != nullptr;) {
5387     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5388     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5389       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5390       // Note that we can't implicitly start the lifetime of a reference,
5391       // so we don't need to proceed any further if we reach one.
5392       if (!FD || FD->getType()->isReferenceType())
5393         break;
5394 
5395       //    ... and also contains A.B if B names a union member ...
5396       if (FD->getParent()->isUnion()) {
5397         //    ... of a non-class, non-array type, or of a class type with a
5398         //    trivial default constructor that is not deleted, or an array of
5399         //    such types.
5400         auto *RD =
5401             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5402         if (!RD || RD->hasTrivialDefaultConstructor())
5403           UnionPathLengths.push_back({PathLength - 1, FD});
5404       }
5405 
5406       E = ME->getBase();
5407       --PathLength;
5408       assert(declaresSameEntity(FD,
5409                                 LHS.Designator.Entries[PathLength]
5410                                     .getAsBaseOrMember().getPointer()));
5411 
5412       //   -- If E is of the form A[B] and is interpreted as a built-in array
5413       //      subscripting operator, S(E) is [S(the array operand, if any)].
5414     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5415       // Step over an ArrayToPointerDecay implicit cast.
5416       auto *Base = ASE->getBase()->IgnoreImplicit();
5417       if (!Base->getType()->isArrayType())
5418         break;
5419 
5420       E = Base;
5421       --PathLength;
5422 
5423     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5424       // Step over a derived-to-base conversion.
5425       E = ICE->getSubExpr();
5426       if (ICE->getCastKind() == CK_NoOp)
5427         continue;
5428       if (ICE->getCastKind() != CK_DerivedToBase &&
5429           ICE->getCastKind() != CK_UncheckedDerivedToBase)
5430         break;
5431       // Walk path backwards as we walk up from the base to the derived class.
5432       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5433         --PathLength;
5434         (void)Elt;
5435         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5436                                   LHS.Designator.Entries[PathLength]
5437                                       .getAsBaseOrMember().getPointer()));
5438       }
5439 
5440     //   -- Otherwise, S(E) is empty.
5441     } else {
5442       break;
5443     }
5444   }
5445 
5446   // Common case: no unions' lifetimes are started.
5447   if (UnionPathLengths.empty())
5448     return true;
5449 
5450   //   if modification of X [would access an inactive union member], an object
5451   //   of the type of X is implicitly created
5452   CompleteObject Obj =
5453       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5454   if (!Obj)
5455     return false;
5456   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5457            llvm::reverse(UnionPathLengths)) {
5458     // Form a designator for the union object.
5459     SubobjectDesignator D = LHS.Designator;
5460     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5461 
5462     StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
5463     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5464       return false;
5465   }
5466 
5467   return true;
5468 }
5469 
5470 namespace {
5471 typedef SmallVector<APValue, 8> ArgVector;
5472 }
5473 
5474 /// EvaluateArgs - Evaluate the arguments to a function call.
5475 static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
5476                          EvalInfo &Info, const FunctionDecl *Callee) {
5477   bool Success = true;
5478   llvm::SmallBitVector ForbiddenNullArgs;
5479   if (Callee->hasAttr<NonNullAttr>()) {
5480     ForbiddenNullArgs.resize(Args.size());
5481     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5482       if (!Attr->args_size()) {
5483         ForbiddenNullArgs.set();
5484         break;
5485       } else
5486         for (auto Idx : Attr->args()) {
5487           unsigned ASTIdx = Idx.getASTIndex();
5488           if (ASTIdx >= Args.size())
5489             continue;
5490           ForbiddenNullArgs[ASTIdx] = 1;
5491         }
5492     }
5493   }
5494   // FIXME: This is the wrong evaluation order for an assignment operator
5495   // called via operator syntax.
5496   for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
5497     if (!Evaluate(ArgValues[Idx], Info, Args[Idx])) {
5498       // If we're checking for a potential constant expression, evaluate all
5499       // initializers even if some of them fail.
5500       if (!Info.noteFailure())
5501         return false;
5502       Success = false;
5503     } else if (!ForbiddenNullArgs.empty() &&
5504                ForbiddenNullArgs[Idx] &&
5505                ArgValues[Idx].isLValue() &&
5506                ArgValues[Idx].isNullPointer()) {
5507       Info.CCEDiag(Args[Idx], diag::note_non_null_attribute_failed);
5508       if (!Info.noteFailure())
5509         return false;
5510       Success = false;
5511     }
5512   }
5513   return Success;
5514 }
5515 
5516 /// Evaluate a function call.
5517 static bool HandleFunctionCall(SourceLocation CallLoc,
5518                                const FunctionDecl *Callee, const LValue *This,
5519                                ArrayRef<const Expr*> Args, const Stmt *Body,
5520                                EvalInfo &Info, APValue &Result,
5521                                const LValue *ResultSlot) {
5522   ArgVector ArgValues(Args.size());
5523   if (!EvaluateArgs(Args, ArgValues, Info, Callee))
5524     return false;
5525 
5526   if (!Info.CheckCallLimit(CallLoc))
5527     return false;
5528 
5529   CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
5530 
5531   // For a trivial copy or move assignment, perform an APValue copy. This is
5532   // essential for unions, where the operations performed by the assignment
5533   // operator cannot be represented as statements.
5534   //
5535   // Skip this for non-union classes with no fields; in that case, the defaulted
5536   // copy/move does not actually read the object.
5537   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
5538   if (MD && MD->isDefaulted() &&
5539       (MD->getParent()->isUnion() ||
5540        (MD->isTrivial() &&
5541         isReadByLvalueToRvalueConversion(MD->getParent())))) {
5542     assert(This &&
5543            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
5544     LValue RHS;
5545     RHS.setFrom(Info.Ctx, ArgValues[0]);
5546     APValue RHSValue;
5547     if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS,
5548                                         RHSValue, MD->getParent()->isUnion()))
5549       return false;
5550     if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
5551         !HandleUnionActiveMemberChange(Info, Args[0], *This))
5552       return false;
5553     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
5554                           RHSValue))
5555       return false;
5556     This->moveInto(Result);
5557     return true;
5558   } else if (MD && isLambdaCallOperator(MD)) {
5559     // We're in a lambda; determine the lambda capture field maps unless we're
5560     // just constexpr checking a lambda's call operator. constexpr checking is
5561     // done before the captures have been added to the closure object (unless
5562     // we're inferring constexpr-ness), so we don't have access to them in this
5563     // case. But since we don't need the captures to constexpr check, we can
5564     // just ignore them.
5565     if (!Info.checkingPotentialConstantExpression())
5566       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5567                                         Frame.LambdaThisCaptureField);
5568   }
5569 
5570   StmtResult Ret = {Result, ResultSlot};
5571   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
5572   if (ESR == ESR_Succeeded) {
5573     if (Callee->getReturnType()->isVoidType())
5574       return true;
5575     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
5576   }
5577   return ESR == ESR_Returned;
5578 }
5579 
5580 /// Evaluate a constructor call.
5581 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5582                                   APValue *ArgValues,
5583                                   const CXXConstructorDecl *Definition,
5584                                   EvalInfo &Info, APValue &Result) {
5585   SourceLocation CallLoc = E->getExprLoc();
5586   if (!Info.CheckCallLimit(CallLoc))
5587     return false;
5588 
5589   const CXXRecordDecl *RD = Definition->getParent();
5590   if (RD->getNumVBases()) {
5591     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5592     return false;
5593   }
5594 
5595   EvalInfo::EvaluatingConstructorRAII EvalObj(
5596       Info,
5597       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5598       RD->getNumBases());
5599   CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
5600 
5601   // FIXME: Creating an APValue just to hold a nonexistent return value is
5602   // wasteful.
5603   APValue RetVal;
5604   StmtResult Ret = {RetVal, nullptr};
5605 
5606   // If it's a delegating constructor, delegate.
5607   if (Definition->isDelegatingConstructor()) {
5608     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
5609     {
5610       FullExpressionRAII InitScope(Info);
5611       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
5612           !InitScope.destroy())
5613         return false;
5614     }
5615     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5616   }
5617 
5618   // For a trivial copy or move constructor, perform an APValue copy. This is
5619   // essential for unions (or classes with anonymous union members), where the
5620   // operations performed by the constructor cannot be represented by
5621   // ctor-initializers.
5622   //
5623   // Skip this for empty non-union classes; we should not perform an
5624   // lvalue-to-rvalue conversion on them because their copy constructor does not
5625   // actually read them.
5626   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
5627       (Definition->getParent()->isUnion() ||
5628        (Definition->isTrivial() &&
5629         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
5630     LValue RHS;
5631     RHS.setFrom(Info.Ctx, ArgValues[0]);
5632     return handleLValueToRValueConversion(
5633         Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
5634         RHS, Result, Definition->getParent()->isUnion());
5635   }
5636 
5637   // Reserve space for the struct members.
5638   if (!Result.hasValue()) {
5639     if (!RD->isUnion())
5640       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5641                        std::distance(RD->field_begin(), RD->field_end()));
5642     else
5643       // A union starts with no active member.
5644       Result = APValue((const FieldDecl*)nullptr);
5645   }
5646 
5647   if (RD->isInvalidDecl()) return false;
5648   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5649 
5650   // A scope for temporaries lifetime-extended by reference members.
5651   BlockScopeRAII LifetimeExtendedScope(Info);
5652 
5653   bool Success = true;
5654   unsigned BasesSeen = 0;
5655 #ifndef NDEBUG
5656   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5657 #endif
5658   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
5659   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
5660     // We might be initializing the same field again if this is an indirect
5661     // field initialization.
5662     if (FieldIt == RD->field_end() ||
5663         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
5664       assert(Indirect && "fields out of order?");
5665       return;
5666     }
5667 
5668     // Default-initialize any fields with no explicit initializer.
5669     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
5670       assert(FieldIt != RD->field_end() && "missing field?");
5671       if (!FieldIt->isUnnamedBitfield())
5672         Result.getStructField(FieldIt->getFieldIndex()) =
5673             getDefaultInitValue(FieldIt->getType());
5674     }
5675     ++FieldIt;
5676   };
5677   for (const auto *I : Definition->inits()) {
5678     LValue Subobject = This;
5679     LValue SubobjectParent = This;
5680     APValue *Value = &Result;
5681 
5682     // Determine the subobject to initialize.
5683     FieldDecl *FD = nullptr;
5684     if (I->isBaseInitializer()) {
5685       QualType BaseType(I->getBaseClass(), 0);
5686 #ifndef NDEBUG
5687       // Non-virtual base classes are initialized in the order in the class
5688       // definition. We have already checked for virtual base classes.
5689       assert(!BaseIt->isVirtual() && "virtual base for literal type");
5690       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5691              "base class initializers not in expected order");
5692       ++BaseIt;
5693 #endif
5694       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
5695                                   BaseType->getAsCXXRecordDecl(), &Layout))
5696         return false;
5697       Value = &Result.getStructBase(BasesSeen++);
5698     } else if ((FD = I->getMember())) {
5699       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
5700         return false;
5701       if (RD->isUnion()) {
5702         Result = APValue(FD);
5703         Value = &Result.getUnionValue();
5704       } else {
5705         SkipToField(FD, false);
5706         Value = &Result.getStructField(FD->getFieldIndex());
5707       }
5708     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
5709       // Walk the indirect field decl's chain to find the object to initialize,
5710       // and make sure we've initialized every step along it.
5711       auto IndirectFieldChain = IFD->chain();
5712       for (auto *C : IndirectFieldChain) {
5713         FD = cast<FieldDecl>(C);
5714         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5715         // Switch the union field if it differs. This happens if we had
5716         // preceding zero-initialization, and we're now initializing a union
5717         // subobject other than the first.
5718         // FIXME: In this case, the values of the other subobjects are
5719         // specified, since zero-initialization sets all padding bits to zero.
5720         if (!Value->hasValue() ||
5721             (Value->isUnion() && Value->getUnionField() != FD)) {
5722           if (CD->isUnion())
5723             *Value = APValue(FD);
5724           else
5725             // FIXME: This immediately starts the lifetime of all members of an
5726             // anonymous struct. It would be preferable to strictly start member
5727             // lifetime in initialization order.
5728             *Value = getDefaultInitValue(Info.Ctx.getRecordType(CD));
5729         }
5730         // Store Subobject as its parent before updating it for the last element
5731         // in the chain.
5732         if (C == IndirectFieldChain.back())
5733           SubobjectParent = Subobject;
5734         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
5735           return false;
5736         if (CD->isUnion())
5737           Value = &Value->getUnionValue();
5738         else {
5739           if (C == IndirectFieldChain.front() && !RD->isUnion())
5740             SkipToField(FD, true);
5741           Value = &Value->getStructField(FD->getFieldIndex());
5742         }
5743       }
5744     } else {
5745       llvm_unreachable("unknown base initializer kind");
5746     }
5747 
5748     // Need to override This for implicit field initializers as in this case
5749     // This refers to innermost anonymous struct/union containing initializer,
5750     // not to currently constructed class.
5751     const Expr *Init = I->getInit();
5752     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
5753                                   isa<CXXDefaultInitExpr>(Init));
5754     FullExpressionRAII InitScope(Info);
5755     if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
5756         (FD && FD->isBitField() &&
5757          !truncateBitfieldValue(Info, Init, *Value, FD))) {
5758       // If we're checking for a potential constant expression, evaluate all
5759       // initializers even if some of them fail.
5760       if (!Info.noteFailure())
5761         return false;
5762       Success = false;
5763     }
5764 
5765     // This is the point at which the dynamic type of the object becomes this
5766     // class type.
5767     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
5768       EvalObj.finishedConstructingBases();
5769   }
5770 
5771   // Default-initialize any remaining fields.
5772   if (!RD->isUnion()) {
5773     for (; FieldIt != RD->field_end(); ++FieldIt) {
5774       if (!FieldIt->isUnnamedBitfield())
5775         Result.getStructField(FieldIt->getFieldIndex()) =
5776             getDefaultInitValue(FieldIt->getType());
5777     }
5778   }
5779 
5780   return Success &&
5781          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
5782          LifetimeExtendedScope.destroy();
5783 }
5784 
5785 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5786                                   ArrayRef<const Expr*> Args,
5787                                   const CXXConstructorDecl *Definition,
5788                                   EvalInfo &Info, APValue &Result) {
5789   ArgVector ArgValues(Args.size());
5790   if (!EvaluateArgs(Args, ArgValues, Info, Definition))
5791     return false;
5792 
5793   return HandleConstructorCall(E, This, ArgValues.data(), Definition,
5794                                Info, Result);
5795 }
5796 
5797 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
5798                                   const LValue &This, APValue &Value,
5799                                   QualType T) {
5800   // Objects can only be destroyed while they're within their lifetimes.
5801   // FIXME: We have no representation for whether an object of type nullptr_t
5802   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
5803   // as indeterminate instead?
5804   if (Value.isAbsent() && !T->isNullPtrType()) {
5805     APValue Printable;
5806     This.moveInto(Printable);
5807     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
5808       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
5809     return false;
5810   }
5811 
5812   // Invent an expression for location purposes.
5813   // FIXME: We shouldn't need to do this.
5814   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue);
5815 
5816   // For arrays, destroy elements right-to-left.
5817   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
5818     uint64_t Size = CAT->getSize().getZExtValue();
5819     QualType ElemT = CAT->getElementType();
5820 
5821     LValue ElemLV = This;
5822     ElemLV.addArray(Info, &LocE, CAT);
5823     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
5824       return false;
5825 
5826     // Ensure that we have actual array elements available to destroy; the
5827     // destructors might mutate the value, so we can't run them on the array
5828     // filler.
5829     if (Size && Size > Value.getArrayInitializedElts())
5830       expandArray(Value, Value.getArraySize() - 1);
5831 
5832     for (; Size != 0; --Size) {
5833       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
5834       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
5835           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
5836         return false;
5837     }
5838 
5839     // End the lifetime of this array now.
5840     Value = APValue();
5841     return true;
5842   }
5843 
5844   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5845   if (!RD) {
5846     if (T.isDestructedType()) {
5847       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
5848       return false;
5849     }
5850 
5851     Value = APValue();
5852     return true;
5853   }
5854 
5855   if (RD->getNumVBases()) {
5856     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5857     return false;
5858   }
5859 
5860   const CXXDestructorDecl *DD = RD->getDestructor();
5861   if (!DD && !RD->hasTrivialDestructor()) {
5862     Info.FFDiag(CallLoc);
5863     return false;
5864   }
5865 
5866   if (!DD || DD->isTrivial() ||
5867       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
5868     // A trivial destructor just ends the lifetime of the object. Check for
5869     // this case before checking for a body, because we might not bother
5870     // building a body for a trivial destructor. Note that it doesn't matter
5871     // whether the destructor is constexpr in this case; all trivial
5872     // destructors are constexpr.
5873     //
5874     // If an anonymous union would be destroyed, some enclosing destructor must
5875     // have been explicitly defined, and the anonymous union destruction should
5876     // have no effect.
5877     Value = APValue();
5878     return true;
5879   }
5880 
5881   if (!Info.CheckCallLimit(CallLoc))
5882     return false;
5883 
5884   const FunctionDecl *Definition = nullptr;
5885   const Stmt *Body = DD->getBody(Definition);
5886 
5887   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
5888     return false;
5889 
5890   CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr);
5891 
5892   // We're now in the period of destruction of this object.
5893   unsigned BasesLeft = RD->getNumBases();
5894   EvalInfo::EvaluatingDestructorRAII EvalObj(
5895       Info,
5896       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
5897   if (!EvalObj.DidInsert) {
5898     // C++2a [class.dtor]p19:
5899     //   the behavior is undefined if the destructor is invoked for an object
5900     //   whose lifetime has ended
5901     // (Note that formally the lifetime ends when the period of destruction
5902     // begins, even though certain uses of the object remain valid until the
5903     // period of destruction ends.)
5904     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
5905     return false;
5906   }
5907 
5908   // FIXME: Creating an APValue just to hold a nonexistent return value is
5909   // wasteful.
5910   APValue RetVal;
5911   StmtResult Ret = {RetVal, nullptr};
5912   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
5913     return false;
5914 
5915   // A union destructor does not implicitly destroy its members.
5916   if (RD->isUnion())
5917     return true;
5918 
5919   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5920 
5921   // We don't have a good way to iterate fields in reverse, so collect all the
5922   // fields first and then walk them backwards.
5923   SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
5924   for (const FieldDecl *FD : llvm::reverse(Fields)) {
5925     if (FD->isUnnamedBitfield())
5926       continue;
5927 
5928     LValue Subobject = This;
5929     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
5930       return false;
5931 
5932     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
5933     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
5934                                FD->getType()))
5935       return false;
5936   }
5937 
5938   if (BasesLeft != 0)
5939     EvalObj.startedDestroyingBases();
5940 
5941   // Destroy base classes in reverse order.
5942   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
5943     --BasesLeft;
5944 
5945     QualType BaseType = Base.getType();
5946     LValue Subobject = This;
5947     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
5948                                 BaseType->getAsCXXRecordDecl(), &Layout))
5949       return false;
5950 
5951     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
5952     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
5953                                BaseType))
5954       return false;
5955   }
5956   assert(BasesLeft == 0 && "NumBases was wrong?");
5957 
5958   // The period of destruction ends now. The object is gone.
5959   Value = APValue();
5960   return true;
5961 }
5962 
5963 namespace {
5964 struct DestroyObjectHandler {
5965   EvalInfo &Info;
5966   const Expr *E;
5967   const LValue &This;
5968   const AccessKinds AccessKind;
5969 
5970   typedef bool result_type;
5971   bool failed() { return false; }
5972   bool found(APValue &Subobj, QualType SubobjType) {
5973     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
5974                                  SubobjType);
5975   }
5976   bool found(APSInt &Value, QualType SubobjType) {
5977     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
5978     return false;
5979   }
5980   bool found(APFloat &Value, QualType SubobjType) {
5981     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
5982     return false;
5983   }
5984 };
5985 }
5986 
5987 /// Perform a destructor or pseudo-destructor call on the given object, which
5988 /// might in general not be a complete object.
5989 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
5990                               const LValue &This, QualType ThisType) {
5991   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
5992   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
5993   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5994 }
5995 
5996 /// Destroy and end the lifetime of the given complete object.
5997 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
5998                               APValue::LValueBase LVBase, APValue &Value,
5999                               QualType T) {
6000   // If we've had an unmodeled side-effect, we can't rely on mutable state
6001   // (such as the object we're about to destroy) being correct.
6002   if (Info.EvalStatus.HasSideEffects)
6003     return false;
6004 
6005   LValue LV;
6006   LV.set({LVBase});
6007   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6008 }
6009 
6010 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6011 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6012                                   LValue &Result) {
6013   if (Info.checkingPotentialConstantExpression() ||
6014       Info.SpeculativeEvaluationDepth)
6015     return false;
6016 
6017   // This is permitted only within a call to std::allocator<T>::allocate.
6018   auto Caller = Info.getStdAllocatorCaller("allocate");
6019   if (!Caller) {
6020     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus2a
6021                                      ? diag::note_constexpr_new_untyped
6022                                      : diag::note_constexpr_new);
6023     return false;
6024   }
6025 
6026   QualType ElemType = Caller.ElemType;
6027   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6028     Info.FFDiag(E->getExprLoc(),
6029                 diag::note_constexpr_new_not_complete_object_type)
6030         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6031     return false;
6032   }
6033 
6034   APSInt ByteSize;
6035   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6036     return false;
6037   bool IsNothrow = false;
6038   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6039     EvaluateIgnoredValue(Info, E->getArg(I));
6040     IsNothrow |= E->getType()->isNothrowT();
6041   }
6042 
6043   CharUnits ElemSize;
6044   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6045     return false;
6046   APInt Size, Remainder;
6047   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6048   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6049   if (Remainder != 0) {
6050     // This likely indicates a bug in the implementation of 'std::allocator'.
6051     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6052         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6053     return false;
6054   }
6055 
6056   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6057     if (IsNothrow) {
6058       Result.setNull(Info.Ctx, E->getType());
6059       return true;
6060     }
6061 
6062     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6063     return false;
6064   }
6065 
6066   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6067                                                      ArrayType::Normal, 0);
6068   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6069   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6070   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6071   return true;
6072 }
6073 
6074 static bool hasVirtualDestructor(QualType T) {
6075   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6076     if (CXXDestructorDecl *DD = RD->getDestructor())
6077       return DD->isVirtual();
6078   return false;
6079 }
6080 
6081 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6082   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6083     if (CXXDestructorDecl *DD = RD->getDestructor())
6084       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6085   return nullptr;
6086 }
6087 
6088 /// Check that the given object is a suitable pointer to a heap allocation that
6089 /// still exists and is of the right kind for the purpose of a deletion.
6090 ///
6091 /// On success, returns the heap allocation to deallocate. On failure, produces
6092 /// a diagnostic and returns None.
6093 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6094                                             const LValue &Pointer,
6095                                             DynAlloc::Kind DeallocKind) {
6096   auto PointerAsString = [&] {
6097     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6098   };
6099 
6100   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6101   if (!DA) {
6102     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6103         << PointerAsString();
6104     if (Pointer.Base)
6105       NoteLValueLocation(Info, Pointer.Base);
6106     return None;
6107   }
6108 
6109   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6110   if (!Alloc) {
6111     Info.FFDiag(E, diag::note_constexpr_double_delete);
6112     return None;
6113   }
6114 
6115   QualType AllocType = Pointer.Base.getDynamicAllocType();
6116   if (DeallocKind != (*Alloc)->getKind()) {
6117     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6118         << DeallocKind << (*Alloc)->getKind() << AllocType;
6119     NoteLValueLocation(Info, Pointer.Base);
6120     return None;
6121   }
6122 
6123   bool Subobject = false;
6124   if (DeallocKind == DynAlloc::New) {
6125     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6126                 Pointer.Designator.isOnePastTheEnd();
6127   } else {
6128     Subobject = Pointer.Designator.Entries.size() != 1 ||
6129                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6130   }
6131   if (Subobject) {
6132     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6133         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6134     return None;
6135   }
6136 
6137   return Alloc;
6138 }
6139 
6140 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6141 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6142   if (Info.checkingPotentialConstantExpression() ||
6143       Info.SpeculativeEvaluationDepth)
6144     return false;
6145 
6146   // This is permitted only within a call to std::allocator<T>::deallocate.
6147   if (!Info.getStdAllocatorCaller("deallocate")) {
6148     Info.FFDiag(E->getExprLoc());
6149     return true;
6150   }
6151 
6152   LValue Pointer;
6153   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6154     return false;
6155   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6156     EvaluateIgnoredValue(Info, E->getArg(I));
6157 
6158   if (Pointer.Designator.Invalid)
6159     return false;
6160 
6161   // Deleting a null pointer has no effect.
6162   if (Pointer.isNullPointer())
6163     return true;
6164 
6165   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6166     return false;
6167 
6168   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6169   return true;
6170 }
6171 
6172 //===----------------------------------------------------------------------===//
6173 // Generic Evaluation
6174 //===----------------------------------------------------------------------===//
6175 namespace {
6176 
6177 class BitCastBuffer {
6178   // FIXME: We're going to need bit-level granularity when we support
6179   // bit-fields.
6180   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6181   // we don't support a host or target where that is the case. Still, we should
6182   // use a more generic type in case we ever do.
6183   SmallVector<Optional<unsigned char>, 32> Bytes;
6184 
6185   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6186                 "Need at least 8 bit unsigned char");
6187 
6188   bool TargetIsLittleEndian;
6189 
6190 public:
6191   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6192       : Bytes(Width.getQuantity()),
6193         TargetIsLittleEndian(TargetIsLittleEndian) {}
6194 
6195   LLVM_NODISCARD
6196   bool readObject(CharUnits Offset, CharUnits Width,
6197                   SmallVectorImpl<unsigned char> &Output) const {
6198     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6199       // If a byte of an integer is uninitialized, then the whole integer is
6200       // uninitalized.
6201       if (!Bytes[I.getQuantity()])
6202         return false;
6203       Output.push_back(*Bytes[I.getQuantity()]);
6204     }
6205     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6206       std::reverse(Output.begin(), Output.end());
6207     return true;
6208   }
6209 
6210   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6211     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6212       std::reverse(Input.begin(), Input.end());
6213 
6214     size_t Index = 0;
6215     for (unsigned char Byte : Input) {
6216       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6217       Bytes[Offset.getQuantity() + Index] = Byte;
6218       ++Index;
6219     }
6220   }
6221 
6222   size_t size() { return Bytes.size(); }
6223 };
6224 
6225 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6226 /// target would represent the value at runtime.
6227 class APValueToBufferConverter {
6228   EvalInfo &Info;
6229   BitCastBuffer Buffer;
6230   const CastExpr *BCE;
6231 
6232   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6233                            const CastExpr *BCE)
6234       : Info(Info),
6235         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6236         BCE(BCE) {}
6237 
6238   bool visit(const APValue &Val, QualType Ty) {
6239     return visit(Val, Ty, CharUnits::fromQuantity(0));
6240   }
6241 
6242   // Write out Val with type Ty into Buffer starting at Offset.
6243   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6244     assert((size_t)Offset.getQuantity() <= Buffer.size());
6245 
6246     // As a special case, nullptr_t has an indeterminate value.
6247     if (Ty->isNullPtrType())
6248       return true;
6249 
6250     // Dig through Src to find the byte at SrcOffset.
6251     switch (Val.getKind()) {
6252     case APValue::Indeterminate:
6253     case APValue::None:
6254       return true;
6255 
6256     case APValue::Int:
6257       return visitInt(Val.getInt(), Ty, Offset);
6258     case APValue::Float:
6259       return visitFloat(Val.getFloat(), Ty, Offset);
6260     case APValue::Array:
6261       return visitArray(Val, Ty, Offset);
6262     case APValue::Struct:
6263       return visitRecord(Val, Ty, Offset);
6264 
6265     case APValue::ComplexInt:
6266     case APValue::ComplexFloat:
6267     case APValue::Vector:
6268     case APValue::FixedPoint:
6269       // FIXME: We should support these.
6270 
6271     case APValue::Union:
6272     case APValue::MemberPointer:
6273     case APValue::AddrLabelDiff: {
6274       Info.FFDiag(BCE->getBeginLoc(),
6275                   diag::note_constexpr_bit_cast_unsupported_type)
6276           << Ty;
6277       return false;
6278     }
6279 
6280     case APValue::LValue:
6281       llvm_unreachable("LValue subobject in bit_cast?");
6282     }
6283     llvm_unreachable("Unhandled APValue::ValueKind");
6284   }
6285 
6286   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6287     const RecordDecl *RD = Ty->getAsRecordDecl();
6288     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6289 
6290     // Visit the base classes.
6291     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6292       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6293         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6294         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6295 
6296         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6297                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6298           return false;
6299       }
6300     }
6301 
6302     // Visit the fields.
6303     unsigned FieldIdx = 0;
6304     for (FieldDecl *FD : RD->fields()) {
6305       if (FD->isBitField()) {
6306         Info.FFDiag(BCE->getBeginLoc(),
6307                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6308         return false;
6309       }
6310 
6311       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6312 
6313       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6314              "only bit-fields can have sub-char alignment");
6315       CharUnits FieldOffset =
6316           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6317       QualType FieldTy = FD->getType();
6318       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6319         return false;
6320       ++FieldIdx;
6321     }
6322 
6323     return true;
6324   }
6325 
6326   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6327     const auto *CAT =
6328         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6329     if (!CAT)
6330       return false;
6331 
6332     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6333     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6334     unsigned ArraySize = Val.getArraySize();
6335     // First, initialize the initialized elements.
6336     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6337       const APValue &SubObj = Val.getArrayInitializedElt(I);
6338       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6339         return false;
6340     }
6341 
6342     // Next, initialize the rest of the array using the filler.
6343     if (Val.hasArrayFiller()) {
6344       const APValue &Filler = Val.getArrayFiller();
6345       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6346         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6347           return false;
6348       }
6349     }
6350 
6351     return true;
6352   }
6353 
6354   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6355     CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
6356     SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
6357     llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
6358     Buffer.writeObject(Offset, Bytes);
6359     return true;
6360   }
6361 
6362   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6363     APSInt AsInt(Val.bitcastToAPInt());
6364     return visitInt(AsInt, Ty, Offset);
6365   }
6366 
6367 public:
6368   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6369                                          const CastExpr *BCE) {
6370     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6371     APValueToBufferConverter Converter(Info, DstSize, BCE);
6372     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6373       return None;
6374     return Converter.Buffer;
6375   }
6376 };
6377 
6378 /// Write an BitCastBuffer into an APValue.
6379 class BufferToAPValueConverter {
6380   EvalInfo &Info;
6381   const BitCastBuffer &Buffer;
6382   const CastExpr *BCE;
6383 
6384   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6385                            const CastExpr *BCE)
6386       : Info(Info), Buffer(Buffer), BCE(BCE) {}
6387 
6388   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6389   // with an invalid type, so anything left is a deficiency on our part (FIXME).
6390   // Ideally this will be unreachable.
6391   llvm::NoneType unsupportedType(QualType Ty) {
6392     Info.FFDiag(BCE->getBeginLoc(),
6393                 diag::note_constexpr_bit_cast_unsupported_type)
6394         << Ty;
6395     return None;
6396   }
6397 
6398   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6399                           const EnumType *EnumSugar = nullptr) {
6400     if (T->isNullPtrType()) {
6401       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6402       return APValue((Expr *)nullptr,
6403                      /*Offset=*/CharUnits::fromQuantity(NullValue),
6404                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6405     }
6406 
6407     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6408     SmallVector<uint8_t, 8> Bytes;
6409     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
6410       // If this is std::byte or unsigned char, then its okay to store an
6411       // indeterminate value.
6412       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
6413       bool IsUChar =
6414           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
6415                          T->isSpecificBuiltinType(BuiltinType::Char_U));
6416       if (!IsStdByte && !IsUChar) {
6417         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
6418         Info.FFDiag(BCE->getExprLoc(),
6419                     diag::note_constexpr_bit_cast_indet_dest)
6420             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
6421         return None;
6422       }
6423 
6424       return APValue::IndeterminateValue();
6425     }
6426 
6427     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
6428     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
6429 
6430     if (T->isIntegralOrEnumerationType()) {
6431       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
6432       return APValue(Val);
6433     }
6434 
6435     if (T->isRealFloatingType()) {
6436       const llvm::fltSemantics &Semantics =
6437           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6438       return APValue(APFloat(Semantics, Val));
6439     }
6440 
6441     return unsupportedType(QualType(T, 0));
6442   }
6443 
6444   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
6445     const RecordDecl *RD = RTy->getAsRecordDecl();
6446     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6447 
6448     unsigned NumBases = 0;
6449     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6450       NumBases = CXXRD->getNumBases();
6451 
6452     APValue ResultVal(APValue::UninitStruct(), NumBases,
6453                       std::distance(RD->field_begin(), RD->field_end()));
6454 
6455     // Visit the base classes.
6456     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6457       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6458         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6459         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6460         if (BaseDecl->isEmpty() ||
6461             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
6462           continue;
6463 
6464         Optional<APValue> SubObj = visitType(
6465             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
6466         if (!SubObj)
6467           return None;
6468         ResultVal.getStructBase(I) = *SubObj;
6469       }
6470     }
6471 
6472     // Visit the fields.
6473     unsigned FieldIdx = 0;
6474     for (FieldDecl *FD : RD->fields()) {
6475       // FIXME: We don't currently support bit-fields. A lot of the logic for
6476       // this is in CodeGen, so we need to factor it around.
6477       if (FD->isBitField()) {
6478         Info.FFDiag(BCE->getBeginLoc(),
6479                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6480         return None;
6481       }
6482 
6483       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6484       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
6485 
6486       CharUnits FieldOffset =
6487           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
6488           Offset;
6489       QualType FieldTy = FD->getType();
6490       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
6491       if (!SubObj)
6492         return None;
6493       ResultVal.getStructField(FieldIdx) = *SubObj;
6494       ++FieldIdx;
6495     }
6496 
6497     return ResultVal;
6498   }
6499 
6500   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
6501     QualType RepresentationType = Ty->getDecl()->getIntegerType();
6502     assert(!RepresentationType.isNull() &&
6503            "enum forward decl should be caught by Sema");
6504     const auto *AsBuiltin =
6505         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
6506     // Recurse into the underlying type. Treat std::byte transparently as
6507     // unsigned char.
6508     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
6509   }
6510 
6511   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
6512     size_t Size = Ty->getSize().getLimitedValue();
6513     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
6514 
6515     APValue ArrayValue(APValue::UninitArray(), Size, Size);
6516     for (size_t I = 0; I != Size; ++I) {
6517       Optional<APValue> ElementValue =
6518           visitType(Ty->getElementType(), Offset + I * ElementWidth);
6519       if (!ElementValue)
6520         return None;
6521       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
6522     }
6523 
6524     return ArrayValue;
6525   }
6526 
6527   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
6528     return unsupportedType(QualType(Ty, 0));
6529   }
6530 
6531   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
6532     QualType Can = Ty.getCanonicalType();
6533 
6534     switch (Can->getTypeClass()) {
6535 #define TYPE(Class, Base)                                                      \
6536   case Type::Class:                                                            \
6537     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
6538 #define ABSTRACT_TYPE(Class, Base)
6539 #define NON_CANONICAL_TYPE(Class, Base)                                        \
6540   case Type::Class:                                                            \
6541     llvm_unreachable("non-canonical type should be impossible!");
6542 #define DEPENDENT_TYPE(Class, Base)                                            \
6543   case Type::Class:                                                            \
6544     llvm_unreachable(                                                          \
6545         "dependent types aren't supported in the constant evaluator!");
6546 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
6547   case Type::Class:                                                            \
6548     llvm_unreachable("either dependent or not canonical!");
6549 #include "clang/AST/TypeNodes.inc"
6550     }
6551     llvm_unreachable("Unhandled Type::TypeClass");
6552   }
6553 
6554 public:
6555   // Pull out a full value of type DstType.
6556   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
6557                                    const CastExpr *BCE) {
6558     BufferToAPValueConverter Converter(Info, Buffer, BCE);
6559     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
6560   }
6561 };
6562 
6563 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
6564                                                  QualType Ty, EvalInfo *Info,
6565                                                  const ASTContext &Ctx,
6566                                                  bool CheckingDest) {
6567   Ty = Ty.getCanonicalType();
6568 
6569   auto diag = [&](int Reason) {
6570     if (Info)
6571       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
6572           << CheckingDest << (Reason == 4) << Reason;
6573     return false;
6574   };
6575   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
6576     if (Info)
6577       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
6578           << NoteTy << Construct << Ty;
6579     return false;
6580   };
6581 
6582   if (Ty->isUnionType())
6583     return diag(0);
6584   if (Ty->isPointerType())
6585     return diag(1);
6586   if (Ty->isMemberPointerType())
6587     return diag(2);
6588   if (Ty.isVolatileQualified())
6589     return diag(3);
6590 
6591   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
6592     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
6593       for (CXXBaseSpecifier &BS : CXXRD->bases())
6594         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
6595                                                   CheckingDest))
6596           return note(1, BS.getType(), BS.getBeginLoc());
6597     }
6598     for (FieldDecl *FD : Record->fields()) {
6599       if (FD->getType()->isReferenceType())
6600         return diag(4);
6601       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
6602                                                 CheckingDest))
6603         return note(0, FD->getType(), FD->getBeginLoc());
6604     }
6605   }
6606 
6607   if (Ty->isArrayType() &&
6608       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
6609                                             Info, Ctx, CheckingDest))
6610     return false;
6611 
6612   return true;
6613 }
6614 
6615 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
6616                                              const ASTContext &Ctx,
6617                                              const CastExpr *BCE) {
6618   bool DestOK = checkBitCastConstexprEligibilityType(
6619       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
6620   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
6621                                 BCE->getBeginLoc(),
6622                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
6623   return SourceOK;
6624 }
6625 
6626 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
6627                                         APValue &SourceValue,
6628                                         const CastExpr *BCE) {
6629   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
6630          "no host or target supports non 8-bit chars");
6631   assert(SourceValue.isLValue() &&
6632          "LValueToRValueBitcast requires an lvalue operand!");
6633 
6634   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
6635     return false;
6636 
6637   LValue SourceLValue;
6638   APValue SourceRValue;
6639   SourceLValue.setFrom(Info.Ctx, SourceValue);
6640   if (!handleLValueToRValueConversion(
6641           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
6642           SourceRValue, /*WantObjectRepresentation=*/true))
6643     return false;
6644 
6645   // Read out SourceValue into a char buffer.
6646   Optional<BitCastBuffer> Buffer =
6647       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
6648   if (!Buffer)
6649     return false;
6650 
6651   // Write out the buffer into a new APValue.
6652   Optional<APValue> MaybeDestValue =
6653       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
6654   if (!MaybeDestValue)
6655     return false;
6656 
6657   DestValue = std::move(*MaybeDestValue);
6658   return true;
6659 }
6660 
6661 template <class Derived>
6662 class ExprEvaluatorBase
6663   : public ConstStmtVisitor<Derived, bool> {
6664 private:
6665   Derived &getDerived() { return static_cast<Derived&>(*this); }
6666   bool DerivedSuccess(const APValue &V, const Expr *E) {
6667     return getDerived().Success(V, E);
6668   }
6669   bool DerivedZeroInitialization(const Expr *E) {
6670     return getDerived().ZeroInitialization(E);
6671   }
6672 
6673   // Check whether a conditional operator with a non-constant condition is a
6674   // potential constant expression. If neither arm is a potential constant
6675   // expression, then the conditional operator is not either.
6676   template<typename ConditionalOperator>
6677   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
6678     assert(Info.checkingPotentialConstantExpression());
6679 
6680     // Speculatively evaluate both arms.
6681     SmallVector<PartialDiagnosticAt, 8> Diag;
6682     {
6683       SpeculativeEvaluationRAII Speculate(Info, &Diag);
6684       StmtVisitorTy::Visit(E->getFalseExpr());
6685       if (Diag.empty())
6686         return;
6687     }
6688 
6689     {
6690       SpeculativeEvaluationRAII Speculate(Info, &Diag);
6691       Diag.clear();
6692       StmtVisitorTy::Visit(E->getTrueExpr());
6693       if (Diag.empty())
6694         return;
6695     }
6696 
6697     Error(E, diag::note_constexpr_conditional_never_const);
6698   }
6699 
6700 
6701   template<typename ConditionalOperator>
6702   bool HandleConditionalOperator(const ConditionalOperator *E) {
6703     bool BoolResult;
6704     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
6705       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
6706         CheckPotentialConstantConditional(E);
6707         return false;
6708       }
6709       if (Info.noteFailure()) {
6710         StmtVisitorTy::Visit(E->getTrueExpr());
6711         StmtVisitorTy::Visit(E->getFalseExpr());
6712       }
6713       return false;
6714     }
6715 
6716     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
6717     return StmtVisitorTy::Visit(EvalExpr);
6718   }
6719 
6720 protected:
6721   EvalInfo &Info;
6722   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
6723   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
6724 
6725   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6726     return Info.CCEDiag(E, D);
6727   }
6728 
6729   bool ZeroInitialization(const Expr *E) { return Error(E); }
6730 
6731 public:
6732   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
6733 
6734   EvalInfo &getEvalInfo() { return Info; }
6735 
6736   /// Report an evaluation error. This should only be called when an error is
6737   /// first discovered. When propagating an error, just return false.
6738   bool Error(const Expr *E, diag::kind D) {
6739     Info.FFDiag(E, D);
6740     return false;
6741   }
6742   bool Error(const Expr *E) {
6743     return Error(E, diag::note_invalid_subexpr_in_const_expr);
6744   }
6745 
6746   bool VisitStmt(const Stmt *) {
6747     llvm_unreachable("Expression evaluator should not be called on stmts");
6748   }
6749   bool VisitExpr(const Expr *E) {
6750     return Error(E);
6751   }
6752 
6753   bool VisitConstantExpr(const ConstantExpr *E)
6754     { return StmtVisitorTy::Visit(E->getSubExpr()); }
6755   bool VisitParenExpr(const ParenExpr *E)
6756     { return StmtVisitorTy::Visit(E->getSubExpr()); }
6757   bool VisitUnaryExtension(const UnaryOperator *E)
6758     { return StmtVisitorTy::Visit(E->getSubExpr()); }
6759   bool VisitUnaryPlus(const UnaryOperator *E)
6760     { return StmtVisitorTy::Visit(E->getSubExpr()); }
6761   bool VisitChooseExpr(const ChooseExpr *E)
6762     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
6763   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
6764     { return StmtVisitorTy::Visit(E->getResultExpr()); }
6765   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
6766     { return StmtVisitorTy::Visit(E->getReplacement()); }
6767   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
6768     TempVersionRAII RAII(*Info.CurrentCall);
6769     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
6770     return StmtVisitorTy::Visit(E->getExpr());
6771   }
6772   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
6773     TempVersionRAII RAII(*Info.CurrentCall);
6774     // The initializer may not have been parsed yet, or might be erroneous.
6775     if (!E->getExpr())
6776       return Error(E);
6777     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
6778     return StmtVisitorTy::Visit(E->getExpr());
6779   }
6780 
6781   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
6782     FullExpressionRAII Scope(Info);
6783     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
6784   }
6785 
6786   // Temporaries are registered when created, so we don't care about
6787   // CXXBindTemporaryExpr.
6788   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
6789     return StmtVisitorTy::Visit(E->getSubExpr());
6790   }
6791 
6792   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
6793     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
6794     return static_cast<Derived*>(this)->VisitCastExpr(E);
6795   }
6796   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
6797     if (!Info.Ctx.getLangOpts().CPlusPlus2a)
6798       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
6799     return static_cast<Derived*>(this)->VisitCastExpr(E);
6800   }
6801   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
6802     return static_cast<Derived*>(this)->VisitCastExpr(E);
6803   }
6804 
6805   bool VisitBinaryOperator(const BinaryOperator *E) {
6806     switch (E->getOpcode()) {
6807     default:
6808       return Error(E);
6809 
6810     case BO_Comma:
6811       VisitIgnoredValue(E->getLHS());
6812       return StmtVisitorTy::Visit(E->getRHS());
6813 
6814     case BO_PtrMemD:
6815     case BO_PtrMemI: {
6816       LValue Obj;
6817       if (!HandleMemberPointerAccess(Info, E, Obj))
6818         return false;
6819       APValue Result;
6820       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
6821         return false;
6822       return DerivedSuccess(Result, E);
6823     }
6824     }
6825   }
6826 
6827   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
6828     return StmtVisitorTy::Visit(E->getSemanticForm());
6829   }
6830 
6831   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
6832     // Evaluate and cache the common expression. We treat it as a temporary,
6833     // even though it's not quite the same thing.
6834     LValue CommonLV;
6835     if (!Evaluate(Info.CurrentCall->createTemporary(
6836                       E->getOpaqueValue(),
6837                       getStorageType(Info.Ctx, E->getOpaqueValue()), false,
6838                       CommonLV),
6839                   Info, E->getCommon()))
6840       return false;
6841 
6842     return HandleConditionalOperator(E);
6843   }
6844 
6845   bool VisitConditionalOperator(const ConditionalOperator *E) {
6846     bool IsBcpCall = false;
6847     // If the condition (ignoring parens) is a __builtin_constant_p call,
6848     // the result is a constant expression if it can be folded without
6849     // side-effects. This is an important GNU extension. See GCC PR38377
6850     // for discussion.
6851     if (const CallExpr *CallCE =
6852           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
6853       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
6854         IsBcpCall = true;
6855 
6856     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
6857     // constant expression; we can't check whether it's potentially foldable.
6858     // FIXME: We should instead treat __builtin_constant_p as non-constant if
6859     // it would return 'false' in this mode.
6860     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
6861       return false;
6862 
6863     FoldConstant Fold(Info, IsBcpCall);
6864     if (!HandleConditionalOperator(E)) {
6865       Fold.keepDiagnostics();
6866       return false;
6867     }
6868 
6869     return true;
6870   }
6871 
6872   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
6873     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
6874       return DerivedSuccess(*Value, E);
6875 
6876     const Expr *Source = E->getSourceExpr();
6877     if (!Source)
6878       return Error(E);
6879     if (Source == E) { // sanity checking.
6880       assert(0 && "OpaqueValueExpr recursively refers to itself");
6881       return Error(E);
6882     }
6883     return StmtVisitorTy::Visit(Source);
6884   }
6885 
6886   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
6887     for (const Expr *SemE : E->semantics()) {
6888       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
6889         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
6890         // result expression: there could be two different LValues that would
6891         // refer to the same object in that case, and we can't model that.
6892         if (SemE == E->getResultExpr())
6893           return Error(E);
6894 
6895         // Unique OVEs get evaluated if and when we encounter them when
6896         // emitting the rest of the semantic form, rather than eagerly.
6897         if (OVE->isUnique())
6898           continue;
6899 
6900         LValue LV;
6901         if (!Evaluate(Info.CurrentCall->createTemporary(
6902                           OVE, getStorageType(Info.Ctx, OVE), false, LV),
6903                       Info, OVE->getSourceExpr()))
6904           return false;
6905       } else if (SemE == E->getResultExpr()) {
6906         if (!StmtVisitorTy::Visit(SemE))
6907           return false;
6908       } else {
6909         if (!EvaluateIgnoredValue(Info, SemE))
6910           return false;
6911       }
6912     }
6913     return true;
6914   }
6915 
6916   bool VisitCallExpr(const CallExpr *E) {
6917     APValue Result;
6918     if (!handleCallExpr(E, Result, nullptr))
6919       return false;
6920     return DerivedSuccess(Result, E);
6921   }
6922 
6923   bool handleCallExpr(const CallExpr *E, APValue &Result,
6924                      const LValue *ResultSlot) {
6925     const Expr *Callee = E->getCallee()->IgnoreParens();
6926     QualType CalleeType = Callee->getType();
6927 
6928     const FunctionDecl *FD = nullptr;
6929     LValue *This = nullptr, ThisVal;
6930     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
6931     bool HasQualifier = false;
6932 
6933     // Extract function decl and 'this' pointer from the callee.
6934     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
6935       const CXXMethodDecl *Member = nullptr;
6936       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
6937         // Explicit bound member calls, such as x.f() or p->g();
6938         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
6939           return false;
6940         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
6941         if (!Member)
6942           return Error(Callee);
6943         This = &ThisVal;
6944         HasQualifier = ME->hasQualifier();
6945       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
6946         // Indirect bound member calls ('.*' or '->*').
6947         const ValueDecl *D =
6948             HandleMemberPointerAccess(Info, BE, ThisVal, false);
6949         if (!D)
6950           return false;
6951         Member = dyn_cast<CXXMethodDecl>(D);
6952         if (!Member)
6953           return Error(Callee);
6954         This = &ThisVal;
6955       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
6956         if (!Info.getLangOpts().CPlusPlus2a)
6957           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
6958         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
6959                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
6960       } else
6961         return Error(Callee);
6962       FD = Member;
6963     } else if (CalleeType->isFunctionPointerType()) {
6964       LValue Call;
6965       if (!EvaluatePointer(Callee, Call, Info))
6966         return false;
6967 
6968       if (!Call.getLValueOffset().isZero())
6969         return Error(Callee);
6970       FD = dyn_cast_or_null<FunctionDecl>(
6971                              Call.getLValueBase().dyn_cast<const ValueDecl*>());
6972       if (!FD)
6973         return Error(Callee);
6974       // Don't call function pointers which have been cast to some other type.
6975       // Per DR (no number yet), the caller and callee can differ in noexcept.
6976       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
6977         CalleeType->getPointeeType(), FD->getType())) {
6978         return Error(E);
6979       }
6980 
6981       // Overloaded operator calls to member functions are represented as normal
6982       // calls with '*this' as the first argument.
6983       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6984       if (MD && !MD->isStatic()) {
6985         // FIXME: When selecting an implicit conversion for an overloaded
6986         // operator delete, we sometimes try to evaluate calls to conversion
6987         // operators without a 'this' parameter!
6988         if (Args.empty())
6989           return Error(E);
6990 
6991         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
6992           return false;
6993         This = &ThisVal;
6994         Args = Args.slice(1);
6995       } else if (MD && MD->isLambdaStaticInvoker()) {
6996         // Map the static invoker for the lambda back to the call operator.
6997         // Conveniently, we don't have to slice out the 'this' argument (as is
6998         // being done for the non-static case), since a static member function
6999         // doesn't have an implicit argument passed in.
7000         const CXXRecordDecl *ClosureClass = MD->getParent();
7001         assert(
7002             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7003             "Number of captures must be zero for conversion to function-ptr");
7004 
7005         const CXXMethodDecl *LambdaCallOp =
7006             ClosureClass->getLambdaCallOperator();
7007 
7008         // Set 'FD', the function that will be called below, to the call
7009         // operator.  If the closure object represents a generic lambda, find
7010         // the corresponding specialization of the call operator.
7011 
7012         if (ClosureClass->isGenericLambda()) {
7013           assert(MD->isFunctionTemplateSpecialization() &&
7014                  "A generic lambda's static-invoker function must be a "
7015                  "template specialization");
7016           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7017           FunctionTemplateDecl *CallOpTemplate =
7018               LambdaCallOp->getDescribedFunctionTemplate();
7019           void *InsertPos = nullptr;
7020           FunctionDecl *CorrespondingCallOpSpecialization =
7021               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7022           assert(CorrespondingCallOpSpecialization &&
7023                  "We must always have a function call operator specialization "
7024                  "that corresponds to our static invoker specialization");
7025           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7026         } else
7027           FD = LambdaCallOp;
7028       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7029         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7030             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7031           LValue Ptr;
7032           if (!HandleOperatorNewCall(Info, E, Ptr))
7033             return false;
7034           Ptr.moveInto(Result);
7035           return true;
7036         } else {
7037           return HandleOperatorDeleteCall(Info, E);
7038         }
7039       }
7040     } else
7041       return Error(E);
7042 
7043     SmallVector<QualType, 4> CovariantAdjustmentPath;
7044     if (This) {
7045       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7046       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7047         // Perform virtual dispatch, if necessary.
7048         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7049                                    CovariantAdjustmentPath);
7050         if (!FD)
7051           return false;
7052       } else {
7053         // Check that the 'this' pointer points to an object of the right type.
7054         // FIXME: If this is an assignment operator call, we may need to change
7055         // the active union member before we check this.
7056         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7057           return false;
7058       }
7059     }
7060 
7061     // Destructor calls are different enough that they have their own codepath.
7062     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7063       assert(This && "no 'this' pointer for destructor call");
7064       return HandleDestruction(Info, E, *This,
7065                                Info.Ctx.getRecordType(DD->getParent()));
7066     }
7067 
7068     const FunctionDecl *Definition = nullptr;
7069     Stmt *Body = FD->getBody(Definition);
7070 
7071     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7072         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
7073                             Result, ResultSlot))
7074       return false;
7075 
7076     if (!CovariantAdjustmentPath.empty() &&
7077         !HandleCovariantReturnAdjustment(Info, E, Result,
7078                                          CovariantAdjustmentPath))
7079       return false;
7080 
7081     return true;
7082   }
7083 
7084   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7085     return StmtVisitorTy::Visit(E->getInitializer());
7086   }
7087   bool VisitInitListExpr(const InitListExpr *E) {
7088     if (E->getNumInits() == 0)
7089       return DerivedZeroInitialization(E);
7090     if (E->getNumInits() == 1)
7091       return StmtVisitorTy::Visit(E->getInit(0));
7092     return Error(E);
7093   }
7094   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7095     return DerivedZeroInitialization(E);
7096   }
7097   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7098     return DerivedZeroInitialization(E);
7099   }
7100   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7101     return DerivedZeroInitialization(E);
7102   }
7103 
7104   /// A member expression where the object is a prvalue is itself a prvalue.
7105   bool VisitMemberExpr(const MemberExpr *E) {
7106     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7107            "missing temporary materialization conversion");
7108     assert(!E->isArrow() && "missing call to bound member function?");
7109 
7110     APValue Val;
7111     if (!Evaluate(Val, Info, E->getBase()))
7112       return false;
7113 
7114     QualType BaseTy = E->getBase()->getType();
7115 
7116     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7117     if (!FD) return Error(E);
7118     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7119     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7120            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7121 
7122     // Note: there is no lvalue base here. But this case should only ever
7123     // happen in C or in C++98, where we cannot be evaluating a constexpr
7124     // constructor, which is the only case the base matters.
7125     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7126     SubobjectDesignator Designator(BaseTy);
7127     Designator.addDeclUnchecked(FD);
7128 
7129     APValue Result;
7130     return extractSubobject(Info, E, Obj, Designator, Result) &&
7131            DerivedSuccess(Result, E);
7132   }
7133 
7134   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7135     APValue Val;
7136     if (!Evaluate(Val, Info, E->getBase()))
7137       return false;
7138 
7139     if (Val.isVector()) {
7140       SmallVector<uint32_t, 4> Indices;
7141       E->getEncodedElementAccess(Indices);
7142       if (Indices.size() == 1) {
7143         // Return scalar.
7144         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7145       } else {
7146         // Construct new APValue vector.
7147         SmallVector<APValue, 4> Elts;
7148         for (unsigned I = 0; I < Indices.size(); ++I) {
7149           Elts.push_back(Val.getVectorElt(Indices[I]));
7150         }
7151         APValue VecResult(Elts.data(), Indices.size());
7152         return DerivedSuccess(VecResult, E);
7153       }
7154     }
7155 
7156     return false;
7157   }
7158 
7159   bool VisitCastExpr(const CastExpr *E) {
7160     switch (E->getCastKind()) {
7161     default:
7162       break;
7163 
7164     case CK_AtomicToNonAtomic: {
7165       APValue AtomicVal;
7166       // This does not need to be done in place even for class/array types:
7167       // atomic-to-non-atomic conversion implies copying the object
7168       // representation.
7169       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7170         return false;
7171       return DerivedSuccess(AtomicVal, E);
7172     }
7173 
7174     case CK_NoOp:
7175     case CK_UserDefinedConversion:
7176       return StmtVisitorTy::Visit(E->getSubExpr());
7177 
7178     case CK_LValueToRValue: {
7179       LValue LVal;
7180       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7181         return false;
7182       APValue RVal;
7183       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7184       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7185                                           LVal, RVal))
7186         return false;
7187       return DerivedSuccess(RVal, E);
7188     }
7189     case CK_LValueToRValueBitCast: {
7190       APValue DestValue, SourceValue;
7191       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7192         return false;
7193       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7194         return false;
7195       return DerivedSuccess(DestValue, E);
7196     }
7197 
7198     case CK_AddressSpaceConversion: {
7199       APValue Value;
7200       if (!Evaluate(Value, Info, E->getSubExpr()))
7201         return false;
7202       return DerivedSuccess(Value, E);
7203     }
7204     }
7205 
7206     return Error(E);
7207   }
7208 
7209   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7210     return VisitUnaryPostIncDec(UO);
7211   }
7212   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7213     return VisitUnaryPostIncDec(UO);
7214   }
7215   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7216     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7217       return Error(UO);
7218 
7219     LValue LVal;
7220     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7221       return false;
7222     APValue RVal;
7223     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7224                       UO->isIncrementOp(), &RVal))
7225       return false;
7226     return DerivedSuccess(RVal, UO);
7227   }
7228 
7229   bool VisitStmtExpr(const StmtExpr *E) {
7230     // We will have checked the full-expressions inside the statement expression
7231     // when they were completed, and don't need to check them again now.
7232     if (Info.checkingForUndefinedBehavior())
7233       return Error(E);
7234 
7235     const CompoundStmt *CS = E->getSubStmt();
7236     if (CS->body_empty())
7237       return true;
7238 
7239     BlockScopeRAII Scope(Info);
7240     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7241                                            BE = CS->body_end();
7242          /**/; ++BI) {
7243       if (BI + 1 == BE) {
7244         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7245         if (!FinalExpr) {
7246           Info.FFDiag((*BI)->getBeginLoc(),
7247                       diag::note_constexpr_stmt_expr_unsupported);
7248           return false;
7249         }
7250         return this->Visit(FinalExpr) && Scope.destroy();
7251       }
7252 
7253       APValue ReturnValue;
7254       StmtResult Result = { ReturnValue, nullptr };
7255       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7256       if (ESR != ESR_Succeeded) {
7257         // FIXME: If the statement-expression terminated due to 'return',
7258         // 'break', or 'continue', it would be nice to propagate that to
7259         // the outer statement evaluation rather than bailing out.
7260         if (ESR != ESR_Failed)
7261           Info.FFDiag((*BI)->getBeginLoc(),
7262                       diag::note_constexpr_stmt_expr_unsupported);
7263         return false;
7264       }
7265     }
7266 
7267     llvm_unreachable("Return from function from the loop above.");
7268   }
7269 
7270   /// Visit a value which is evaluated, but whose value is ignored.
7271   void VisitIgnoredValue(const Expr *E) {
7272     EvaluateIgnoredValue(Info, E);
7273   }
7274 
7275   /// Potentially visit a MemberExpr's base expression.
7276   void VisitIgnoredBaseExpression(const Expr *E) {
7277     // While MSVC doesn't evaluate the base expression, it does diagnose the
7278     // presence of side-effecting behavior.
7279     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7280       return;
7281     VisitIgnoredValue(E);
7282   }
7283 };
7284 
7285 } // namespace
7286 
7287 //===----------------------------------------------------------------------===//
7288 // Common base class for lvalue and temporary evaluation.
7289 //===----------------------------------------------------------------------===//
7290 namespace {
7291 template<class Derived>
7292 class LValueExprEvaluatorBase
7293   : public ExprEvaluatorBase<Derived> {
7294 protected:
7295   LValue &Result;
7296   bool InvalidBaseOK;
7297   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7298   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7299 
7300   bool Success(APValue::LValueBase B) {
7301     Result.set(B);
7302     return true;
7303   }
7304 
7305   bool evaluatePointer(const Expr *E, LValue &Result) {
7306     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7307   }
7308 
7309 public:
7310   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7311       : ExprEvaluatorBaseTy(Info), Result(Result),
7312         InvalidBaseOK(InvalidBaseOK) {}
7313 
7314   bool Success(const APValue &V, const Expr *E) {
7315     Result.setFrom(this->Info.Ctx, V);
7316     return true;
7317   }
7318 
7319   bool VisitMemberExpr(const MemberExpr *E) {
7320     // Handle non-static data members.
7321     QualType BaseTy;
7322     bool EvalOK;
7323     if (E->isArrow()) {
7324       EvalOK = evaluatePointer(E->getBase(), Result);
7325       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
7326     } else if (E->getBase()->isRValue()) {
7327       assert(E->getBase()->getType()->isRecordType());
7328       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
7329       BaseTy = E->getBase()->getType();
7330     } else {
7331       EvalOK = this->Visit(E->getBase());
7332       BaseTy = E->getBase()->getType();
7333     }
7334     if (!EvalOK) {
7335       if (!InvalidBaseOK)
7336         return false;
7337       Result.setInvalid(E);
7338       return true;
7339     }
7340 
7341     const ValueDecl *MD = E->getMemberDecl();
7342     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
7343       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7344              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7345       (void)BaseTy;
7346       if (!HandleLValueMember(this->Info, E, Result, FD))
7347         return false;
7348     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
7349       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
7350         return false;
7351     } else
7352       return this->Error(E);
7353 
7354     if (MD->getType()->isReferenceType()) {
7355       APValue RefValue;
7356       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
7357                                           RefValue))
7358         return false;
7359       return Success(RefValue, E);
7360     }
7361     return true;
7362   }
7363 
7364   bool VisitBinaryOperator(const BinaryOperator *E) {
7365     switch (E->getOpcode()) {
7366     default:
7367       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7368 
7369     case BO_PtrMemD:
7370     case BO_PtrMemI:
7371       return HandleMemberPointerAccess(this->Info, E, Result);
7372     }
7373   }
7374 
7375   bool VisitCastExpr(const CastExpr *E) {
7376     switch (E->getCastKind()) {
7377     default:
7378       return ExprEvaluatorBaseTy::VisitCastExpr(E);
7379 
7380     case CK_DerivedToBase:
7381     case CK_UncheckedDerivedToBase:
7382       if (!this->Visit(E->getSubExpr()))
7383         return false;
7384 
7385       // Now figure out the necessary offset to add to the base LV to get from
7386       // the derived class to the base class.
7387       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
7388                                   Result);
7389     }
7390   }
7391 };
7392 }
7393 
7394 //===----------------------------------------------------------------------===//
7395 // LValue Evaluation
7396 //
7397 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
7398 // function designators (in C), decl references to void objects (in C), and
7399 // temporaries (if building with -Wno-address-of-temporary).
7400 //
7401 // LValue evaluation produces values comprising a base expression of one of the
7402 // following types:
7403 // - Declarations
7404 //  * VarDecl
7405 //  * FunctionDecl
7406 // - Literals
7407 //  * CompoundLiteralExpr in C (and in global scope in C++)
7408 //  * StringLiteral
7409 //  * PredefinedExpr
7410 //  * ObjCStringLiteralExpr
7411 //  * ObjCEncodeExpr
7412 //  * AddrLabelExpr
7413 //  * BlockExpr
7414 //  * CallExpr for a MakeStringConstant builtin
7415 // - typeid(T) expressions, as TypeInfoLValues
7416 // - Locals and temporaries
7417 //  * MaterializeTemporaryExpr
7418 //  * Any Expr, with a CallIndex indicating the function in which the temporary
7419 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
7420 //    from the AST (FIXME).
7421 //  * A MaterializeTemporaryExpr that has static storage duration, with no
7422 //    CallIndex, for a lifetime-extended temporary.
7423 //  * The ConstantExpr that is currently being evaluated during evaluation of an
7424 //    immediate invocation.
7425 // plus an offset in bytes.
7426 //===----------------------------------------------------------------------===//
7427 namespace {
7428 class LValueExprEvaluator
7429   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
7430 public:
7431   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
7432     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
7433 
7434   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
7435   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
7436 
7437   bool VisitDeclRefExpr(const DeclRefExpr *E);
7438   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
7439   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
7440   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
7441   bool VisitMemberExpr(const MemberExpr *E);
7442   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
7443   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
7444   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
7445   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
7446   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
7447   bool VisitUnaryDeref(const UnaryOperator *E);
7448   bool VisitUnaryReal(const UnaryOperator *E);
7449   bool VisitUnaryImag(const UnaryOperator *E);
7450   bool VisitUnaryPreInc(const UnaryOperator *UO) {
7451     return VisitUnaryPreIncDec(UO);
7452   }
7453   bool VisitUnaryPreDec(const UnaryOperator *UO) {
7454     return VisitUnaryPreIncDec(UO);
7455   }
7456   bool VisitBinAssign(const BinaryOperator *BO);
7457   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
7458 
7459   bool VisitCastExpr(const CastExpr *E) {
7460     switch (E->getCastKind()) {
7461     default:
7462       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
7463 
7464     case CK_LValueBitCast:
7465       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7466       if (!Visit(E->getSubExpr()))
7467         return false;
7468       Result.Designator.setInvalid();
7469       return true;
7470 
7471     case CK_BaseToDerived:
7472       if (!Visit(E->getSubExpr()))
7473         return false;
7474       return HandleBaseToDerivedCast(Info, E, Result);
7475 
7476     case CK_Dynamic:
7477       if (!Visit(E->getSubExpr()))
7478         return false;
7479       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
7480     }
7481   }
7482 };
7483 } // end anonymous namespace
7484 
7485 /// Evaluate an expression as an lvalue. This can be legitimately called on
7486 /// expressions which are not glvalues, in three cases:
7487 ///  * function designators in C, and
7488 ///  * "extern void" objects
7489 ///  * @selector() expressions in Objective-C
7490 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
7491                            bool InvalidBaseOK) {
7492   assert(E->isGLValue() || E->getType()->isFunctionType() ||
7493          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
7494   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
7495 }
7496 
7497 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
7498   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
7499     return Success(FD);
7500   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
7501     return VisitVarDecl(E, VD);
7502   if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
7503     return Visit(BD->getBinding());
7504   return Error(E);
7505 }
7506 
7507 
7508 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
7509 
7510   // If we are within a lambda's call operator, check whether the 'VD' referred
7511   // to within 'E' actually represents a lambda-capture that maps to a
7512   // data-member/field within the closure object, and if so, evaluate to the
7513   // field or what the field refers to.
7514   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
7515       isa<DeclRefExpr>(E) &&
7516       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
7517     // We don't always have a complete capture-map when checking or inferring if
7518     // the function call operator meets the requirements of a constexpr function
7519     // - but we don't need to evaluate the captures to determine constexprness
7520     // (dcl.constexpr C++17).
7521     if (Info.checkingPotentialConstantExpression())
7522       return false;
7523 
7524     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
7525       // Start with 'Result' referring to the complete closure object...
7526       Result = *Info.CurrentCall->This;
7527       // ... then update it to refer to the field of the closure object
7528       // that represents the capture.
7529       if (!HandleLValueMember(Info, E, Result, FD))
7530         return false;
7531       // And if the field is of reference type, update 'Result' to refer to what
7532       // the field refers to.
7533       if (FD->getType()->isReferenceType()) {
7534         APValue RVal;
7535         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
7536                                             RVal))
7537           return false;
7538         Result.setFrom(Info.Ctx, RVal);
7539       }
7540       return true;
7541     }
7542   }
7543   CallStackFrame *Frame = nullptr;
7544   if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
7545     // Only if a local variable was declared in the function currently being
7546     // evaluated, do we expect to be able to find its value in the current
7547     // frame. (Otherwise it was likely declared in an enclosing context and
7548     // could either have a valid evaluatable value (for e.g. a constexpr
7549     // variable) or be ill-formed (and trigger an appropriate evaluation
7550     // diagnostic)).
7551     if (Info.CurrentCall->Callee &&
7552         Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
7553       Frame = Info.CurrentCall;
7554     }
7555   }
7556 
7557   if (!VD->getType()->isReferenceType()) {
7558     if (Frame) {
7559       Result.set({VD, Frame->Index,
7560                   Info.CurrentCall->getCurrentTemporaryVersion(VD)});
7561       return true;
7562     }
7563     return Success(VD);
7564   }
7565 
7566   APValue *V;
7567   if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
7568     return false;
7569   if (!V->hasValue()) {
7570     // FIXME: Is it possible for V to be indeterminate here? If so, we should
7571     // adjust the diagnostic to say that.
7572     if (!Info.checkingPotentialConstantExpression())
7573       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
7574     return false;
7575   }
7576   return Success(*V, E);
7577 }
7578 
7579 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
7580     const MaterializeTemporaryExpr *E) {
7581   // Walk through the expression to find the materialized temporary itself.
7582   SmallVector<const Expr *, 2> CommaLHSs;
7583   SmallVector<SubobjectAdjustment, 2> Adjustments;
7584   const Expr *Inner =
7585       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
7586 
7587   // If we passed any comma operators, evaluate their LHSs.
7588   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
7589     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
7590       return false;
7591 
7592   // A materialized temporary with static storage duration can appear within the
7593   // result of a constant expression evaluation, so we need to preserve its
7594   // value for use outside this evaluation.
7595   APValue *Value;
7596   if (E->getStorageDuration() == SD_Static) {
7597     Value = E->getOrCreateValue(true);
7598     *Value = APValue();
7599     Result.set(E);
7600   } else {
7601     Value = &Info.CurrentCall->createTemporary(
7602         E, E->getType(), E->getStorageDuration() == SD_Automatic, Result);
7603   }
7604 
7605   QualType Type = Inner->getType();
7606 
7607   // Materialize the temporary itself.
7608   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
7609     *Value = APValue();
7610     return false;
7611   }
7612 
7613   // Adjust our lvalue to refer to the desired subobject.
7614   for (unsigned I = Adjustments.size(); I != 0; /**/) {
7615     --I;
7616     switch (Adjustments[I].Kind) {
7617     case SubobjectAdjustment::DerivedToBaseAdjustment:
7618       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
7619                                 Type, Result))
7620         return false;
7621       Type = Adjustments[I].DerivedToBase.BasePath->getType();
7622       break;
7623 
7624     case SubobjectAdjustment::FieldAdjustment:
7625       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
7626         return false;
7627       Type = Adjustments[I].Field->getType();
7628       break;
7629 
7630     case SubobjectAdjustment::MemberPointerAdjustment:
7631       if (!HandleMemberPointerAccess(this->Info, Type, Result,
7632                                      Adjustments[I].Ptr.RHS))
7633         return false;
7634       Type = Adjustments[I].Ptr.MPT->getPointeeType();
7635       break;
7636     }
7637   }
7638 
7639   return true;
7640 }
7641 
7642 bool
7643 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7644   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
7645          "lvalue compound literal in c++?");
7646   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
7647   // only see this when folding in C, so there's no standard to follow here.
7648   return Success(E);
7649 }
7650 
7651 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
7652   TypeInfoLValue TypeInfo;
7653 
7654   if (!E->isPotentiallyEvaluated()) {
7655     if (E->isTypeOperand())
7656       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
7657     else
7658       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
7659   } else {
7660     if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
7661       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
7662         << E->getExprOperand()->getType()
7663         << E->getExprOperand()->getSourceRange();
7664     }
7665 
7666     if (!Visit(E->getExprOperand()))
7667       return false;
7668 
7669     Optional<DynamicType> DynType =
7670         ComputeDynamicType(Info, E, Result, AK_TypeId);
7671     if (!DynType)
7672       return false;
7673 
7674     TypeInfo =
7675         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
7676   }
7677 
7678   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
7679 }
7680 
7681 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
7682   return Success(E);
7683 }
7684 
7685 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
7686   // Handle static data members.
7687   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
7688     VisitIgnoredBaseExpression(E->getBase());
7689     return VisitVarDecl(E, VD);
7690   }
7691 
7692   // Handle static member functions.
7693   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
7694     if (MD->isStatic()) {
7695       VisitIgnoredBaseExpression(E->getBase());
7696       return Success(MD);
7697     }
7698   }
7699 
7700   // Handle non-static data members.
7701   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
7702 }
7703 
7704 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
7705   // FIXME: Deal with vectors as array subscript bases.
7706   if (E->getBase()->getType()->isVectorType())
7707     return Error(E);
7708 
7709   bool Success = true;
7710   if (!evaluatePointer(E->getBase(), Result)) {
7711     if (!Info.noteFailure())
7712       return false;
7713     Success = false;
7714   }
7715 
7716   APSInt Index;
7717   if (!EvaluateInteger(E->getIdx(), Index, Info))
7718     return false;
7719 
7720   return Success &&
7721          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
7722 }
7723 
7724 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
7725   return evaluatePointer(E->getSubExpr(), Result);
7726 }
7727 
7728 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7729   if (!Visit(E->getSubExpr()))
7730     return false;
7731   // __real is a no-op on scalar lvalues.
7732   if (E->getSubExpr()->getType()->isAnyComplexType())
7733     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
7734   return true;
7735 }
7736 
7737 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7738   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
7739          "lvalue __imag__ on scalar?");
7740   if (!Visit(E->getSubExpr()))
7741     return false;
7742   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
7743   return true;
7744 }
7745 
7746 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
7747   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7748     return Error(UO);
7749 
7750   if (!this->Visit(UO->getSubExpr()))
7751     return false;
7752 
7753   return handleIncDec(
7754       this->Info, UO, Result, UO->getSubExpr()->getType(),
7755       UO->isIncrementOp(), nullptr);
7756 }
7757 
7758 bool LValueExprEvaluator::VisitCompoundAssignOperator(
7759     const CompoundAssignOperator *CAO) {
7760   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7761     return Error(CAO);
7762 
7763   APValue RHS;
7764 
7765   // The overall lvalue result is the result of evaluating the LHS.
7766   if (!this->Visit(CAO->getLHS())) {
7767     if (Info.noteFailure())
7768       Evaluate(RHS, this->Info, CAO->getRHS());
7769     return false;
7770   }
7771 
7772   if (!Evaluate(RHS, this->Info, CAO->getRHS()))
7773     return false;
7774 
7775   return handleCompoundAssignment(
7776       this->Info, CAO,
7777       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
7778       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
7779 }
7780 
7781 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
7782   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7783     return Error(E);
7784 
7785   APValue NewVal;
7786 
7787   if (!this->Visit(E->getLHS())) {
7788     if (Info.noteFailure())
7789       Evaluate(NewVal, this->Info, E->getRHS());
7790     return false;
7791   }
7792 
7793   if (!Evaluate(NewVal, this->Info, E->getRHS()))
7794     return false;
7795 
7796   if (Info.getLangOpts().CPlusPlus2a &&
7797       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
7798     return false;
7799 
7800   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
7801                           NewVal);
7802 }
7803 
7804 //===----------------------------------------------------------------------===//
7805 // Pointer Evaluation
7806 //===----------------------------------------------------------------------===//
7807 
7808 /// Attempts to compute the number of bytes available at the pointer
7809 /// returned by a function with the alloc_size attribute. Returns true if we
7810 /// were successful. Places an unsigned number into `Result`.
7811 ///
7812 /// This expects the given CallExpr to be a call to a function with an
7813 /// alloc_size attribute.
7814 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
7815                                             const CallExpr *Call,
7816                                             llvm::APInt &Result) {
7817   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
7818 
7819   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
7820   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
7821   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
7822   if (Call->getNumArgs() <= SizeArgNo)
7823     return false;
7824 
7825   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
7826     Expr::EvalResult ExprResult;
7827     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
7828       return false;
7829     Into = ExprResult.Val.getInt();
7830     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
7831       return false;
7832     Into = Into.zextOrSelf(BitsInSizeT);
7833     return true;
7834   };
7835 
7836   APSInt SizeOfElem;
7837   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
7838     return false;
7839 
7840   if (!AllocSize->getNumElemsParam().isValid()) {
7841     Result = std::move(SizeOfElem);
7842     return true;
7843   }
7844 
7845   APSInt NumberOfElems;
7846   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
7847   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
7848     return false;
7849 
7850   bool Overflow;
7851   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
7852   if (Overflow)
7853     return false;
7854 
7855   Result = std::move(BytesAvailable);
7856   return true;
7857 }
7858 
7859 /// Convenience function. LVal's base must be a call to an alloc_size
7860 /// function.
7861 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
7862                                             const LValue &LVal,
7863                                             llvm::APInt &Result) {
7864   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7865          "Can't get the size of a non alloc_size function");
7866   const auto *Base = LVal.getLValueBase().get<const Expr *>();
7867   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
7868   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
7869 }
7870 
7871 /// Attempts to evaluate the given LValueBase as the result of a call to
7872 /// a function with the alloc_size attribute. If it was possible to do so, this
7873 /// function will return true, make Result's Base point to said function call,
7874 /// and mark Result's Base as invalid.
7875 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
7876                                       LValue &Result) {
7877   if (Base.isNull())
7878     return false;
7879 
7880   // Because we do no form of static analysis, we only support const variables.
7881   //
7882   // Additionally, we can't support parameters, nor can we support static
7883   // variables (in the latter case, use-before-assign isn't UB; in the former,
7884   // we have no clue what they'll be assigned to).
7885   const auto *VD =
7886       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
7887   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
7888     return false;
7889 
7890   const Expr *Init = VD->getAnyInitializer();
7891   if (!Init)
7892     return false;
7893 
7894   const Expr *E = Init->IgnoreParens();
7895   if (!tryUnwrapAllocSizeCall(E))
7896     return false;
7897 
7898   // Store E instead of E unwrapped so that the type of the LValue's base is
7899   // what the user wanted.
7900   Result.setInvalid(E);
7901 
7902   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
7903   Result.addUnsizedArray(Info, E, Pointee);
7904   return true;
7905 }
7906 
7907 namespace {
7908 class PointerExprEvaluator
7909   : public ExprEvaluatorBase<PointerExprEvaluator> {
7910   LValue &Result;
7911   bool InvalidBaseOK;
7912 
7913   bool Success(const Expr *E) {
7914     Result.set(E);
7915     return true;
7916   }
7917 
7918   bool evaluateLValue(const Expr *E, LValue &Result) {
7919     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
7920   }
7921 
7922   bool evaluatePointer(const Expr *E, LValue &Result) {
7923     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
7924   }
7925 
7926   bool visitNonBuiltinCallExpr(const CallExpr *E);
7927 public:
7928 
7929   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
7930       : ExprEvaluatorBaseTy(info), Result(Result),
7931         InvalidBaseOK(InvalidBaseOK) {}
7932 
7933   bool Success(const APValue &V, const Expr *E) {
7934     Result.setFrom(Info.Ctx, V);
7935     return true;
7936   }
7937   bool ZeroInitialization(const Expr *E) {
7938     Result.setNull(Info.Ctx, E->getType());
7939     return true;
7940   }
7941 
7942   bool VisitBinaryOperator(const BinaryOperator *E);
7943   bool VisitCastExpr(const CastExpr* E);
7944   bool VisitUnaryAddrOf(const UnaryOperator *E);
7945   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
7946       { return Success(E); }
7947   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
7948     if (E->isExpressibleAsConstantInitializer())
7949       return Success(E);
7950     if (Info.noteFailure())
7951       EvaluateIgnoredValue(Info, E->getSubExpr());
7952     return Error(E);
7953   }
7954   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
7955       { return Success(E); }
7956   bool VisitCallExpr(const CallExpr *E);
7957   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
7958   bool VisitBlockExpr(const BlockExpr *E) {
7959     if (!E->getBlockDecl()->hasCaptures())
7960       return Success(E);
7961     return Error(E);
7962   }
7963   bool VisitCXXThisExpr(const CXXThisExpr *E) {
7964     // Can't look at 'this' when checking a potential constant expression.
7965     if (Info.checkingPotentialConstantExpression())
7966       return false;
7967     if (!Info.CurrentCall->This) {
7968       if (Info.getLangOpts().CPlusPlus11)
7969         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
7970       else
7971         Info.FFDiag(E);
7972       return false;
7973     }
7974     Result = *Info.CurrentCall->This;
7975     // If we are inside a lambda's call operator, the 'this' expression refers
7976     // to the enclosing '*this' object (either by value or reference) which is
7977     // either copied into the closure object's field that represents the '*this'
7978     // or refers to '*this'.
7979     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
7980       // Ensure we actually have captured 'this'. (an error will have
7981       // been previously reported if not).
7982       if (!Info.CurrentCall->LambdaThisCaptureField)
7983         return false;
7984 
7985       // Update 'Result' to refer to the data member/field of the closure object
7986       // that represents the '*this' capture.
7987       if (!HandleLValueMember(Info, E, Result,
7988                              Info.CurrentCall->LambdaThisCaptureField))
7989         return false;
7990       // If we captured '*this' by reference, replace the field with its referent.
7991       if (Info.CurrentCall->LambdaThisCaptureField->getType()
7992               ->isPointerType()) {
7993         APValue RVal;
7994         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
7995                                             RVal))
7996           return false;
7997 
7998         Result.setFrom(Info.Ctx, RVal);
7999       }
8000     }
8001     return true;
8002   }
8003 
8004   bool VisitCXXNewExpr(const CXXNewExpr *E);
8005 
8006   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8007     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
8008     APValue LValResult = E->EvaluateInContext(
8009         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8010     Result.setFrom(Info.Ctx, LValResult);
8011     return true;
8012   }
8013 
8014   // FIXME: Missing: @protocol, @selector
8015 };
8016 } // end anonymous namespace
8017 
8018 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8019                             bool InvalidBaseOK) {
8020   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
8021   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8022 }
8023 
8024 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8025   if (E->getOpcode() != BO_Add &&
8026       E->getOpcode() != BO_Sub)
8027     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8028 
8029   const Expr *PExp = E->getLHS();
8030   const Expr *IExp = E->getRHS();
8031   if (IExp->getType()->isPointerType())
8032     std::swap(PExp, IExp);
8033 
8034   bool EvalPtrOK = evaluatePointer(PExp, Result);
8035   if (!EvalPtrOK && !Info.noteFailure())
8036     return false;
8037 
8038   llvm::APSInt Offset;
8039   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8040     return false;
8041 
8042   if (E->getOpcode() == BO_Sub)
8043     negateAsSigned(Offset);
8044 
8045   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8046   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8047 }
8048 
8049 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8050   return evaluateLValue(E->getSubExpr(), Result);
8051 }
8052 
8053 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8054   const Expr *SubExpr = E->getSubExpr();
8055 
8056   switch (E->getCastKind()) {
8057   default:
8058     break;
8059   case CK_BitCast:
8060   case CK_CPointerToObjCPointerCast:
8061   case CK_BlockPointerToObjCPointerCast:
8062   case CK_AnyPointerToBlockPointerCast:
8063   case CK_AddressSpaceConversion:
8064     if (!Visit(SubExpr))
8065       return false;
8066     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8067     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8068     // also static_casts, but we disallow them as a resolution to DR1312.
8069     if (!E->getType()->isVoidPointerType()) {
8070       if (!Result.InvalidBase && !Result.Designator.Invalid &&
8071           !Result.IsNullPtr &&
8072           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8073                                           E->getType()->getPointeeType()) &&
8074           Info.getStdAllocatorCaller("allocate")) {
8075         // Inside a call to std::allocator::allocate and friends, we permit
8076         // casting from void* back to cv1 T* for a pointer that points to a
8077         // cv2 T.
8078       } else {
8079         Result.Designator.setInvalid();
8080         if (SubExpr->getType()->isVoidPointerType())
8081           CCEDiag(E, diag::note_constexpr_invalid_cast)
8082             << 3 << SubExpr->getType();
8083         else
8084           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8085       }
8086     }
8087     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8088       ZeroInitialization(E);
8089     return true;
8090 
8091   case CK_DerivedToBase:
8092   case CK_UncheckedDerivedToBase:
8093     if (!evaluatePointer(E->getSubExpr(), Result))
8094       return false;
8095     if (!Result.Base && Result.Offset.isZero())
8096       return true;
8097 
8098     // Now figure out the necessary offset to add to the base LV to get from
8099     // the derived class to the base class.
8100     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8101                                   castAs<PointerType>()->getPointeeType(),
8102                                 Result);
8103 
8104   case CK_BaseToDerived:
8105     if (!Visit(E->getSubExpr()))
8106       return false;
8107     if (!Result.Base && Result.Offset.isZero())
8108       return true;
8109     return HandleBaseToDerivedCast(Info, E, Result);
8110 
8111   case CK_Dynamic:
8112     if (!Visit(E->getSubExpr()))
8113       return false;
8114     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8115 
8116   case CK_NullToPointer:
8117     VisitIgnoredValue(E->getSubExpr());
8118     return ZeroInitialization(E);
8119 
8120   case CK_IntegralToPointer: {
8121     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8122 
8123     APValue Value;
8124     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8125       break;
8126 
8127     if (Value.isInt()) {
8128       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8129       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8130       Result.Base = (Expr*)nullptr;
8131       Result.InvalidBase = false;
8132       Result.Offset = CharUnits::fromQuantity(N);
8133       Result.Designator.setInvalid();
8134       Result.IsNullPtr = false;
8135       return true;
8136     } else {
8137       // Cast is of an lvalue, no need to change value.
8138       Result.setFrom(Info.Ctx, Value);
8139       return true;
8140     }
8141   }
8142 
8143   case CK_ArrayToPointerDecay: {
8144     if (SubExpr->isGLValue()) {
8145       if (!evaluateLValue(SubExpr, Result))
8146         return false;
8147     } else {
8148       APValue &Value = Info.CurrentCall->createTemporary(
8149           SubExpr, SubExpr->getType(), false, Result);
8150       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8151         return false;
8152     }
8153     // The result is a pointer to the first element of the array.
8154     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8155     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8156       Result.addArray(Info, E, CAT);
8157     else
8158       Result.addUnsizedArray(Info, E, AT->getElementType());
8159     return true;
8160   }
8161 
8162   case CK_FunctionToPointerDecay:
8163     return evaluateLValue(SubExpr, Result);
8164 
8165   case CK_LValueToRValue: {
8166     LValue LVal;
8167     if (!evaluateLValue(E->getSubExpr(), LVal))
8168       return false;
8169 
8170     APValue RVal;
8171     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8172     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8173                                         LVal, RVal))
8174       return InvalidBaseOK &&
8175              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8176     return Success(RVal, E);
8177   }
8178   }
8179 
8180   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8181 }
8182 
8183 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8184                                 UnaryExprOrTypeTrait ExprKind) {
8185   // C++ [expr.alignof]p3:
8186   //     When alignof is applied to a reference type, the result is the
8187   //     alignment of the referenced type.
8188   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8189     T = Ref->getPointeeType();
8190 
8191   if (T.getQualifiers().hasUnaligned())
8192     return CharUnits::One();
8193 
8194   const bool AlignOfReturnsPreferred =
8195       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8196 
8197   // __alignof is defined to return the preferred alignment.
8198   // Before 8, clang returned the preferred alignment for alignof and _Alignof
8199   // as well.
8200   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8201     return Info.Ctx.toCharUnitsFromBits(
8202       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8203   // alignof and _Alignof are defined to return the ABI alignment.
8204   else if (ExprKind == UETT_AlignOf)
8205     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8206   else
8207     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8208 }
8209 
8210 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8211                                 UnaryExprOrTypeTrait ExprKind) {
8212   E = E->IgnoreParens();
8213 
8214   // The kinds of expressions that we have special-case logic here for
8215   // should be kept up to date with the special checks for those
8216   // expressions in Sema.
8217 
8218   // alignof decl is always accepted, even if it doesn't make sense: we default
8219   // to 1 in those cases.
8220   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8221     return Info.Ctx.getDeclAlign(DRE->getDecl(),
8222                                  /*RefAsPointee*/true);
8223 
8224   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8225     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8226                                  /*RefAsPointee*/true);
8227 
8228   return GetAlignOfType(Info, E->getType(), ExprKind);
8229 }
8230 
8231 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
8232   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
8233     return Info.Ctx.getDeclAlign(VD);
8234   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
8235     return GetAlignOfExpr(Info, E, UETT_AlignOf);
8236   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
8237 }
8238 
8239 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
8240 /// __builtin_is_aligned and __builtin_assume_aligned.
8241 static bool getAlignmentArgument(const Expr *E, QualType ForType,
8242                                  EvalInfo &Info, APSInt &Alignment) {
8243   if (!EvaluateInteger(E, Alignment, Info))
8244     return false;
8245   if (Alignment < 0 || !Alignment.isPowerOf2()) {
8246     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
8247     return false;
8248   }
8249   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
8250   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
8251   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
8252     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
8253         << MaxValue << ForType << Alignment;
8254     return false;
8255   }
8256   // Ensure both alignment and source value have the same bit width so that we
8257   // don't assert when computing the resulting value.
8258   APSInt ExtAlignment =
8259       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
8260   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
8261          "Alignment should not be changed by ext/trunc");
8262   Alignment = ExtAlignment;
8263   assert(Alignment.getBitWidth() == SrcWidth);
8264   return true;
8265 }
8266 
8267 // To be clear: this happily visits unsupported builtins. Better name welcomed.
8268 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8269   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8270     return true;
8271 
8272   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
8273     return false;
8274 
8275   Result.setInvalid(E);
8276   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
8277   Result.addUnsizedArray(Info, E, PointeeTy);
8278   return true;
8279 }
8280 
8281 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
8282   if (IsStringLiteralCall(E))
8283     return Success(E);
8284 
8285   if (unsigned BuiltinOp = E->getBuiltinCallee())
8286     return VisitBuiltinCallExpr(E, BuiltinOp);
8287 
8288   return visitNonBuiltinCallExpr(E);
8289 }
8290 
8291 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8292                                                 unsigned BuiltinOp) {
8293   switch (BuiltinOp) {
8294   case Builtin::BI__builtin_addressof:
8295     return evaluateLValue(E->getArg(0), Result);
8296   case Builtin::BI__builtin_assume_aligned: {
8297     // We need to be very careful here because: if the pointer does not have the
8298     // asserted alignment, then the behavior is undefined, and undefined
8299     // behavior is non-constant.
8300     if (!evaluatePointer(E->getArg(0), Result))
8301       return false;
8302 
8303     LValue OffsetResult(Result);
8304     APSInt Alignment;
8305     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8306                               Alignment))
8307       return false;
8308     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
8309 
8310     if (E->getNumArgs() > 2) {
8311       APSInt Offset;
8312       if (!EvaluateInteger(E->getArg(2), Offset, Info))
8313         return false;
8314 
8315       int64_t AdditionalOffset = -Offset.getZExtValue();
8316       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
8317     }
8318 
8319     // If there is a base object, then it must have the correct alignment.
8320     if (OffsetResult.Base) {
8321       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
8322 
8323       if (BaseAlignment < Align) {
8324         Result.Designator.setInvalid();
8325         // FIXME: Add support to Diagnostic for long / long long.
8326         CCEDiag(E->getArg(0),
8327                 diag::note_constexpr_baa_insufficient_alignment) << 0
8328           << (unsigned)BaseAlignment.getQuantity()
8329           << (unsigned)Align.getQuantity();
8330         return false;
8331       }
8332     }
8333 
8334     // The offset must also have the correct alignment.
8335     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
8336       Result.Designator.setInvalid();
8337 
8338       (OffsetResult.Base
8339            ? CCEDiag(E->getArg(0),
8340                      diag::note_constexpr_baa_insufficient_alignment) << 1
8341            : CCEDiag(E->getArg(0),
8342                      diag::note_constexpr_baa_value_insufficient_alignment))
8343         << (int)OffsetResult.Offset.getQuantity()
8344         << (unsigned)Align.getQuantity();
8345       return false;
8346     }
8347 
8348     return true;
8349   }
8350   case Builtin::BI__builtin_align_up:
8351   case Builtin::BI__builtin_align_down: {
8352     if (!evaluatePointer(E->getArg(0), Result))
8353       return false;
8354     APSInt Alignment;
8355     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8356                               Alignment))
8357       return false;
8358     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
8359     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
8360     // For align_up/align_down, we can return the same value if the alignment
8361     // is known to be greater or equal to the requested value.
8362     if (PtrAlign.getQuantity() >= Alignment)
8363       return true;
8364 
8365     // The alignment could be greater than the minimum at run-time, so we cannot
8366     // infer much about the resulting pointer value. One case is possible:
8367     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
8368     // can infer the correct index if the requested alignment is smaller than
8369     // the base alignment so we can perform the computation on the offset.
8370     if (BaseAlignment.getQuantity() >= Alignment) {
8371       assert(Alignment.getBitWidth() <= 64 &&
8372              "Cannot handle > 64-bit address-space");
8373       uint64_t Alignment64 = Alignment.getZExtValue();
8374       CharUnits NewOffset = CharUnits::fromQuantity(
8375           BuiltinOp == Builtin::BI__builtin_align_down
8376               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
8377               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
8378       Result.adjustOffset(NewOffset - Result.Offset);
8379       // TODO: diagnose out-of-bounds values/only allow for arrays?
8380       return true;
8381     }
8382     // Otherwise, we cannot constant-evaluate the result.
8383     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
8384         << Alignment;
8385     return false;
8386   }
8387   case Builtin::BI__builtin_operator_new:
8388     return HandleOperatorNewCall(Info, E, Result);
8389   case Builtin::BI__builtin_launder:
8390     return evaluatePointer(E->getArg(0), Result);
8391   case Builtin::BIstrchr:
8392   case Builtin::BIwcschr:
8393   case Builtin::BImemchr:
8394   case Builtin::BIwmemchr:
8395     if (Info.getLangOpts().CPlusPlus11)
8396       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8397         << /*isConstexpr*/0 << /*isConstructor*/0
8398         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8399     else
8400       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8401     LLVM_FALLTHROUGH;
8402   case Builtin::BI__builtin_strchr:
8403   case Builtin::BI__builtin_wcschr:
8404   case Builtin::BI__builtin_memchr:
8405   case Builtin::BI__builtin_char_memchr:
8406   case Builtin::BI__builtin_wmemchr: {
8407     if (!Visit(E->getArg(0)))
8408       return false;
8409     APSInt Desired;
8410     if (!EvaluateInteger(E->getArg(1), Desired, Info))
8411       return false;
8412     uint64_t MaxLength = uint64_t(-1);
8413     if (BuiltinOp != Builtin::BIstrchr &&
8414         BuiltinOp != Builtin::BIwcschr &&
8415         BuiltinOp != Builtin::BI__builtin_strchr &&
8416         BuiltinOp != Builtin::BI__builtin_wcschr) {
8417       APSInt N;
8418       if (!EvaluateInteger(E->getArg(2), N, Info))
8419         return false;
8420       MaxLength = N.getExtValue();
8421     }
8422     // We cannot find the value if there are no candidates to match against.
8423     if (MaxLength == 0u)
8424       return ZeroInitialization(E);
8425     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8426         Result.Designator.Invalid)
8427       return false;
8428     QualType CharTy = Result.Designator.getType(Info.Ctx);
8429     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
8430                      BuiltinOp == Builtin::BI__builtin_memchr;
8431     assert(IsRawByte ||
8432            Info.Ctx.hasSameUnqualifiedType(
8433                CharTy, E->getArg(0)->getType()->getPointeeType()));
8434     // Pointers to const void may point to objects of incomplete type.
8435     if (IsRawByte && CharTy->isIncompleteType()) {
8436       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
8437       return false;
8438     }
8439     // Give up on byte-oriented matching against multibyte elements.
8440     // FIXME: We can compare the bytes in the correct order.
8441     if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
8442       return false;
8443     // Figure out what value we're actually looking for (after converting to
8444     // the corresponding unsigned type if necessary).
8445     uint64_t DesiredVal;
8446     bool StopAtNull = false;
8447     switch (BuiltinOp) {
8448     case Builtin::BIstrchr:
8449     case Builtin::BI__builtin_strchr:
8450       // strchr compares directly to the passed integer, and therefore
8451       // always fails if given an int that is not a char.
8452       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
8453                                                   E->getArg(1)->getType(),
8454                                                   Desired),
8455                                Desired))
8456         return ZeroInitialization(E);
8457       StopAtNull = true;
8458       LLVM_FALLTHROUGH;
8459     case Builtin::BImemchr:
8460     case Builtin::BI__builtin_memchr:
8461     case Builtin::BI__builtin_char_memchr:
8462       // memchr compares by converting both sides to unsigned char. That's also
8463       // correct for strchr if we get this far (to cope with plain char being
8464       // unsigned in the strchr case).
8465       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
8466       break;
8467 
8468     case Builtin::BIwcschr:
8469     case Builtin::BI__builtin_wcschr:
8470       StopAtNull = true;
8471       LLVM_FALLTHROUGH;
8472     case Builtin::BIwmemchr:
8473     case Builtin::BI__builtin_wmemchr:
8474       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
8475       DesiredVal = Desired.getZExtValue();
8476       break;
8477     }
8478 
8479     for (; MaxLength; --MaxLength) {
8480       APValue Char;
8481       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
8482           !Char.isInt())
8483         return false;
8484       if (Char.getInt().getZExtValue() == DesiredVal)
8485         return true;
8486       if (StopAtNull && !Char.getInt())
8487         break;
8488       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
8489         return false;
8490     }
8491     // Not found: return nullptr.
8492     return ZeroInitialization(E);
8493   }
8494 
8495   case Builtin::BImemcpy:
8496   case Builtin::BImemmove:
8497   case Builtin::BIwmemcpy:
8498   case Builtin::BIwmemmove:
8499     if (Info.getLangOpts().CPlusPlus11)
8500       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8501         << /*isConstexpr*/0 << /*isConstructor*/0
8502         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8503     else
8504       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8505     LLVM_FALLTHROUGH;
8506   case Builtin::BI__builtin_memcpy:
8507   case Builtin::BI__builtin_memmove:
8508   case Builtin::BI__builtin_wmemcpy:
8509   case Builtin::BI__builtin_wmemmove: {
8510     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
8511                  BuiltinOp == Builtin::BIwmemmove ||
8512                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
8513                  BuiltinOp == Builtin::BI__builtin_wmemmove;
8514     bool Move = BuiltinOp == Builtin::BImemmove ||
8515                 BuiltinOp == Builtin::BIwmemmove ||
8516                 BuiltinOp == Builtin::BI__builtin_memmove ||
8517                 BuiltinOp == Builtin::BI__builtin_wmemmove;
8518 
8519     // The result of mem* is the first argument.
8520     if (!Visit(E->getArg(0)))
8521       return false;
8522     LValue Dest = Result;
8523 
8524     LValue Src;
8525     if (!EvaluatePointer(E->getArg(1), Src, Info))
8526       return false;
8527 
8528     APSInt N;
8529     if (!EvaluateInteger(E->getArg(2), N, Info))
8530       return false;
8531     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
8532 
8533     // If the size is zero, we treat this as always being a valid no-op.
8534     // (Even if one of the src and dest pointers is null.)
8535     if (!N)
8536       return true;
8537 
8538     // Otherwise, if either of the operands is null, we can't proceed. Don't
8539     // try to determine the type of the copied objects, because there aren't
8540     // any.
8541     if (!Src.Base || !Dest.Base) {
8542       APValue Val;
8543       (!Src.Base ? Src : Dest).moveInto(Val);
8544       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
8545           << Move << WChar << !!Src.Base
8546           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
8547       return false;
8548     }
8549     if (Src.Designator.Invalid || Dest.Designator.Invalid)
8550       return false;
8551 
8552     // We require that Src and Dest are both pointers to arrays of
8553     // trivially-copyable type. (For the wide version, the designator will be
8554     // invalid if the designated object is not a wchar_t.)
8555     QualType T = Dest.Designator.getType(Info.Ctx);
8556     QualType SrcT = Src.Designator.getType(Info.Ctx);
8557     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
8558       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
8559       return false;
8560     }
8561     if (T->isIncompleteType()) {
8562       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
8563       return false;
8564     }
8565     if (!T.isTriviallyCopyableType(Info.Ctx)) {
8566       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
8567       return false;
8568     }
8569 
8570     // Figure out how many T's we're copying.
8571     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
8572     if (!WChar) {
8573       uint64_t Remainder;
8574       llvm::APInt OrigN = N;
8575       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
8576       if (Remainder) {
8577         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8578             << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
8579             << (unsigned)TSize;
8580         return false;
8581       }
8582     }
8583 
8584     // Check that the copying will remain within the arrays, just so that we
8585     // can give a more meaningful diagnostic. This implicitly also checks that
8586     // N fits into 64 bits.
8587     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
8588     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
8589     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
8590       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8591           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
8592           << N.toString(10, /*Signed*/false);
8593       return false;
8594     }
8595     uint64_t NElems = N.getZExtValue();
8596     uint64_t NBytes = NElems * TSize;
8597 
8598     // Check for overlap.
8599     int Direction = 1;
8600     if (HasSameBase(Src, Dest)) {
8601       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
8602       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
8603       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
8604         // Dest is inside the source region.
8605         if (!Move) {
8606           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8607           return false;
8608         }
8609         // For memmove and friends, copy backwards.
8610         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
8611             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
8612           return false;
8613         Direction = -1;
8614       } else if (!Move && SrcOffset >= DestOffset &&
8615                  SrcOffset - DestOffset < NBytes) {
8616         // Src is inside the destination region for memcpy: invalid.
8617         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8618         return false;
8619       }
8620     }
8621 
8622     while (true) {
8623       APValue Val;
8624       // FIXME: Set WantObjectRepresentation to true if we're copying a
8625       // char-like type?
8626       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
8627           !handleAssignment(Info, E, Dest, T, Val))
8628         return false;
8629       // Do not iterate past the last element; if we're copying backwards, that
8630       // might take us off the start of the array.
8631       if (--NElems == 0)
8632         return true;
8633       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
8634           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
8635         return false;
8636     }
8637   }
8638 
8639   default:
8640     break;
8641   }
8642 
8643   return visitNonBuiltinCallExpr(E);
8644 }
8645 
8646 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
8647                                      APValue &Result, const InitListExpr *ILE,
8648                                      QualType AllocType);
8649 
8650 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
8651   if (!Info.getLangOpts().CPlusPlus2a)
8652     Info.CCEDiag(E, diag::note_constexpr_new);
8653 
8654   // We cannot speculatively evaluate a delete expression.
8655   if (Info.SpeculativeEvaluationDepth)
8656     return false;
8657 
8658   FunctionDecl *OperatorNew = E->getOperatorNew();
8659 
8660   bool IsNothrow = false;
8661   bool IsPlacement = false;
8662   if (OperatorNew->isReservedGlobalPlacementOperator() &&
8663       Info.CurrentCall->isStdFunction() && !E->isArray()) {
8664     // FIXME Support array placement new.
8665     assert(E->getNumPlacementArgs() == 1);
8666     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
8667       return false;
8668     if (Result.Designator.Invalid)
8669       return false;
8670     IsPlacement = true;
8671   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
8672     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
8673         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
8674     return false;
8675   } else if (E->getNumPlacementArgs()) {
8676     // The only new-placement list we support is of the form (std::nothrow).
8677     //
8678     // FIXME: There is no restriction on this, but it's not clear that any
8679     // other form makes any sense. We get here for cases such as:
8680     //
8681     //   new (std::align_val_t{N}) X(int)
8682     //
8683     // (which should presumably be valid only if N is a multiple of
8684     // alignof(int), and in any case can't be deallocated unless N is
8685     // alignof(X) and X has new-extended alignment).
8686     if (E->getNumPlacementArgs() != 1 ||
8687         !E->getPlacementArg(0)->getType()->isNothrowT())
8688       return Error(E, diag::note_constexpr_new_placement);
8689 
8690     LValue Nothrow;
8691     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
8692       return false;
8693     IsNothrow = true;
8694   }
8695 
8696   const Expr *Init = E->getInitializer();
8697   const InitListExpr *ResizedArrayILE = nullptr;
8698 
8699   QualType AllocType = E->getAllocatedType();
8700   if (Optional<const Expr*> ArraySize = E->getArraySize()) {
8701     const Expr *Stripped = *ArraySize;
8702     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
8703          Stripped = ICE->getSubExpr())
8704       if (ICE->getCastKind() != CK_NoOp &&
8705           ICE->getCastKind() != CK_IntegralCast)
8706         break;
8707 
8708     llvm::APSInt ArrayBound;
8709     if (!EvaluateInteger(Stripped, ArrayBound, Info))
8710       return false;
8711 
8712     // C++ [expr.new]p9:
8713     //   The expression is erroneous if:
8714     //   -- [...] its value before converting to size_t [or] applying the
8715     //      second standard conversion sequence is less than zero
8716     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
8717       if (IsNothrow)
8718         return ZeroInitialization(E);
8719 
8720       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
8721           << ArrayBound << (*ArraySize)->getSourceRange();
8722       return false;
8723     }
8724 
8725     //   -- its value is such that the size of the allocated object would
8726     //      exceed the implementation-defined limit
8727     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
8728                                                 ArrayBound) >
8729         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
8730       if (IsNothrow)
8731         return ZeroInitialization(E);
8732 
8733       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
8734         << ArrayBound << (*ArraySize)->getSourceRange();
8735       return false;
8736     }
8737 
8738     //   -- the new-initializer is a braced-init-list and the number of
8739     //      array elements for which initializers are provided [...]
8740     //      exceeds the number of elements to initialize
8741     if (Init) {
8742       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
8743       assert(CAT && "unexpected type for array initializer");
8744 
8745       unsigned Bits =
8746           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
8747       llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
8748       llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
8749       if (InitBound.ugt(AllocBound)) {
8750         if (IsNothrow)
8751           return ZeroInitialization(E);
8752 
8753         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
8754             << AllocBound.toString(10, /*Signed=*/false)
8755             << InitBound.toString(10, /*Signed=*/false)
8756             << (*ArraySize)->getSourceRange();
8757         return false;
8758       }
8759 
8760       // If the sizes differ, we must have an initializer list, and we need
8761       // special handling for this case when we initialize.
8762       if (InitBound != AllocBound)
8763         ResizedArrayILE = cast<InitListExpr>(Init);
8764     }
8765 
8766     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
8767                                               ArrayType::Normal, 0);
8768   } else {
8769     assert(!AllocType->isArrayType() &&
8770            "array allocation with non-array new");
8771   }
8772 
8773   APValue *Val;
8774   if (IsPlacement) {
8775     AccessKinds AK = AK_Construct;
8776     struct FindObjectHandler {
8777       EvalInfo &Info;
8778       const Expr *E;
8779       QualType AllocType;
8780       const AccessKinds AccessKind;
8781       APValue *Value;
8782 
8783       typedef bool result_type;
8784       bool failed() { return false; }
8785       bool found(APValue &Subobj, QualType SubobjType) {
8786         // FIXME: Reject the cases where [basic.life]p8 would not permit the
8787         // old name of the object to be used to name the new object.
8788         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
8789           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
8790             SubobjType << AllocType;
8791           return false;
8792         }
8793         Value = &Subobj;
8794         return true;
8795       }
8796       bool found(APSInt &Value, QualType SubobjType) {
8797         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
8798         return false;
8799       }
8800       bool found(APFloat &Value, QualType SubobjType) {
8801         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
8802         return false;
8803       }
8804     } Handler = {Info, E, AllocType, AK, nullptr};
8805 
8806     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
8807     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
8808       return false;
8809 
8810     Val = Handler.Value;
8811 
8812     // [basic.life]p1:
8813     //   The lifetime of an object o of type T ends when [...] the storage
8814     //   which the object occupies is [...] reused by an object that is not
8815     //   nested within o (6.6.2).
8816     *Val = APValue();
8817   } else {
8818     // Perform the allocation and obtain a pointer to the resulting object.
8819     Val = Info.createHeapAlloc(E, AllocType, Result);
8820     if (!Val)
8821       return false;
8822   }
8823 
8824   if (ResizedArrayILE) {
8825     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
8826                                   AllocType))
8827       return false;
8828   } else if (Init) {
8829     if (!EvaluateInPlace(*Val, Info, Result, Init))
8830       return false;
8831   } else {
8832     *Val = getDefaultInitValue(AllocType);
8833   }
8834 
8835   // Array new returns a pointer to the first element, not a pointer to the
8836   // array.
8837   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
8838     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
8839 
8840   return true;
8841 }
8842 //===----------------------------------------------------------------------===//
8843 // Member Pointer Evaluation
8844 //===----------------------------------------------------------------------===//
8845 
8846 namespace {
8847 class MemberPointerExprEvaluator
8848   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
8849   MemberPtr &Result;
8850 
8851   bool Success(const ValueDecl *D) {
8852     Result = MemberPtr(D);
8853     return true;
8854   }
8855 public:
8856 
8857   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
8858     : ExprEvaluatorBaseTy(Info), Result(Result) {}
8859 
8860   bool Success(const APValue &V, const Expr *E) {
8861     Result.setFrom(V);
8862     return true;
8863   }
8864   bool ZeroInitialization(const Expr *E) {
8865     return Success((const ValueDecl*)nullptr);
8866   }
8867 
8868   bool VisitCastExpr(const CastExpr *E);
8869   bool VisitUnaryAddrOf(const UnaryOperator *E);
8870 };
8871 } // end anonymous namespace
8872 
8873 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
8874                                   EvalInfo &Info) {
8875   assert(E->isRValue() && E->getType()->isMemberPointerType());
8876   return MemberPointerExprEvaluator(Info, Result).Visit(E);
8877 }
8878 
8879 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8880   switch (E->getCastKind()) {
8881   default:
8882     return ExprEvaluatorBaseTy::VisitCastExpr(E);
8883 
8884   case CK_NullToMemberPointer:
8885     VisitIgnoredValue(E->getSubExpr());
8886     return ZeroInitialization(E);
8887 
8888   case CK_BaseToDerivedMemberPointer: {
8889     if (!Visit(E->getSubExpr()))
8890       return false;
8891     if (E->path_empty())
8892       return true;
8893     // Base-to-derived member pointer casts store the path in derived-to-base
8894     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
8895     // the wrong end of the derived->base arc, so stagger the path by one class.
8896     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
8897     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
8898          PathI != PathE; ++PathI) {
8899       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
8900       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
8901       if (!Result.castToDerived(Derived))
8902         return Error(E);
8903     }
8904     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
8905     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
8906       return Error(E);
8907     return true;
8908   }
8909 
8910   case CK_DerivedToBaseMemberPointer:
8911     if (!Visit(E->getSubExpr()))
8912       return false;
8913     for (CastExpr::path_const_iterator PathI = E->path_begin(),
8914          PathE = E->path_end(); PathI != PathE; ++PathI) {
8915       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
8916       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
8917       if (!Result.castToBase(Base))
8918         return Error(E);
8919     }
8920     return true;
8921   }
8922 }
8923 
8924 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8925   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
8926   // member can be formed.
8927   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
8928 }
8929 
8930 //===----------------------------------------------------------------------===//
8931 // Record Evaluation
8932 //===----------------------------------------------------------------------===//
8933 
8934 namespace {
8935   class RecordExprEvaluator
8936   : public ExprEvaluatorBase<RecordExprEvaluator> {
8937     const LValue &This;
8938     APValue &Result;
8939   public:
8940 
8941     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
8942       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
8943 
8944     bool Success(const APValue &V, const Expr *E) {
8945       Result = V;
8946       return true;
8947     }
8948     bool ZeroInitialization(const Expr *E) {
8949       return ZeroInitialization(E, E->getType());
8950     }
8951     bool ZeroInitialization(const Expr *E, QualType T);
8952 
8953     bool VisitCallExpr(const CallExpr *E) {
8954       return handleCallExpr(E, Result, &This);
8955     }
8956     bool VisitCastExpr(const CastExpr *E);
8957     bool VisitInitListExpr(const InitListExpr *E);
8958     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
8959       return VisitCXXConstructExpr(E, E->getType());
8960     }
8961     bool VisitLambdaExpr(const LambdaExpr *E);
8962     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
8963     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
8964     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
8965     bool VisitBinCmp(const BinaryOperator *E);
8966   };
8967 }
8968 
8969 /// Perform zero-initialization on an object of non-union class type.
8970 /// C++11 [dcl.init]p5:
8971 ///  To zero-initialize an object or reference of type T means:
8972 ///    [...]
8973 ///    -- if T is a (possibly cv-qualified) non-union class type,
8974 ///       each non-static data member and each base-class subobject is
8975 ///       zero-initialized
8976 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
8977                                           const RecordDecl *RD,
8978                                           const LValue &This, APValue &Result) {
8979   assert(!RD->isUnion() && "Expected non-union class type");
8980   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
8981   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
8982                    std::distance(RD->field_begin(), RD->field_end()));
8983 
8984   if (RD->isInvalidDecl()) return false;
8985   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
8986 
8987   if (CD) {
8988     unsigned Index = 0;
8989     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
8990            End = CD->bases_end(); I != End; ++I, ++Index) {
8991       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
8992       LValue Subobject = This;
8993       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
8994         return false;
8995       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
8996                                          Result.getStructBase(Index)))
8997         return false;
8998     }
8999   }
9000 
9001   for (const auto *I : RD->fields()) {
9002     // -- if T is a reference type, no initialization is performed.
9003     if (I->getType()->isReferenceType())
9004       continue;
9005 
9006     LValue Subobject = This;
9007     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9008       return false;
9009 
9010     ImplicitValueInitExpr VIE(I->getType());
9011     if (!EvaluateInPlace(
9012           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9013       return false;
9014   }
9015 
9016   return true;
9017 }
9018 
9019 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9020   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9021   if (RD->isInvalidDecl()) return false;
9022   if (RD->isUnion()) {
9023     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9024     // object's first non-static named data member is zero-initialized
9025     RecordDecl::field_iterator I = RD->field_begin();
9026     if (I == RD->field_end()) {
9027       Result = APValue((const FieldDecl*)nullptr);
9028       return true;
9029     }
9030 
9031     LValue Subobject = This;
9032     if (!HandleLValueMember(Info, E, Subobject, *I))
9033       return false;
9034     Result = APValue(*I);
9035     ImplicitValueInitExpr VIE(I->getType());
9036     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9037   }
9038 
9039   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9040     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9041     return false;
9042   }
9043 
9044   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9045 }
9046 
9047 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9048   switch (E->getCastKind()) {
9049   default:
9050     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9051 
9052   case CK_ConstructorConversion:
9053     return Visit(E->getSubExpr());
9054 
9055   case CK_DerivedToBase:
9056   case CK_UncheckedDerivedToBase: {
9057     APValue DerivedObject;
9058     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9059       return false;
9060     if (!DerivedObject.isStruct())
9061       return Error(E->getSubExpr());
9062 
9063     // Derived-to-base rvalue conversion: just slice off the derived part.
9064     APValue *Value = &DerivedObject;
9065     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9066     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9067          PathE = E->path_end(); PathI != PathE; ++PathI) {
9068       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9069       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9070       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9071       RD = Base;
9072     }
9073     Result = *Value;
9074     return true;
9075   }
9076   }
9077 }
9078 
9079 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9080   if (E->isTransparent())
9081     return Visit(E->getInit(0));
9082 
9083   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9084   if (RD->isInvalidDecl()) return false;
9085   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9086   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9087 
9088   EvalInfo::EvaluatingConstructorRAII EvalObj(
9089       Info,
9090       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9091       CXXRD && CXXRD->getNumBases());
9092 
9093   if (RD->isUnion()) {
9094     const FieldDecl *Field = E->getInitializedFieldInUnion();
9095     Result = APValue(Field);
9096     if (!Field)
9097       return true;
9098 
9099     // If the initializer list for a union does not contain any elements, the
9100     // first element of the union is value-initialized.
9101     // FIXME: The element should be initialized from an initializer list.
9102     //        Is this difference ever observable for initializer lists which
9103     //        we don't build?
9104     ImplicitValueInitExpr VIE(Field->getType());
9105     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9106 
9107     LValue Subobject = This;
9108     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9109       return false;
9110 
9111     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9112     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9113                                   isa<CXXDefaultInitExpr>(InitExpr));
9114 
9115     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
9116   }
9117 
9118   if (!Result.hasValue())
9119     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9120                      std::distance(RD->field_begin(), RD->field_end()));
9121   unsigned ElementNo = 0;
9122   bool Success = true;
9123 
9124   // Initialize base classes.
9125   if (CXXRD && CXXRD->getNumBases()) {
9126     for (const auto &Base : CXXRD->bases()) {
9127       assert(ElementNo < E->getNumInits() && "missing init for base class");
9128       const Expr *Init = E->getInit(ElementNo);
9129 
9130       LValue Subobject = This;
9131       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9132         return false;
9133 
9134       APValue &FieldVal = Result.getStructBase(ElementNo);
9135       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9136         if (!Info.noteFailure())
9137           return false;
9138         Success = false;
9139       }
9140       ++ElementNo;
9141     }
9142 
9143     EvalObj.finishedConstructingBases();
9144   }
9145 
9146   // Initialize members.
9147   for (const auto *Field : RD->fields()) {
9148     // Anonymous bit-fields are not considered members of the class for
9149     // purposes of aggregate initialization.
9150     if (Field->isUnnamedBitfield())
9151       continue;
9152 
9153     LValue Subobject = This;
9154 
9155     bool HaveInit = ElementNo < E->getNumInits();
9156 
9157     // FIXME: Diagnostics here should point to the end of the initializer
9158     // list, not the start.
9159     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9160                             Subobject, Field, &Layout))
9161       return false;
9162 
9163     // Perform an implicit value-initialization for members beyond the end of
9164     // the initializer list.
9165     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9166     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9167 
9168     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9169     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9170                                   isa<CXXDefaultInitExpr>(Init));
9171 
9172     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9173     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9174         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9175                                                        FieldVal, Field))) {
9176       if (!Info.noteFailure())
9177         return false;
9178       Success = false;
9179     }
9180   }
9181 
9182   return Success;
9183 }
9184 
9185 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9186                                                 QualType T) {
9187   // Note that E's type is not necessarily the type of our class here; we might
9188   // be initializing an array element instead.
9189   const CXXConstructorDecl *FD = E->getConstructor();
9190   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9191 
9192   bool ZeroInit = E->requiresZeroInitialization();
9193   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
9194     // If we've already performed zero-initialization, we're already done.
9195     if (Result.hasValue())
9196       return true;
9197 
9198     if (ZeroInit)
9199       return ZeroInitialization(E, T);
9200 
9201     Result = getDefaultInitValue(T);
9202     return true;
9203   }
9204 
9205   const FunctionDecl *Definition = nullptr;
9206   auto Body = FD->getBody(Definition);
9207 
9208   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9209     return false;
9210 
9211   // Avoid materializing a temporary for an elidable copy/move constructor.
9212   if (E->isElidable() && !ZeroInit)
9213     if (const MaterializeTemporaryExpr *ME
9214           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
9215       return Visit(ME->getSubExpr());
9216 
9217   if (ZeroInit && !ZeroInitialization(E, T))
9218     return false;
9219 
9220   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
9221   return HandleConstructorCall(E, This, Args,
9222                                cast<CXXConstructorDecl>(Definition), Info,
9223                                Result);
9224 }
9225 
9226 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9227     const CXXInheritedCtorInitExpr *E) {
9228   if (!Info.CurrentCall) {
9229     assert(Info.checkingPotentialConstantExpression());
9230     return false;
9231   }
9232 
9233   const CXXConstructorDecl *FD = E->getConstructor();
9234   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9235     return false;
9236 
9237   const FunctionDecl *Definition = nullptr;
9238   auto Body = FD->getBody(Definition);
9239 
9240   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9241     return false;
9242 
9243   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
9244                                cast<CXXConstructorDecl>(Definition), Info,
9245                                Result);
9246 }
9247 
9248 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
9249     const CXXStdInitializerListExpr *E) {
9250   const ConstantArrayType *ArrayType =
9251       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
9252 
9253   LValue Array;
9254   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
9255     return false;
9256 
9257   // Get a pointer to the first element of the array.
9258   Array.addArray(Info, E, ArrayType);
9259 
9260   // FIXME: Perform the checks on the field types in SemaInit.
9261   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
9262   RecordDecl::field_iterator Field = Record->field_begin();
9263   if (Field == Record->field_end())
9264     return Error(E);
9265 
9266   // Start pointer.
9267   if (!Field->getType()->isPointerType() ||
9268       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9269                             ArrayType->getElementType()))
9270     return Error(E);
9271 
9272   // FIXME: What if the initializer_list type has base classes, etc?
9273   Result = APValue(APValue::UninitStruct(), 0, 2);
9274   Array.moveInto(Result.getStructField(0));
9275 
9276   if (++Field == Record->field_end())
9277     return Error(E);
9278 
9279   if (Field->getType()->isPointerType() &&
9280       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9281                            ArrayType->getElementType())) {
9282     // End pointer.
9283     if (!HandleLValueArrayAdjustment(Info, E, Array,
9284                                      ArrayType->getElementType(),
9285                                      ArrayType->getSize().getZExtValue()))
9286       return false;
9287     Array.moveInto(Result.getStructField(1));
9288   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
9289     // Length.
9290     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
9291   else
9292     return Error(E);
9293 
9294   if (++Field != Record->field_end())
9295     return Error(E);
9296 
9297   return true;
9298 }
9299 
9300 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
9301   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
9302   if (ClosureClass->isInvalidDecl())
9303     return false;
9304 
9305   const size_t NumFields =
9306       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
9307 
9308   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
9309                                             E->capture_init_end()) &&
9310          "The number of lambda capture initializers should equal the number of "
9311          "fields within the closure type");
9312 
9313   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
9314   // Iterate through all the lambda's closure object's fields and initialize
9315   // them.
9316   auto *CaptureInitIt = E->capture_init_begin();
9317   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
9318   bool Success = true;
9319   for (const auto *Field : ClosureClass->fields()) {
9320     assert(CaptureInitIt != E->capture_init_end());
9321     // Get the initializer for this field
9322     Expr *const CurFieldInit = *CaptureInitIt++;
9323 
9324     // If there is no initializer, either this is a VLA or an error has
9325     // occurred.
9326     if (!CurFieldInit)
9327       return Error(E);
9328 
9329     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9330     if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
9331       if (!Info.keepEvaluatingAfterFailure())
9332         return false;
9333       Success = false;
9334     }
9335     ++CaptureIt;
9336   }
9337   return Success;
9338 }
9339 
9340 static bool EvaluateRecord(const Expr *E, const LValue &This,
9341                            APValue &Result, EvalInfo &Info) {
9342   assert(E->isRValue() && E->getType()->isRecordType() &&
9343          "can't evaluate expression as a record rvalue");
9344   return RecordExprEvaluator(Info, This, Result).Visit(E);
9345 }
9346 
9347 //===----------------------------------------------------------------------===//
9348 // Temporary Evaluation
9349 //
9350 // Temporaries are represented in the AST as rvalues, but generally behave like
9351 // lvalues. The full-object of which the temporary is a subobject is implicitly
9352 // materialized so that a reference can bind to it.
9353 //===----------------------------------------------------------------------===//
9354 namespace {
9355 class TemporaryExprEvaluator
9356   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
9357 public:
9358   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
9359     LValueExprEvaluatorBaseTy(Info, Result, false) {}
9360 
9361   /// Visit an expression which constructs the value of this temporary.
9362   bool VisitConstructExpr(const Expr *E) {
9363     APValue &Value =
9364         Info.CurrentCall->createTemporary(E, E->getType(), false, Result);
9365     return EvaluateInPlace(Value, Info, Result, E);
9366   }
9367 
9368   bool VisitCastExpr(const CastExpr *E) {
9369     switch (E->getCastKind()) {
9370     default:
9371       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9372 
9373     case CK_ConstructorConversion:
9374       return VisitConstructExpr(E->getSubExpr());
9375     }
9376   }
9377   bool VisitInitListExpr(const InitListExpr *E) {
9378     return VisitConstructExpr(E);
9379   }
9380   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9381     return VisitConstructExpr(E);
9382   }
9383   bool VisitCallExpr(const CallExpr *E) {
9384     return VisitConstructExpr(E);
9385   }
9386   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
9387     return VisitConstructExpr(E);
9388   }
9389   bool VisitLambdaExpr(const LambdaExpr *E) {
9390     return VisitConstructExpr(E);
9391   }
9392 };
9393 } // end anonymous namespace
9394 
9395 /// Evaluate an expression of record type as a temporary.
9396 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
9397   assert(E->isRValue() && E->getType()->isRecordType());
9398   return TemporaryExprEvaluator(Info, Result).Visit(E);
9399 }
9400 
9401 //===----------------------------------------------------------------------===//
9402 // Vector Evaluation
9403 //===----------------------------------------------------------------------===//
9404 
9405 namespace {
9406   class VectorExprEvaluator
9407   : public ExprEvaluatorBase<VectorExprEvaluator> {
9408     APValue &Result;
9409   public:
9410 
9411     VectorExprEvaluator(EvalInfo &info, APValue &Result)
9412       : ExprEvaluatorBaseTy(info), Result(Result) {}
9413 
9414     bool Success(ArrayRef<APValue> V, const Expr *E) {
9415       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
9416       // FIXME: remove this APValue copy.
9417       Result = APValue(V.data(), V.size());
9418       return true;
9419     }
9420     bool Success(const APValue &V, const Expr *E) {
9421       assert(V.isVector());
9422       Result = V;
9423       return true;
9424     }
9425     bool ZeroInitialization(const Expr *E);
9426 
9427     bool VisitUnaryReal(const UnaryOperator *E)
9428       { return Visit(E->getSubExpr()); }
9429     bool VisitCastExpr(const CastExpr* E);
9430     bool VisitInitListExpr(const InitListExpr *E);
9431     bool VisitUnaryImag(const UnaryOperator *E);
9432     // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
9433     //                 binary comparisons, binary and/or/xor,
9434     //                 conditional operator (for GNU conditional select),
9435     //                 shufflevector, ExtVectorElementExpr
9436   };
9437 } // end anonymous namespace
9438 
9439 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
9440   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
9441   return VectorExprEvaluator(Info, Result).Visit(E);
9442 }
9443 
9444 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
9445   const VectorType *VTy = E->getType()->castAs<VectorType>();
9446   unsigned NElts = VTy->getNumElements();
9447 
9448   const Expr *SE = E->getSubExpr();
9449   QualType SETy = SE->getType();
9450 
9451   switch (E->getCastKind()) {
9452   case CK_VectorSplat: {
9453     APValue Val = APValue();
9454     if (SETy->isIntegerType()) {
9455       APSInt IntResult;
9456       if (!EvaluateInteger(SE, IntResult, Info))
9457         return false;
9458       Val = APValue(std::move(IntResult));
9459     } else if (SETy->isRealFloatingType()) {
9460       APFloat FloatResult(0.0);
9461       if (!EvaluateFloat(SE, FloatResult, Info))
9462         return false;
9463       Val = APValue(std::move(FloatResult));
9464     } else {
9465       return Error(E);
9466     }
9467 
9468     // Splat and create vector APValue.
9469     SmallVector<APValue, 4> Elts(NElts, Val);
9470     return Success(Elts, E);
9471   }
9472   case CK_BitCast: {
9473     // Evaluate the operand into an APInt we can extract from.
9474     llvm::APInt SValInt;
9475     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
9476       return false;
9477     // Extract the elements
9478     QualType EltTy = VTy->getElementType();
9479     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
9480     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
9481     SmallVector<APValue, 4> Elts;
9482     if (EltTy->isRealFloatingType()) {
9483       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
9484       unsigned FloatEltSize = EltSize;
9485       if (&Sem == &APFloat::x87DoubleExtended())
9486         FloatEltSize = 80;
9487       for (unsigned i = 0; i < NElts; i++) {
9488         llvm::APInt Elt;
9489         if (BigEndian)
9490           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
9491         else
9492           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
9493         Elts.push_back(APValue(APFloat(Sem, Elt)));
9494       }
9495     } else if (EltTy->isIntegerType()) {
9496       for (unsigned i = 0; i < NElts; i++) {
9497         llvm::APInt Elt;
9498         if (BigEndian)
9499           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
9500         else
9501           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
9502         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
9503       }
9504     } else {
9505       return Error(E);
9506     }
9507     return Success(Elts, E);
9508   }
9509   default:
9510     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9511   }
9512 }
9513 
9514 bool
9515 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9516   const VectorType *VT = E->getType()->castAs<VectorType>();
9517   unsigned NumInits = E->getNumInits();
9518   unsigned NumElements = VT->getNumElements();
9519 
9520   QualType EltTy = VT->getElementType();
9521   SmallVector<APValue, 4> Elements;
9522 
9523   // The number of initializers can be less than the number of
9524   // vector elements. For OpenCL, this can be due to nested vector
9525   // initialization. For GCC compatibility, missing trailing elements
9526   // should be initialized with zeroes.
9527   unsigned CountInits = 0, CountElts = 0;
9528   while (CountElts < NumElements) {
9529     // Handle nested vector initialization.
9530     if (CountInits < NumInits
9531         && E->getInit(CountInits)->getType()->isVectorType()) {
9532       APValue v;
9533       if (!EvaluateVector(E->getInit(CountInits), v, Info))
9534         return Error(E);
9535       unsigned vlen = v.getVectorLength();
9536       for (unsigned j = 0; j < vlen; j++)
9537         Elements.push_back(v.getVectorElt(j));
9538       CountElts += vlen;
9539     } else if (EltTy->isIntegerType()) {
9540       llvm::APSInt sInt(32);
9541       if (CountInits < NumInits) {
9542         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
9543           return false;
9544       } else // trailing integer zero.
9545         sInt = Info.Ctx.MakeIntValue(0, EltTy);
9546       Elements.push_back(APValue(sInt));
9547       CountElts++;
9548     } else {
9549       llvm::APFloat f(0.0);
9550       if (CountInits < NumInits) {
9551         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
9552           return false;
9553       } else // trailing float zero.
9554         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
9555       Elements.push_back(APValue(f));
9556       CountElts++;
9557     }
9558     CountInits++;
9559   }
9560   return Success(Elements, E);
9561 }
9562 
9563 bool
9564 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
9565   const auto *VT = E->getType()->castAs<VectorType>();
9566   QualType EltTy = VT->getElementType();
9567   APValue ZeroElement;
9568   if (EltTy->isIntegerType())
9569     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
9570   else
9571     ZeroElement =
9572         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
9573 
9574   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
9575   return Success(Elements, E);
9576 }
9577 
9578 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9579   VisitIgnoredValue(E->getSubExpr());
9580   return ZeroInitialization(E);
9581 }
9582 
9583 //===----------------------------------------------------------------------===//
9584 // Array Evaluation
9585 //===----------------------------------------------------------------------===//
9586 
9587 namespace {
9588   class ArrayExprEvaluator
9589   : public ExprEvaluatorBase<ArrayExprEvaluator> {
9590     const LValue &This;
9591     APValue &Result;
9592   public:
9593 
9594     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
9595       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
9596 
9597     bool Success(const APValue &V, const Expr *E) {
9598       assert(V.isArray() && "expected array");
9599       Result = V;
9600       return true;
9601     }
9602 
9603     bool ZeroInitialization(const Expr *E) {
9604       const ConstantArrayType *CAT =
9605           Info.Ctx.getAsConstantArrayType(E->getType());
9606       if (!CAT)
9607         return Error(E);
9608 
9609       Result = APValue(APValue::UninitArray(), 0,
9610                        CAT->getSize().getZExtValue());
9611       if (!Result.hasArrayFiller()) return true;
9612 
9613       // Zero-initialize all elements.
9614       LValue Subobject = This;
9615       Subobject.addArray(Info, E, CAT);
9616       ImplicitValueInitExpr VIE(CAT->getElementType());
9617       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
9618     }
9619 
9620     bool VisitCallExpr(const CallExpr *E) {
9621       return handleCallExpr(E, Result, &This);
9622     }
9623     bool VisitInitListExpr(const InitListExpr *E,
9624                            QualType AllocType = QualType());
9625     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
9626     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
9627     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
9628                                const LValue &Subobject,
9629                                APValue *Value, QualType Type);
9630     bool VisitStringLiteral(const StringLiteral *E,
9631                             QualType AllocType = QualType()) {
9632       expandStringLiteral(Info, E, Result, AllocType);
9633       return true;
9634     }
9635   };
9636 } // end anonymous namespace
9637 
9638 static bool EvaluateArray(const Expr *E, const LValue &This,
9639                           APValue &Result, EvalInfo &Info) {
9640   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
9641   return ArrayExprEvaluator(Info, This, Result).Visit(E);
9642 }
9643 
9644 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9645                                      APValue &Result, const InitListExpr *ILE,
9646                                      QualType AllocType) {
9647   assert(ILE->isRValue() && ILE->getType()->isArrayType() &&
9648          "not an array rvalue");
9649   return ArrayExprEvaluator(Info, This, Result)
9650       .VisitInitListExpr(ILE, AllocType);
9651 }
9652 
9653 // Return true iff the given array filler may depend on the element index.
9654 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
9655   // For now, just whitelist non-class value-initialization and initialization
9656   // lists comprised of them.
9657   if (isa<ImplicitValueInitExpr>(FillerExpr))
9658     return false;
9659   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
9660     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
9661       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
9662         return true;
9663     }
9664     return false;
9665   }
9666   return true;
9667 }
9668 
9669 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
9670                                            QualType AllocType) {
9671   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
9672       AllocType.isNull() ? E->getType() : AllocType);
9673   if (!CAT)
9674     return Error(E);
9675 
9676   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
9677   // an appropriately-typed string literal enclosed in braces.
9678   if (E->isStringLiteralInit()) {
9679     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
9680     // FIXME: Support ObjCEncodeExpr here once we support it in
9681     // ArrayExprEvaluator generally.
9682     if (!SL)
9683       return Error(E);
9684     return VisitStringLiteral(SL, AllocType);
9685   }
9686 
9687   bool Success = true;
9688 
9689   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
9690          "zero-initialized array shouldn't have any initialized elts");
9691   APValue Filler;
9692   if (Result.isArray() && Result.hasArrayFiller())
9693     Filler = Result.getArrayFiller();
9694 
9695   unsigned NumEltsToInit = E->getNumInits();
9696   unsigned NumElts = CAT->getSize().getZExtValue();
9697   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
9698 
9699   // If the initializer might depend on the array index, run it for each
9700   // array element.
9701   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
9702     NumEltsToInit = NumElts;
9703 
9704   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
9705                           << NumEltsToInit << ".\n");
9706 
9707   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
9708 
9709   // If the array was previously zero-initialized, preserve the
9710   // zero-initialized values.
9711   if (Filler.hasValue()) {
9712     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
9713       Result.getArrayInitializedElt(I) = Filler;
9714     if (Result.hasArrayFiller())
9715       Result.getArrayFiller() = Filler;
9716   }
9717 
9718   LValue Subobject = This;
9719   Subobject.addArray(Info, E, CAT);
9720   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
9721     const Expr *Init =
9722         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
9723     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
9724                          Info, Subobject, Init) ||
9725         !HandleLValueArrayAdjustment(Info, Init, Subobject,
9726                                      CAT->getElementType(), 1)) {
9727       if (!Info.noteFailure())
9728         return false;
9729       Success = false;
9730     }
9731   }
9732 
9733   if (!Result.hasArrayFiller())
9734     return Success;
9735 
9736   // If we get here, we have a trivial filler, which we can just evaluate
9737   // once and splat over the rest of the array elements.
9738   assert(FillerExpr && "no array filler for incomplete init list");
9739   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
9740                          FillerExpr) && Success;
9741 }
9742 
9743 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
9744   LValue CommonLV;
9745   if (E->getCommonExpr() &&
9746       !Evaluate(Info.CurrentCall->createTemporary(
9747                     E->getCommonExpr(),
9748                     getStorageType(Info.Ctx, E->getCommonExpr()), false,
9749                     CommonLV),
9750                 Info, E->getCommonExpr()->getSourceExpr()))
9751     return false;
9752 
9753   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
9754 
9755   uint64_t Elements = CAT->getSize().getZExtValue();
9756   Result = APValue(APValue::UninitArray(), Elements, Elements);
9757 
9758   LValue Subobject = This;
9759   Subobject.addArray(Info, E, CAT);
9760 
9761   bool Success = true;
9762   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
9763     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
9764                          Info, Subobject, E->getSubExpr()) ||
9765         !HandleLValueArrayAdjustment(Info, E, Subobject,
9766                                      CAT->getElementType(), 1)) {
9767       if (!Info.noteFailure())
9768         return false;
9769       Success = false;
9770     }
9771   }
9772 
9773   return Success;
9774 }
9775 
9776 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
9777   return VisitCXXConstructExpr(E, This, &Result, E->getType());
9778 }
9779 
9780 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9781                                                const LValue &Subobject,
9782                                                APValue *Value,
9783                                                QualType Type) {
9784   bool HadZeroInit = Value->hasValue();
9785 
9786   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
9787     unsigned N = CAT->getSize().getZExtValue();
9788 
9789     // Preserve the array filler if we had prior zero-initialization.
9790     APValue Filler =
9791       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
9792                                              : APValue();
9793 
9794     *Value = APValue(APValue::UninitArray(), N, N);
9795 
9796     if (HadZeroInit)
9797       for (unsigned I = 0; I != N; ++I)
9798         Value->getArrayInitializedElt(I) = Filler;
9799 
9800     // Initialize the elements.
9801     LValue ArrayElt = Subobject;
9802     ArrayElt.addArray(Info, E, CAT);
9803     for (unsigned I = 0; I != N; ++I)
9804       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
9805                                  CAT->getElementType()) ||
9806           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
9807                                        CAT->getElementType(), 1))
9808         return false;
9809 
9810     return true;
9811   }
9812 
9813   if (!Type->isRecordType())
9814     return Error(E);
9815 
9816   return RecordExprEvaluator(Info, Subobject, *Value)
9817              .VisitCXXConstructExpr(E, Type);
9818 }
9819 
9820 //===----------------------------------------------------------------------===//
9821 // Integer Evaluation
9822 //
9823 // As a GNU extension, we support casting pointers to sufficiently-wide integer
9824 // types and back in constant folding. Integer values are thus represented
9825 // either as an integer-valued APValue, or as an lvalue-valued APValue.
9826 //===----------------------------------------------------------------------===//
9827 
9828 namespace {
9829 class IntExprEvaluator
9830         : public ExprEvaluatorBase<IntExprEvaluator> {
9831   APValue &Result;
9832 public:
9833   IntExprEvaluator(EvalInfo &info, APValue &result)
9834       : ExprEvaluatorBaseTy(info), Result(result) {}
9835 
9836   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
9837     assert(E->getType()->isIntegralOrEnumerationType() &&
9838            "Invalid evaluation result.");
9839     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
9840            "Invalid evaluation result.");
9841     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
9842            "Invalid evaluation result.");
9843     Result = APValue(SI);
9844     return true;
9845   }
9846   bool Success(const llvm::APSInt &SI, const Expr *E) {
9847     return Success(SI, E, Result);
9848   }
9849 
9850   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
9851     assert(E->getType()->isIntegralOrEnumerationType() &&
9852            "Invalid evaluation result.");
9853     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
9854            "Invalid evaluation result.");
9855     Result = APValue(APSInt(I));
9856     Result.getInt().setIsUnsigned(
9857                             E->getType()->isUnsignedIntegerOrEnumerationType());
9858     return true;
9859   }
9860   bool Success(const llvm::APInt &I, const Expr *E) {
9861     return Success(I, E, Result);
9862   }
9863 
9864   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
9865     assert(E->getType()->isIntegralOrEnumerationType() &&
9866            "Invalid evaluation result.");
9867     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
9868     return true;
9869   }
9870   bool Success(uint64_t Value, const Expr *E) {
9871     return Success(Value, E, Result);
9872   }
9873 
9874   bool Success(CharUnits Size, const Expr *E) {
9875     return Success(Size.getQuantity(), E);
9876   }
9877 
9878   bool Success(const APValue &V, const Expr *E) {
9879     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
9880       Result = V;
9881       return true;
9882     }
9883     return Success(V.getInt(), E);
9884   }
9885 
9886   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
9887 
9888   //===--------------------------------------------------------------------===//
9889   //                            Visitor Methods
9890   //===--------------------------------------------------------------------===//
9891 
9892   bool VisitConstantExpr(const ConstantExpr *E);
9893 
9894   bool VisitIntegerLiteral(const IntegerLiteral *E) {
9895     return Success(E->getValue(), E);
9896   }
9897   bool VisitCharacterLiteral(const CharacterLiteral *E) {
9898     return Success(E->getValue(), E);
9899   }
9900 
9901   bool CheckReferencedDecl(const Expr *E, const Decl *D);
9902   bool VisitDeclRefExpr(const DeclRefExpr *E) {
9903     if (CheckReferencedDecl(E, E->getDecl()))
9904       return true;
9905 
9906     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
9907   }
9908   bool VisitMemberExpr(const MemberExpr *E) {
9909     if (CheckReferencedDecl(E, E->getMemberDecl())) {
9910       VisitIgnoredBaseExpression(E->getBase());
9911       return true;
9912     }
9913 
9914     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
9915   }
9916 
9917   bool VisitCallExpr(const CallExpr *E);
9918   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9919   bool VisitBinaryOperator(const BinaryOperator *E);
9920   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
9921   bool VisitUnaryOperator(const UnaryOperator *E);
9922 
9923   bool VisitCastExpr(const CastExpr* E);
9924   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
9925 
9926   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
9927     return Success(E->getValue(), E);
9928   }
9929 
9930   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
9931     return Success(E->getValue(), E);
9932   }
9933 
9934   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
9935     if (Info.ArrayInitIndex == uint64_t(-1)) {
9936       // We were asked to evaluate this subexpression independent of the
9937       // enclosing ArrayInitLoopExpr. We can't do that.
9938       Info.FFDiag(E);
9939       return false;
9940     }
9941     return Success(Info.ArrayInitIndex, E);
9942   }
9943 
9944   // Note, GNU defines __null as an integer, not a pointer.
9945   bool VisitGNUNullExpr(const GNUNullExpr *E) {
9946     return ZeroInitialization(E);
9947   }
9948 
9949   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
9950     return Success(E->getValue(), E);
9951   }
9952 
9953   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
9954     return Success(E->getValue(), E);
9955   }
9956 
9957   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
9958     return Success(E->getValue(), E);
9959   }
9960 
9961   bool VisitUnaryReal(const UnaryOperator *E);
9962   bool VisitUnaryImag(const UnaryOperator *E);
9963 
9964   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
9965   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
9966   bool VisitSourceLocExpr(const SourceLocExpr *E);
9967   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
9968   bool VisitRequiresExpr(const RequiresExpr *E);
9969   // FIXME: Missing: array subscript of vector, member of vector
9970 };
9971 
9972 class FixedPointExprEvaluator
9973     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
9974   APValue &Result;
9975 
9976  public:
9977   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
9978       : ExprEvaluatorBaseTy(info), Result(result) {}
9979 
9980   bool Success(const llvm::APInt &I, const Expr *E) {
9981     return Success(
9982         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
9983   }
9984 
9985   bool Success(uint64_t Value, const Expr *E) {
9986     return Success(
9987         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
9988   }
9989 
9990   bool Success(const APValue &V, const Expr *E) {
9991     return Success(V.getFixedPoint(), E);
9992   }
9993 
9994   bool Success(const APFixedPoint &V, const Expr *E) {
9995     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
9996     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
9997            "Invalid evaluation result.");
9998     Result = APValue(V);
9999     return true;
10000   }
10001 
10002   //===--------------------------------------------------------------------===//
10003   //                            Visitor Methods
10004   //===--------------------------------------------------------------------===//
10005 
10006   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
10007     return Success(E->getValue(), E);
10008   }
10009 
10010   bool VisitCastExpr(const CastExpr *E);
10011   bool VisitUnaryOperator(const UnaryOperator *E);
10012   bool VisitBinaryOperator(const BinaryOperator *E);
10013 };
10014 } // end anonymous namespace
10015 
10016 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
10017 /// produce either the integer value or a pointer.
10018 ///
10019 /// GCC has a heinous extension which folds casts between pointer types and
10020 /// pointer-sized integral types. We support this by allowing the evaluation of
10021 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
10022 /// Some simple arithmetic on such values is supported (they are treated much
10023 /// like char*).
10024 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
10025                                     EvalInfo &Info) {
10026   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
10027   return IntExprEvaluator(Info, Result).Visit(E);
10028 }
10029 
10030 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
10031   APValue Val;
10032   if (!EvaluateIntegerOrLValue(E, Val, Info))
10033     return false;
10034   if (!Val.isInt()) {
10035     // FIXME: It would be better to produce the diagnostic for casting
10036     //        a pointer to an integer.
10037     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10038     return false;
10039   }
10040   Result = Val.getInt();
10041   return true;
10042 }
10043 
10044 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
10045   APValue Evaluated = E->EvaluateInContext(
10046       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10047   return Success(Evaluated, E);
10048 }
10049 
10050 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
10051                                EvalInfo &Info) {
10052   if (E->getType()->isFixedPointType()) {
10053     APValue Val;
10054     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
10055       return false;
10056     if (!Val.isFixedPoint())
10057       return false;
10058 
10059     Result = Val.getFixedPoint();
10060     return true;
10061   }
10062   return false;
10063 }
10064 
10065 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
10066                                         EvalInfo &Info) {
10067   if (E->getType()->isIntegerType()) {
10068     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
10069     APSInt Val;
10070     if (!EvaluateInteger(E, Val, Info))
10071       return false;
10072     Result = APFixedPoint(Val, FXSema);
10073     return true;
10074   } else if (E->getType()->isFixedPointType()) {
10075     return EvaluateFixedPoint(E, Result, Info);
10076   }
10077   return false;
10078 }
10079 
10080 /// Check whether the given declaration can be directly converted to an integral
10081 /// rvalue. If not, no diagnostic is produced; there are other things we can
10082 /// try.
10083 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
10084   // Enums are integer constant exprs.
10085   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
10086     // Check for signedness/width mismatches between E type and ECD value.
10087     bool SameSign = (ECD->getInitVal().isSigned()
10088                      == E->getType()->isSignedIntegerOrEnumerationType());
10089     bool SameWidth = (ECD->getInitVal().getBitWidth()
10090                       == Info.Ctx.getIntWidth(E->getType()));
10091     if (SameSign && SameWidth)
10092       return Success(ECD->getInitVal(), E);
10093     else {
10094       // Get rid of mismatch (otherwise Success assertions will fail)
10095       // by computing a new value matching the type of E.
10096       llvm::APSInt Val = ECD->getInitVal();
10097       if (!SameSign)
10098         Val.setIsSigned(!ECD->getInitVal().isSigned());
10099       if (!SameWidth)
10100         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
10101       return Success(Val, E);
10102     }
10103   }
10104   return false;
10105 }
10106 
10107 /// Values returned by __builtin_classify_type, chosen to match the values
10108 /// produced by GCC's builtin.
10109 enum class GCCTypeClass {
10110   None = -1,
10111   Void = 0,
10112   Integer = 1,
10113   // GCC reserves 2 for character types, but instead classifies them as
10114   // integers.
10115   Enum = 3,
10116   Bool = 4,
10117   Pointer = 5,
10118   // GCC reserves 6 for references, but appears to never use it (because
10119   // expressions never have reference type, presumably).
10120   PointerToDataMember = 7,
10121   RealFloat = 8,
10122   Complex = 9,
10123   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
10124   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
10125   // GCC claims to reserve 11 for pointers to member functions, but *actually*
10126   // uses 12 for that purpose, same as for a class or struct. Maybe it
10127   // internally implements a pointer to member as a struct?  Who knows.
10128   PointerToMemberFunction = 12, // Not a bug, see above.
10129   ClassOrStruct = 12,
10130   Union = 13,
10131   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
10132   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
10133   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
10134   // literals.
10135 };
10136 
10137 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10138 /// as GCC.
10139 static GCCTypeClass
10140 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
10141   assert(!T->isDependentType() && "unexpected dependent type");
10142 
10143   QualType CanTy = T.getCanonicalType();
10144   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
10145 
10146   switch (CanTy->getTypeClass()) {
10147 #define TYPE(ID, BASE)
10148 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
10149 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
10150 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
10151 #include "clang/AST/TypeNodes.inc"
10152   case Type::Auto:
10153   case Type::DeducedTemplateSpecialization:
10154       llvm_unreachable("unexpected non-canonical or dependent type");
10155 
10156   case Type::Builtin:
10157     switch (BT->getKind()) {
10158 #define BUILTIN_TYPE(ID, SINGLETON_ID)
10159 #define SIGNED_TYPE(ID, SINGLETON_ID) \
10160     case BuiltinType::ID: return GCCTypeClass::Integer;
10161 #define FLOATING_TYPE(ID, SINGLETON_ID) \
10162     case BuiltinType::ID: return GCCTypeClass::RealFloat;
10163 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
10164     case BuiltinType::ID: break;
10165 #include "clang/AST/BuiltinTypes.def"
10166     case BuiltinType::Void:
10167       return GCCTypeClass::Void;
10168 
10169     case BuiltinType::Bool:
10170       return GCCTypeClass::Bool;
10171 
10172     case BuiltinType::Char_U:
10173     case BuiltinType::UChar:
10174     case BuiltinType::WChar_U:
10175     case BuiltinType::Char8:
10176     case BuiltinType::Char16:
10177     case BuiltinType::Char32:
10178     case BuiltinType::UShort:
10179     case BuiltinType::UInt:
10180     case BuiltinType::ULong:
10181     case BuiltinType::ULongLong:
10182     case BuiltinType::UInt128:
10183       return GCCTypeClass::Integer;
10184 
10185     case BuiltinType::UShortAccum:
10186     case BuiltinType::UAccum:
10187     case BuiltinType::ULongAccum:
10188     case BuiltinType::UShortFract:
10189     case BuiltinType::UFract:
10190     case BuiltinType::ULongFract:
10191     case BuiltinType::SatUShortAccum:
10192     case BuiltinType::SatUAccum:
10193     case BuiltinType::SatULongAccum:
10194     case BuiltinType::SatUShortFract:
10195     case BuiltinType::SatUFract:
10196     case BuiltinType::SatULongFract:
10197       return GCCTypeClass::None;
10198 
10199     case BuiltinType::NullPtr:
10200 
10201     case BuiltinType::ObjCId:
10202     case BuiltinType::ObjCClass:
10203     case BuiltinType::ObjCSel:
10204 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
10205     case BuiltinType::Id:
10206 #include "clang/Basic/OpenCLImageTypes.def"
10207 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
10208     case BuiltinType::Id:
10209 #include "clang/Basic/OpenCLExtensionTypes.def"
10210     case BuiltinType::OCLSampler:
10211     case BuiltinType::OCLEvent:
10212     case BuiltinType::OCLClkEvent:
10213     case BuiltinType::OCLQueue:
10214     case BuiltinType::OCLReserveID:
10215 #define SVE_TYPE(Name, Id, SingletonId) \
10216     case BuiltinType::Id:
10217 #include "clang/Basic/AArch64SVEACLETypes.def"
10218       return GCCTypeClass::None;
10219 
10220     case BuiltinType::Dependent:
10221       llvm_unreachable("unexpected dependent type");
10222     };
10223     llvm_unreachable("unexpected placeholder type");
10224 
10225   case Type::Enum:
10226     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
10227 
10228   case Type::Pointer:
10229   case Type::ConstantArray:
10230   case Type::VariableArray:
10231   case Type::IncompleteArray:
10232   case Type::FunctionNoProto:
10233   case Type::FunctionProto:
10234     return GCCTypeClass::Pointer;
10235 
10236   case Type::MemberPointer:
10237     return CanTy->isMemberDataPointerType()
10238                ? GCCTypeClass::PointerToDataMember
10239                : GCCTypeClass::PointerToMemberFunction;
10240 
10241   case Type::Complex:
10242     return GCCTypeClass::Complex;
10243 
10244   case Type::Record:
10245     return CanTy->isUnionType() ? GCCTypeClass::Union
10246                                 : GCCTypeClass::ClassOrStruct;
10247 
10248   case Type::Atomic:
10249     // GCC classifies _Atomic T the same as T.
10250     return EvaluateBuiltinClassifyType(
10251         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
10252 
10253   case Type::BlockPointer:
10254   case Type::Vector:
10255   case Type::ExtVector:
10256   case Type::ObjCObject:
10257   case Type::ObjCInterface:
10258   case Type::ObjCObjectPointer:
10259   case Type::Pipe:
10260     // GCC classifies vectors as None. We follow its lead and classify all
10261     // other types that don't fit into the regular classification the same way.
10262     return GCCTypeClass::None;
10263 
10264   case Type::LValueReference:
10265   case Type::RValueReference:
10266     llvm_unreachable("invalid type for expression");
10267   }
10268 
10269   llvm_unreachable("unexpected type class");
10270 }
10271 
10272 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10273 /// as GCC.
10274 static GCCTypeClass
10275 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
10276   // If no argument was supplied, default to None. This isn't
10277   // ideal, however it is what gcc does.
10278   if (E->getNumArgs() == 0)
10279     return GCCTypeClass::None;
10280 
10281   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
10282   // being an ICE, but still folds it to a constant using the type of the first
10283   // argument.
10284   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
10285 }
10286 
10287 /// EvaluateBuiltinConstantPForLValue - Determine the result of
10288 /// __builtin_constant_p when applied to the given pointer.
10289 ///
10290 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
10291 /// or it points to the first character of a string literal.
10292 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
10293   APValue::LValueBase Base = LV.getLValueBase();
10294   if (Base.isNull()) {
10295     // A null base is acceptable.
10296     return true;
10297   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
10298     if (!isa<StringLiteral>(E))
10299       return false;
10300     return LV.getLValueOffset().isZero();
10301   } else if (Base.is<TypeInfoLValue>()) {
10302     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
10303     // evaluate to true.
10304     return true;
10305   } else {
10306     // Any other base is not constant enough for GCC.
10307     return false;
10308   }
10309 }
10310 
10311 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
10312 /// GCC as we can manage.
10313 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
10314   // This evaluation is not permitted to have side-effects, so evaluate it in
10315   // a speculative evaluation context.
10316   SpeculativeEvaluationRAII SpeculativeEval(Info);
10317 
10318   // Constant-folding is always enabled for the operand of __builtin_constant_p
10319   // (even when the enclosing evaluation context otherwise requires a strict
10320   // language-specific constant expression).
10321   FoldConstant Fold(Info, true);
10322 
10323   QualType ArgType = Arg->getType();
10324 
10325   // __builtin_constant_p always has one operand. The rules which gcc follows
10326   // are not precisely documented, but are as follows:
10327   //
10328   //  - If the operand is of integral, floating, complex or enumeration type,
10329   //    and can be folded to a known value of that type, it returns 1.
10330   //  - If the operand can be folded to a pointer to the first character
10331   //    of a string literal (or such a pointer cast to an integral type)
10332   //    or to a null pointer or an integer cast to a pointer, it returns 1.
10333   //
10334   // Otherwise, it returns 0.
10335   //
10336   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
10337   // its support for this did not work prior to GCC 9 and is not yet well
10338   // understood.
10339   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
10340       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
10341       ArgType->isNullPtrType()) {
10342     APValue V;
10343     if (!::EvaluateAsRValue(Info, Arg, V)) {
10344       Fold.keepDiagnostics();
10345       return false;
10346     }
10347 
10348     // For a pointer (possibly cast to integer), there are special rules.
10349     if (V.getKind() == APValue::LValue)
10350       return EvaluateBuiltinConstantPForLValue(V);
10351 
10352     // Otherwise, any constant value is good enough.
10353     return V.hasValue();
10354   }
10355 
10356   // Anything else isn't considered to be sufficiently constant.
10357   return false;
10358 }
10359 
10360 /// Retrieves the "underlying object type" of the given expression,
10361 /// as used by __builtin_object_size.
10362 static QualType getObjectType(APValue::LValueBase B) {
10363   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
10364     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
10365       return VD->getType();
10366   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
10367     if (isa<CompoundLiteralExpr>(E))
10368       return E->getType();
10369   } else if (B.is<TypeInfoLValue>()) {
10370     return B.getTypeInfoType();
10371   } else if (B.is<DynamicAllocLValue>()) {
10372     return B.getDynamicAllocType();
10373   }
10374 
10375   return QualType();
10376 }
10377 
10378 /// A more selective version of E->IgnoreParenCasts for
10379 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
10380 /// to change the type of E.
10381 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
10382 ///
10383 /// Always returns an RValue with a pointer representation.
10384 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
10385   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
10386 
10387   auto *NoParens = E->IgnoreParens();
10388   auto *Cast = dyn_cast<CastExpr>(NoParens);
10389   if (Cast == nullptr)
10390     return NoParens;
10391 
10392   // We only conservatively allow a few kinds of casts, because this code is
10393   // inherently a simple solution that seeks to support the common case.
10394   auto CastKind = Cast->getCastKind();
10395   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
10396       CastKind != CK_AddressSpaceConversion)
10397     return NoParens;
10398 
10399   auto *SubExpr = Cast->getSubExpr();
10400   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
10401     return NoParens;
10402   return ignorePointerCastsAndParens(SubExpr);
10403 }
10404 
10405 /// Checks to see if the given LValue's Designator is at the end of the LValue's
10406 /// record layout. e.g.
10407 ///   struct { struct { int a, b; } fst, snd; } obj;
10408 ///   obj.fst   // no
10409 ///   obj.snd   // yes
10410 ///   obj.fst.a // no
10411 ///   obj.fst.b // no
10412 ///   obj.snd.a // no
10413 ///   obj.snd.b // yes
10414 ///
10415 /// Please note: this function is specialized for how __builtin_object_size
10416 /// views "objects".
10417 ///
10418 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
10419 /// correct result, it will always return true.
10420 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
10421   assert(!LVal.Designator.Invalid);
10422 
10423   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
10424     const RecordDecl *Parent = FD->getParent();
10425     Invalid = Parent->isInvalidDecl();
10426     if (Invalid || Parent->isUnion())
10427       return true;
10428     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
10429     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
10430   };
10431 
10432   auto &Base = LVal.getLValueBase();
10433   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
10434     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
10435       bool Invalid;
10436       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10437         return Invalid;
10438     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
10439       for (auto *FD : IFD->chain()) {
10440         bool Invalid;
10441         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
10442           return Invalid;
10443       }
10444     }
10445   }
10446 
10447   unsigned I = 0;
10448   QualType BaseType = getType(Base);
10449   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
10450     // If we don't know the array bound, conservatively assume we're looking at
10451     // the final array element.
10452     ++I;
10453     if (BaseType->isIncompleteArrayType())
10454       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
10455     else
10456       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
10457   }
10458 
10459   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
10460     const auto &Entry = LVal.Designator.Entries[I];
10461     if (BaseType->isArrayType()) {
10462       // Because __builtin_object_size treats arrays as objects, we can ignore
10463       // the index iff this is the last array in the Designator.
10464       if (I + 1 == E)
10465         return true;
10466       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
10467       uint64_t Index = Entry.getAsArrayIndex();
10468       if (Index + 1 != CAT->getSize())
10469         return false;
10470       BaseType = CAT->getElementType();
10471     } else if (BaseType->isAnyComplexType()) {
10472       const auto *CT = BaseType->castAs<ComplexType>();
10473       uint64_t Index = Entry.getAsArrayIndex();
10474       if (Index != 1)
10475         return false;
10476       BaseType = CT->getElementType();
10477     } else if (auto *FD = getAsField(Entry)) {
10478       bool Invalid;
10479       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10480         return Invalid;
10481       BaseType = FD->getType();
10482     } else {
10483       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
10484       return false;
10485     }
10486   }
10487   return true;
10488 }
10489 
10490 /// Tests to see if the LValue has a user-specified designator (that isn't
10491 /// necessarily valid). Note that this always returns 'true' if the LValue has
10492 /// an unsized array as its first designator entry, because there's currently no
10493 /// way to tell if the user typed *foo or foo[0].
10494 static bool refersToCompleteObject(const LValue &LVal) {
10495   if (LVal.Designator.Invalid)
10496     return false;
10497 
10498   if (!LVal.Designator.Entries.empty())
10499     return LVal.Designator.isMostDerivedAnUnsizedArray();
10500 
10501   if (!LVal.InvalidBase)
10502     return true;
10503 
10504   // If `E` is a MemberExpr, then the first part of the designator is hiding in
10505   // the LValueBase.
10506   const auto *E = LVal.Base.dyn_cast<const Expr *>();
10507   return !E || !isa<MemberExpr>(E);
10508 }
10509 
10510 /// Attempts to detect a user writing into a piece of memory that's impossible
10511 /// to figure out the size of by just using types.
10512 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
10513   const SubobjectDesignator &Designator = LVal.Designator;
10514   // Notes:
10515   // - Users can only write off of the end when we have an invalid base. Invalid
10516   //   bases imply we don't know where the memory came from.
10517   // - We used to be a bit more aggressive here; we'd only be conservative if
10518   //   the array at the end was flexible, or if it had 0 or 1 elements. This
10519   //   broke some common standard library extensions (PR30346), but was
10520   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
10521   //   with some sort of whitelist. OTOH, it seems that GCC is always
10522   //   conservative with the last element in structs (if it's an array), so our
10523   //   current behavior is more compatible than a whitelisting approach would
10524   //   be.
10525   return LVal.InvalidBase &&
10526          Designator.Entries.size() == Designator.MostDerivedPathLength &&
10527          Designator.MostDerivedIsArrayElement &&
10528          isDesignatorAtObjectEnd(Ctx, LVal);
10529 }
10530 
10531 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
10532 /// Fails if the conversion would cause loss of precision.
10533 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
10534                                             CharUnits &Result) {
10535   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
10536   if (Int.ugt(CharUnitsMax))
10537     return false;
10538   Result = CharUnits::fromQuantity(Int.getZExtValue());
10539   return true;
10540 }
10541 
10542 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
10543 /// determine how many bytes exist from the beginning of the object to either
10544 /// the end of the current subobject, or the end of the object itself, depending
10545 /// on what the LValue looks like + the value of Type.
10546 ///
10547 /// If this returns false, the value of Result is undefined.
10548 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
10549                                unsigned Type, const LValue &LVal,
10550                                CharUnits &EndOffset) {
10551   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
10552 
10553   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
10554     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
10555       return false;
10556     return HandleSizeof(Info, ExprLoc, Ty, Result);
10557   };
10558 
10559   // We want to evaluate the size of the entire object. This is a valid fallback
10560   // for when Type=1 and the designator is invalid, because we're asked for an
10561   // upper-bound.
10562   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
10563     // Type=3 wants a lower bound, so we can't fall back to this.
10564     if (Type == 3 && !DetermineForCompleteObject)
10565       return false;
10566 
10567     llvm::APInt APEndOffset;
10568     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10569         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10570       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10571 
10572     if (LVal.InvalidBase)
10573       return false;
10574 
10575     QualType BaseTy = getObjectType(LVal.getLValueBase());
10576     return CheckedHandleSizeof(BaseTy, EndOffset);
10577   }
10578 
10579   // We want to evaluate the size of a subobject.
10580   const SubobjectDesignator &Designator = LVal.Designator;
10581 
10582   // The following is a moderately common idiom in C:
10583   //
10584   // struct Foo { int a; char c[1]; };
10585   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
10586   // strcpy(&F->c[0], Bar);
10587   //
10588   // In order to not break too much legacy code, we need to support it.
10589   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
10590     // If we can resolve this to an alloc_size call, we can hand that back,
10591     // because we know for certain how many bytes there are to write to.
10592     llvm::APInt APEndOffset;
10593     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10594         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10595       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10596 
10597     // If we cannot determine the size of the initial allocation, then we can't
10598     // given an accurate upper-bound. However, we are still able to give
10599     // conservative lower-bounds for Type=3.
10600     if (Type == 1)
10601       return false;
10602   }
10603 
10604   CharUnits BytesPerElem;
10605   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
10606     return false;
10607 
10608   // According to the GCC documentation, we want the size of the subobject
10609   // denoted by the pointer. But that's not quite right -- what we actually
10610   // want is the size of the immediately-enclosing array, if there is one.
10611   int64_t ElemsRemaining;
10612   if (Designator.MostDerivedIsArrayElement &&
10613       Designator.Entries.size() == Designator.MostDerivedPathLength) {
10614     uint64_t ArraySize = Designator.getMostDerivedArraySize();
10615     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
10616     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
10617   } else {
10618     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
10619   }
10620 
10621   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
10622   return true;
10623 }
10624 
10625 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
10626 /// returns true and stores the result in @p Size.
10627 ///
10628 /// If @p WasError is non-null, this will report whether the failure to evaluate
10629 /// is to be treated as an Error in IntExprEvaluator.
10630 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
10631                                          EvalInfo &Info, uint64_t &Size) {
10632   // Determine the denoted object.
10633   LValue LVal;
10634   {
10635     // The operand of __builtin_object_size is never evaluated for side-effects.
10636     // If there are any, but we can determine the pointed-to object anyway, then
10637     // ignore the side-effects.
10638     SpeculativeEvaluationRAII SpeculativeEval(Info);
10639     IgnoreSideEffectsRAII Fold(Info);
10640 
10641     if (E->isGLValue()) {
10642       // It's possible for us to be given GLValues if we're called via
10643       // Expr::tryEvaluateObjectSize.
10644       APValue RVal;
10645       if (!EvaluateAsRValue(Info, E, RVal))
10646         return false;
10647       LVal.setFrom(Info.Ctx, RVal);
10648     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
10649                                 /*InvalidBaseOK=*/true))
10650       return false;
10651   }
10652 
10653   // If we point to before the start of the object, there are no accessible
10654   // bytes.
10655   if (LVal.getLValueOffset().isNegative()) {
10656     Size = 0;
10657     return true;
10658   }
10659 
10660   CharUnits EndOffset;
10661   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
10662     return false;
10663 
10664   // If we've fallen outside of the end offset, just pretend there's nothing to
10665   // write to/read from.
10666   if (EndOffset <= LVal.getLValueOffset())
10667     Size = 0;
10668   else
10669     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
10670   return true;
10671 }
10672 
10673 bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
10674   llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
10675   if (E->getResultAPValueKind() != APValue::None)
10676     return Success(E->getAPValueResult(), E);
10677   return ExprEvaluatorBaseTy::VisitConstantExpr(E);
10678 }
10679 
10680 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
10681   if (unsigned BuiltinOp = E->getBuiltinCallee())
10682     return VisitBuiltinCallExpr(E, BuiltinOp);
10683 
10684   return ExprEvaluatorBaseTy::VisitCallExpr(E);
10685 }
10686 
10687 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
10688                                      APValue &Val, APSInt &Alignment) {
10689   QualType SrcTy = E->getArg(0)->getType();
10690   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
10691     return false;
10692   // Even though we are evaluating integer expressions we could get a pointer
10693   // argument for the __builtin_is_aligned() case.
10694   if (SrcTy->isPointerType()) {
10695     LValue Ptr;
10696     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
10697       return false;
10698     Ptr.moveInto(Val);
10699   } else if (!SrcTy->isIntegralOrEnumerationType()) {
10700     Info.FFDiag(E->getArg(0));
10701     return false;
10702   } else {
10703     APSInt SrcInt;
10704     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
10705       return false;
10706     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
10707            "Bit widths must be the same");
10708     Val = APValue(SrcInt);
10709   }
10710   assert(Val.hasValue());
10711   return true;
10712 }
10713 
10714 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10715                                             unsigned BuiltinOp) {
10716   switch (BuiltinOp) {
10717   default:
10718     return ExprEvaluatorBaseTy::VisitCallExpr(E);
10719 
10720   case Builtin::BI__builtin_dynamic_object_size:
10721   case Builtin::BI__builtin_object_size: {
10722     // The type was checked when we built the expression.
10723     unsigned Type =
10724         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
10725     assert(Type <= 3 && "unexpected type");
10726 
10727     uint64_t Size;
10728     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
10729       return Success(Size, E);
10730 
10731     if (E->getArg(0)->HasSideEffects(Info.Ctx))
10732       return Success((Type & 2) ? 0 : -1, E);
10733 
10734     // Expression had no side effects, but we couldn't statically determine the
10735     // size of the referenced object.
10736     switch (Info.EvalMode) {
10737     case EvalInfo::EM_ConstantExpression:
10738     case EvalInfo::EM_ConstantFold:
10739     case EvalInfo::EM_IgnoreSideEffects:
10740       // Leave it to IR generation.
10741       return Error(E);
10742     case EvalInfo::EM_ConstantExpressionUnevaluated:
10743       // Reduce it to a constant now.
10744       return Success((Type & 2) ? 0 : -1, E);
10745     }
10746 
10747     llvm_unreachable("unexpected EvalMode");
10748   }
10749 
10750   case Builtin::BI__builtin_os_log_format_buffer_size: {
10751     analyze_os_log::OSLogBufferLayout Layout;
10752     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
10753     return Success(Layout.size().getQuantity(), E);
10754   }
10755 
10756   case Builtin::BI__builtin_is_aligned: {
10757     APValue Src;
10758     APSInt Alignment;
10759     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
10760       return false;
10761     if (Src.isLValue()) {
10762       // If we evaluated a pointer, check the minimum known alignment.
10763       LValue Ptr;
10764       Ptr.setFrom(Info.Ctx, Src);
10765       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
10766       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
10767       // We can return true if the known alignment at the computed offset is
10768       // greater than the requested alignment.
10769       assert(PtrAlign.isPowerOfTwo());
10770       assert(Alignment.isPowerOf2());
10771       if (PtrAlign.getQuantity() >= Alignment)
10772         return Success(1, E);
10773       // If the alignment is not known to be sufficient, some cases could still
10774       // be aligned at run time. However, if the requested alignment is less or
10775       // equal to the base alignment and the offset is not aligned, we know that
10776       // the run-time value can never be aligned.
10777       if (BaseAlignment.getQuantity() >= Alignment &&
10778           PtrAlign.getQuantity() < Alignment)
10779         return Success(0, E);
10780       // Otherwise we can't infer whether the value is sufficiently aligned.
10781       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
10782       //  in cases where we can't fully evaluate the pointer.
10783       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
10784           << Alignment;
10785       return false;
10786     }
10787     assert(Src.isInt());
10788     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
10789   }
10790   case Builtin::BI__builtin_align_up: {
10791     APValue Src;
10792     APSInt Alignment;
10793     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
10794       return false;
10795     if (!Src.isInt())
10796       return Error(E);
10797     APSInt AlignedVal =
10798         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
10799                Src.getInt().isUnsigned());
10800     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
10801     return Success(AlignedVal, E);
10802   }
10803   case Builtin::BI__builtin_align_down: {
10804     APValue Src;
10805     APSInt Alignment;
10806     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
10807       return false;
10808     if (!Src.isInt())
10809       return Error(E);
10810     APSInt AlignedVal =
10811         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
10812     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
10813     return Success(AlignedVal, E);
10814   }
10815 
10816   case Builtin::BI__builtin_bswap16:
10817   case Builtin::BI__builtin_bswap32:
10818   case Builtin::BI__builtin_bswap64: {
10819     APSInt Val;
10820     if (!EvaluateInteger(E->getArg(0), Val, Info))
10821       return false;
10822 
10823     return Success(Val.byteSwap(), E);
10824   }
10825 
10826   case Builtin::BI__builtin_classify_type:
10827     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
10828 
10829   case Builtin::BI__builtin_clrsb:
10830   case Builtin::BI__builtin_clrsbl:
10831   case Builtin::BI__builtin_clrsbll: {
10832     APSInt Val;
10833     if (!EvaluateInteger(E->getArg(0), Val, Info))
10834       return false;
10835 
10836     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
10837   }
10838 
10839   case Builtin::BI__builtin_clz:
10840   case Builtin::BI__builtin_clzl:
10841   case Builtin::BI__builtin_clzll:
10842   case Builtin::BI__builtin_clzs: {
10843     APSInt Val;
10844     if (!EvaluateInteger(E->getArg(0), Val, Info))
10845       return false;
10846     if (!Val)
10847       return Error(E);
10848 
10849     return Success(Val.countLeadingZeros(), E);
10850   }
10851 
10852   case Builtin::BI__builtin_constant_p: {
10853     const Expr *Arg = E->getArg(0);
10854     if (EvaluateBuiltinConstantP(Info, Arg))
10855       return Success(true, E);
10856     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
10857       // Outside a constant context, eagerly evaluate to false in the presence
10858       // of side-effects in order to avoid -Wunsequenced false-positives in
10859       // a branch on __builtin_constant_p(expr).
10860       return Success(false, E);
10861     }
10862     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10863     return false;
10864   }
10865 
10866   case Builtin::BI__builtin_is_constant_evaluated: {
10867     const auto *Callee = Info.CurrentCall->getCallee();
10868     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
10869         (Info.CallStackDepth == 1 ||
10870          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
10871           Callee->getIdentifier() &&
10872           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
10873       // FIXME: Find a better way to avoid duplicated diagnostics.
10874       if (Info.EvalStatus.Diag)
10875         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
10876                                                : Info.CurrentCall->CallLoc,
10877                     diag::warn_is_constant_evaluated_always_true_constexpr)
10878             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
10879                                          : "std::is_constant_evaluated");
10880     }
10881 
10882     return Success(Info.InConstantContext, E);
10883   }
10884 
10885   case Builtin::BI__builtin_ctz:
10886   case Builtin::BI__builtin_ctzl:
10887   case Builtin::BI__builtin_ctzll:
10888   case Builtin::BI__builtin_ctzs: {
10889     APSInt Val;
10890     if (!EvaluateInteger(E->getArg(0), Val, Info))
10891       return false;
10892     if (!Val)
10893       return Error(E);
10894 
10895     return Success(Val.countTrailingZeros(), E);
10896   }
10897 
10898   case Builtin::BI__builtin_eh_return_data_regno: {
10899     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
10900     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
10901     return Success(Operand, E);
10902   }
10903 
10904   case Builtin::BI__builtin_expect:
10905     return Visit(E->getArg(0));
10906 
10907   case Builtin::BI__builtin_ffs:
10908   case Builtin::BI__builtin_ffsl:
10909   case Builtin::BI__builtin_ffsll: {
10910     APSInt Val;
10911     if (!EvaluateInteger(E->getArg(0), Val, Info))
10912       return false;
10913 
10914     unsigned N = Val.countTrailingZeros();
10915     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
10916   }
10917 
10918   case Builtin::BI__builtin_fpclassify: {
10919     APFloat Val(0.0);
10920     if (!EvaluateFloat(E->getArg(5), Val, Info))
10921       return false;
10922     unsigned Arg;
10923     switch (Val.getCategory()) {
10924     case APFloat::fcNaN: Arg = 0; break;
10925     case APFloat::fcInfinity: Arg = 1; break;
10926     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
10927     case APFloat::fcZero: Arg = 4; break;
10928     }
10929     return Visit(E->getArg(Arg));
10930   }
10931 
10932   case Builtin::BI__builtin_isinf_sign: {
10933     APFloat Val(0.0);
10934     return EvaluateFloat(E->getArg(0), Val, Info) &&
10935            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
10936   }
10937 
10938   case Builtin::BI__builtin_isinf: {
10939     APFloat Val(0.0);
10940     return EvaluateFloat(E->getArg(0), Val, Info) &&
10941            Success(Val.isInfinity() ? 1 : 0, E);
10942   }
10943 
10944   case Builtin::BI__builtin_isfinite: {
10945     APFloat Val(0.0);
10946     return EvaluateFloat(E->getArg(0), Val, Info) &&
10947            Success(Val.isFinite() ? 1 : 0, E);
10948   }
10949 
10950   case Builtin::BI__builtin_isnan: {
10951     APFloat Val(0.0);
10952     return EvaluateFloat(E->getArg(0), Val, Info) &&
10953            Success(Val.isNaN() ? 1 : 0, E);
10954   }
10955 
10956   case Builtin::BI__builtin_isnormal: {
10957     APFloat Val(0.0);
10958     return EvaluateFloat(E->getArg(0), Val, Info) &&
10959            Success(Val.isNormal() ? 1 : 0, E);
10960   }
10961 
10962   case Builtin::BI__builtin_parity:
10963   case Builtin::BI__builtin_parityl:
10964   case Builtin::BI__builtin_parityll: {
10965     APSInt Val;
10966     if (!EvaluateInteger(E->getArg(0), Val, Info))
10967       return false;
10968 
10969     return Success(Val.countPopulation() % 2, E);
10970   }
10971 
10972   case Builtin::BI__builtin_popcount:
10973   case Builtin::BI__builtin_popcountl:
10974   case Builtin::BI__builtin_popcountll: {
10975     APSInt Val;
10976     if (!EvaluateInteger(E->getArg(0), Val, Info))
10977       return false;
10978 
10979     return Success(Val.countPopulation(), E);
10980   }
10981 
10982   case Builtin::BIstrlen:
10983   case Builtin::BIwcslen:
10984     // A call to strlen is not a constant expression.
10985     if (Info.getLangOpts().CPlusPlus11)
10986       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
10987         << /*isConstexpr*/0 << /*isConstructor*/0
10988         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
10989     else
10990       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
10991     LLVM_FALLTHROUGH;
10992   case Builtin::BI__builtin_strlen:
10993   case Builtin::BI__builtin_wcslen: {
10994     // As an extension, we support __builtin_strlen() as a constant expression,
10995     // and support folding strlen() to a constant.
10996     LValue String;
10997     if (!EvaluatePointer(E->getArg(0), String, Info))
10998       return false;
10999 
11000     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
11001 
11002     // Fast path: if it's a string literal, search the string value.
11003     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
11004             String.getLValueBase().dyn_cast<const Expr *>())) {
11005       // The string literal may have embedded null characters. Find the first
11006       // one and truncate there.
11007       StringRef Str = S->getBytes();
11008       int64_t Off = String.Offset.getQuantity();
11009       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
11010           S->getCharByteWidth() == 1 &&
11011           // FIXME: Add fast-path for wchar_t too.
11012           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
11013         Str = Str.substr(Off);
11014 
11015         StringRef::size_type Pos = Str.find(0);
11016         if (Pos != StringRef::npos)
11017           Str = Str.substr(0, Pos);
11018 
11019         return Success(Str.size(), E);
11020       }
11021 
11022       // Fall through to slow path to issue appropriate diagnostic.
11023     }
11024 
11025     // Slow path: scan the bytes of the string looking for the terminating 0.
11026     for (uint64_t Strlen = 0; /**/; ++Strlen) {
11027       APValue Char;
11028       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
11029           !Char.isInt())
11030         return false;
11031       if (!Char.getInt())
11032         return Success(Strlen, E);
11033       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
11034         return false;
11035     }
11036   }
11037 
11038   case Builtin::BIstrcmp:
11039   case Builtin::BIwcscmp:
11040   case Builtin::BIstrncmp:
11041   case Builtin::BIwcsncmp:
11042   case Builtin::BImemcmp:
11043   case Builtin::BIbcmp:
11044   case Builtin::BIwmemcmp:
11045     // A call to strlen is not a constant expression.
11046     if (Info.getLangOpts().CPlusPlus11)
11047       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11048         << /*isConstexpr*/0 << /*isConstructor*/0
11049         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11050     else
11051       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11052     LLVM_FALLTHROUGH;
11053   case Builtin::BI__builtin_strcmp:
11054   case Builtin::BI__builtin_wcscmp:
11055   case Builtin::BI__builtin_strncmp:
11056   case Builtin::BI__builtin_wcsncmp:
11057   case Builtin::BI__builtin_memcmp:
11058   case Builtin::BI__builtin_bcmp:
11059   case Builtin::BI__builtin_wmemcmp: {
11060     LValue String1, String2;
11061     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
11062         !EvaluatePointer(E->getArg(1), String2, Info))
11063       return false;
11064 
11065     uint64_t MaxLength = uint64_t(-1);
11066     if (BuiltinOp != Builtin::BIstrcmp &&
11067         BuiltinOp != Builtin::BIwcscmp &&
11068         BuiltinOp != Builtin::BI__builtin_strcmp &&
11069         BuiltinOp != Builtin::BI__builtin_wcscmp) {
11070       APSInt N;
11071       if (!EvaluateInteger(E->getArg(2), N, Info))
11072         return false;
11073       MaxLength = N.getExtValue();
11074     }
11075 
11076     // Empty substrings compare equal by definition.
11077     if (MaxLength == 0u)
11078       return Success(0, E);
11079 
11080     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11081         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11082         String1.Designator.Invalid || String2.Designator.Invalid)
11083       return false;
11084 
11085     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
11086     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
11087 
11088     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
11089                      BuiltinOp == Builtin::BIbcmp ||
11090                      BuiltinOp == Builtin::BI__builtin_memcmp ||
11091                      BuiltinOp == Builtin::BI__builtin_bcmp;
11092 
11093     assert(IsRawByte ||
11094            (Info.Ctx.hasSameUnqualifiedType(
11095                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
11096             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
11097 
11098     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
11099       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
11100              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
11101              Char1.isInt() && Char2.isInt();
11102     };
11103     const auto &AdvanceElems = [&] {
11104       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
11105              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
11106     };
11107 
11108     if (IsRawByte) {
11109       uint64_t BytesRemaining = MaxLength;
11110       // Pointers to const void may point to objects of incomplete type.
11111       if (CharTy1->isIncompleteType()) {
11112         Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
11113         return false;
11114       }
11115       if (CharTy2->isIncompleteType()) {
11116         Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
11117         return false;
11118       }
11119       uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
11120       CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
11121       // Give up on comparing between elements with disparate widths.
11122       if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
11123         return false;
11124       uint64_t BytesPerElement = CharTy1Size.getQuantity();
11125       assert(BytesRemaining && "BytesRemaining should not be zero: the "
11126                                "following loop considers at least one element");
11127       while (true) {
11128         APValue Char1, Char2;
11129         if (!ReadCurElems(Char1, Char2))
11130           return false;
11131         // We have compatible in-memory widths, but a possible type and
11132         // (for `bool`) internal representation mismatch.
11133         // Assuming two's complement representation, including 0 for `false` and
11134         // 1 for `true`, we can check an appropriate number of elements for
11135         // equality even if they are not byte-sized.
11136         APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
11137         APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
11138         if (Char1InMem.ne(Char2InMem)) {
11139           // If the elements are byte-sized, then we can produce a three-way
11140           // comparison result in a straightforward manner.
11141           if (BytesPerElement == 1u) {
11142             // memcmp always compares unsigned chars.
11143             return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
11144           }
11145           // The result is byte-order sensitive, and we have multibyte elements.
11146           // FIXME: We can compare the remaining bytes in the correct order.
11147           return false;
11148         }
11149         if (!AdvanceElems())
11150           return false;
11151         if (BytesRemaining <= BytesPerElement)
11152           break;
11153         BytesRemaining -= BytesPerElement;
11154       }
11155       // Enough elements are equal to account for the memcmp limit.
11156       return Success(0, E);
11157     }
11158 
11159     bool StopAtNull =
11160         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
11161          BuiltinOp != Builtin::BIwmemcmp &&
11162          BuiltinOp != Builtin::BI__builtin_memcmp &&
11163          BuiltinOp != Builtin::BI__builtin_bcmp &&
11164          BuiltinOp != Builtin::BI__builtin_wmemcmp);
11165     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
11166                   BuiltinOp == Builtin::BIwcsncmp ||
11167                   BuiltinOp == Builtin::BIwmemcmp ||
11168                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
11169                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
11170                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
11171 
11172     for (; MaxLength; --MaxLength) {
11173       APValue Char1, Char2;
11174       if (!ReadCurElems(Char1, Char2))
11175         return false;
11176       if (Char1.getInt() != Char2.getInt()) {
11177         if (IsWide) // wmemcmp compares with wchar_t signedness.
11178           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
11179         // memcmp always compares unsigned chars.
11180         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
11181       }
11182       if (StopAtNull && !Char1.getInt())
11183         return Success(0, E);
11184       assert(!(StopAtNull && !Char2.getInt()));
11185       if (!AdvanceElems())
11186         return false;
11187     }
11188     // We hit the strncmp / memcmp limit.
11189     return Success(0, E);
11190   }
11191 
11192   case Builtin::BI__atomic_always_lock_free:
11193   case Builtin::BI__atomic_is_lock_free:
11194   case Builtin::BI__c11_atomic_is_lock_free: {
11195     APSInt SizeVal;
11196     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
11197       return false;
11198 
11199     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
11200     // of two less than the maximum inline atomic width, we know it is
11201     // lock-free.  If the size isn't a power of two, or greater than the
11202     // maximum alignment where we promote atomics, we know it is not lock-free
11203     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
11204     // the answer can only be determined at runtime; for example, 16-byte
11205     // atomics have lock-free implementations on some, but not all,
11206     // x86-64 processors.
11207 
11208     // Check power-of-two.
11209     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
11210     if (Size.isPowerOfTwo()) {
11211       // Check against inlining width.
11212       unsigned InlineWidthBits =
11213           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
11214       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
11215         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
11216             Size == CharUnits::One() ||
11217             E->getArg(1)->isNullPointerConstant(Info.Ctx,
11218                                                 Expr::NPC_NeverValueDependent))
11219           // OK, we will inline appropriately-aligned operations of this size,
11220           // and _Atomic(T) is appropriately-aligned.
11221           return Success(1, E);
11222 
11223         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
11224           castAs<PointerType>()->getPointeeType();
11225         if (!PointeeType->isIncompleteType() &&
11226             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
11227           // OK, we will inline operations on this object.
11228           return Success(1, E);
11229         }
11230       }
11231     }
11232 
11233     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
11234         Success(0, E) : Error(E);
11235   }
11236   case Builtin::BIomp_is_initial_device:
11237     // We can decide statically which value the runtime would return if called.
11238     return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
11239   case Builtin::BI__builtin_add_overflow:
11240   case Builtin::BI__builtin_sub_overflow:
11241   case Builtin::BI__builtin_mul_overflow:
11242   case Builtin::BI__builtin_sadd_overflow:
11243   case Builtin::BI__builtin_uadd_overflow:
11244   case Builtin::BI__builtin_uaddl_overflow:
11245   case Builtin::BI__builtin_uaddll_overflow:
11246   case Builtin::BI__builtin_usub_overflow:
11247   case Builtin::BI__builtin_usubl_overflow:
11248   case Builtin::BI__builtin_usubll_overflow:
11249   case Builtin::BI__builtin_umul_overflow:
11250   case Builtin::BI__builtin_umull_overflow:
11251   case Builtin::BI__builtin_umulll_overflow:
11252   case Builtin::BI__builtin_saddl_overflow:
11253   case Builtin::BI__builtin_saddll_overflow:
11254   case Builtin::BI__builtin_ssub_overflow:
11255   case Builtin::BI__builtin_ssubl_overflow:
11256   case Builtin::BI__builtin_ssubll_overflow:
11257   case Builtin::BI__builtin_smul_overflow:
11258   case Builtin::BI__builtin_smull_overflow:
11259   case Builtin::BI__builtin_smulll_overflow: {
11260     LValue ResultLValue;
11261     APSInt LHS, RHS;
11262 
11263     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
11264     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
11265         !EvaluateInteger(E->getArg(1), RHS, Info) ||
11266         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
11267       return false;
11268 
11269     APSInt Result;
11270     bool DidOverflow = false;
11271 
11272     // If the types don't have to match, enlarge all 3 to the largest of them.
11273     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11274         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11275         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11276       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
11277                       ResultType->isSignedIntegerOrEnumerationType();
11278       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
11279                       ResultType->isSignedIntegerOrEnumerationType();
11280       uint64_t LHSSize = LHS.getBitWidth();
11281       uint64_t RHSSize = RHS.getBitWidth();
11282       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
11283       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
11284 
11285       // Add an additional bit if the signedness isn't uniformly agreed to. We
11286       // could do this ONLY if there is a signed and an unsigned that both have
11287       // MaxBits, but the code to check that is pretty nasty.  The issue will be
11288       // caught in the shrink-to-result later anyway.
11289       if (IsSigned && !AllSigned)
11290         ++MaxBits;
11291 
11292       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
11293       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
11294       Result = APSInt(MaxBits, !IsSigned);
11295     }
11296 
11297     // Find largest int.
11298     switch (BuiltinOp) {
11299     default:
11300       llvm_unreachable("Invalid value for BuiltinOp");
11301     case Builtin::BI__builtin_add_overflow:
11302     case Builtin::BI__builtin_sadd_overflow:
11303     case Builtin::BI__builtin_saddl_overflow:
11304     case Builtin::BI__builtin_saddll_overflow:
11305     case Builtin::BI__builtin_uadd_overflow:
11306     case Builtin::BI__builtin_uaddl_overflow:
11307     case Builtin::BI__builtin_uaddll_overflow:
11308       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
11309                               : LHS.uadd_ov(RHS, DidOverflow);
11310       break;
11311     case Builtin::BI__builtin_sub_overflow:
11312     case Builtin::BI__builtin_ssub_overflow:
11313     case Builtin::BI__builtin_ssubl_overflow:
11314     case Builtin::BI__builtin_ssubll_overflow:
11315     case Builtin::BI__builtin_usub_overflow:
11316     case Builtin::BI__builtin_usubl_overflow:
11317     case Builtin::BI__builtin_usubll_overflow:
11318       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
11319                               : LHS.usub_ov(RHS, DidOverflow);
11320       break;
11321     case Builtin::BI__builtin_mul_overflow:
11322     case Builtin::BI__builtin_smul_overflow:
11323     case Builtin::BI__builtin_smull_overflow:
11324     case Builtin::BI__builtin_smulll_overflow:
11325     case Builtin::BI__builtin_umul_overflow:
11326     case Builtin::BI__builtin_umull_overflow:
11327     case Builtin::BI__builtin_umulll_overflow:
11328       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
11329                               : LHS.umul_ov(RHS, DidOverflow);
11330       break;
11331     }
11332 
11333     // In the case where multiple sizes are allowed, truncate and see if
11334     // the values are the same.
11335     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11336         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11337         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11338       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
11339       // since it will give us the behavior of a TruncOrSelf in the case where
11340       // its parameter <= its size.  We previously set Result to be at least the
11341       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
11342       // will work exactly like TruncOrSelf.
11343       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
11344       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
11345 
11346       if (!APSInt::isSameValue(Temp, Result))
11347         DidOverflow = true;
11348       Result = Temp;
11349     }
11350 
11351     APValue APV{Result};
11352     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
11353       return false;
11354     return Success(DidOverflow, E);
11355   }
11356   }
11357 }
11358 
11359 /// Determine whether this is a pointer past the end of the complete
11360 /// object referred to by the lvalue.
11361 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
11362                                             const LValue &LV) {
11363   // A null pointer can be viewed as being "past the end" but we don't
11364   // choose to look at it that way here.
11365   if (!LV.getLValueBase())
11366     return false;
11367 
11368   // If the designator is valid and refers to a subobject, we're not pointing
11369   // past the end.
11370   if (!LV.getLValueDesignator().Invalid &&
11371       !LV.getLValueDesignator().isOnePastTheEnd())
11372     return false;
11373 
11374   // A pointer to an incomplete type might be past-the-end if the type's size is
11375   // zero.  We cannot tell because the type is incomplete.
11376   QualType Ty = getType(LV.getLValueBase());
11377   if (Ty->isIncompleteType())
11378     return true;
11379 
11380   // We're a past-the-end pointer if we point to the byte after the object,
11381   // no matter what our type or path is.
11382   auto Size = Ctx.getTypeSizeInChars(Ty);
11383   return LV.getLValueOffset() == Size;
11384 }
11385 
11386 namespace {
11387 
11388 /// Data recursive integer evaluator of certain binary operators.
11389 ///
11390 /// We use a data recursive algorithm for binary operators so that we are able
11391 /// to handle extreme cases of chained binary operators without causing stack
11392 /// overflow.
11393 class DataRecursiveIntBinOpEvaluator {
11394   struct EvalResult {
11395     APValue Val;
11396     bool Failed;
11397 
11398     EvalResult() : Failed(false) { }
11399 
11400     void swap(EvalResult &RHS) {
11401       Val.swap(RHS.Val);
11402       Failed = RHS.Failed;
11403       RHS.Failed = false;
11404     }
11405   };
11406 
11407   struct Job {
11408     const Expr *E;
11409     EvalResult LHSResult; // meaningful only for binary operator expression.
11410     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
11411 
11412     Job() = default;
11413     Job(Job &&) = default;
11414 
11415     void startSpeculativeEval(EvalInfo &Info) {
11416       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
11417     }
11418 
11419   private:
11420     SpeculativeEvaluationRAII SpecEvalRAII;
11421   };
11422 
11423   SmallVector<Job, 16> Queue;
11424 
11425   IntExprEvaluator &IntEval;
11426   EvalInfo &Info;
11427   APValue &FinalResult;
11428 
11429 public:
11430   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
11431     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
11432 
11433   /// True if \param E is a binary operator that we are going to handle
11434   /// data recursively.
11435   /// We handle binary operators that are comma, logical, or that have operands
11436   /// with integral or enumeration type.
11437   static bool shouldEnqueue(const BinaryOperator *E) {
11438     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
11439            (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
11440             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11441             E->getRHS()->getType()->isIntegralOrEnumerationType());
11442   }
11443 
11444   bool Traverse(const BinaryOperator *E) {
11445     enqueue(E);
11446     EvalResult PrevResult;
11447     while (!Queue.empty())
11448       process(PrevResult);
11449 
11450     if (PrevResult.Failed) return false;
11451 
11452     FinalResult.swap(PrevResult.Val);
11453     return true;
11454   }
11455 
11456 private:
11457   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11458     return IntEval.Success(Value, E, Result);
11459   }
11460   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
11461     return IntEval.Success(Value, E, Result);
11462   }
11463   bool Error(const Expr *E) {
11464     return IntEval.Error(E);
11465   }
11466   bool Error(const Expr *E, diag::kind D) {
11467     return IntEval.Error(E, D);
11468   }
11469 
11470   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
11471     return Info.CCEDiag(E, D);
11472   }
11473 
11474   // Returns true if visiting the RHS is necessary, false otherwise.
11475   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
11476                          bool &SuppressRHSDiags);
11477 
11478   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
11479                   const BinaryOperator *E, APValue &Result);
11480 
11481   void EvaluateExpr(const Expr *E, EvalResult &Result) {
11482     Result.Failed = !Evaluate(Result.Val, Info, E);
11483     if (Result.Failed)
11484       Result.Val = APValue();
11485   }
11486 
11487   void process(EvalResult &Result);
11488 
11489   void enqueue(const Expr *E) {
11490     E = E->IgnoreParens();
11491     Queue.resize(Queue.size()+1);
11492     Queue.back().E = E;
11493     Queue.back().Kind = Job::AnyExprKind;
11494   }
11495 };
11496 
11497 }
11498 
11499 bool DataRecursiveIntBinOpEvaluator::
11500        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
11501                          bool &SuppressRHSDiags) {
11502   if (E->getOpcode() == BO_Comma) {
11503     // Ignore LHS but note if we could not evaluate it.
11504     if (LHSResult.Failed)
11505       return Info.noteSideEffect();
11506     return true;
11507   }
11508 
11509   if (E->isLogicalOp()) {
11510     bool LHSAsBool;
11511     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
11512       // We were able to evaluate the LHS, see if we can get away with not
11513       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
11514       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
11515         Success(LHSAsBool, E, LHSResult.Val);
11516         return false; // Ignore RHS
11517       }
11518     } else {
11519       LHSResult.Failed = true;
11520 
11521       // Since we weren't able to evaluate the left hand side, it
11522       // might have had side effects.
11523       if (!Info.noteSideEffect())
11524         return false;
11525 
11526       // We can't evaluate the LHS; however, sometimes the result
11527       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
11528       // Don't ignore RHS and suppress diagnostics from this arm.
11529       SuppressRHSDiags = true;
11530     }
11531 
11532     return true;
11533   }
11534 
11535   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11536          E->getRHS()->getType()->isIntegralOrEnumerationType());
11537 
11538   if (LHSResult.Failed && !Info.noteFailure())
11539     return false; // Ignore RHS;
11540 
11541   return true;
11542 }
11543 
11544 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
11545                                     bool IsSub) {
11546   // Compute the new offset in the appropriate width, wrapping at 64 bits.
11547   // FIXME: When compiling for a 32-bit target, we should use 32-bit
11548   // offsets.
11549   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
11550   CharUnits &Offset = LVal.getLValueOffset();
11551   uint64_t Offset64 = Offset.getQuantity();
11552   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
11553   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
11554                                          : Offset64 + Index64);
11555 }
11556 
11557 bool DataRecursiveIntBinOpEvaluator::
11558        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
11559                   const BinaryOperator *E, APValue &Result) {
11560   if (E->getOpcode() == BO_Comma) {
11561     if (RHSResult.Failed)
11562       return false;
11563     Result = RHSResult.Val;
11564     return true;
11565   }
11566 
11567   if (E->isLogicalOp()) {
11568     bool lhsResult, rhsResult;
11569     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
11570     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
11571 
11572     if (LHSIsOK) {
11573       if (RHSIsOK) {
11574         if (E->getOpcode() == BO_LOr)
11575           return Success(lhsResult || rhsResult, E, Result);
11576         else
11577           return Success(lhsResult && rhsResult, E, Result);
11578       }
11579     } else {
11580       if (RHSIsOK) {
11581         // We can't evaluate the LHS; however, sometimes the result
11582         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
11583         if (rhsResult == (E->getOpcode() == BO_LOr))
11584           return Success(rhsResult, E, Result);
11585       }
11586     }
11587 
11588     return false;
11589   }
11590 
11591   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11592          E->getRHS()->getType()->isIntegralOrEnumerationType());
11593 
11594   if (LHSResult.Failed || RHSResult.Failed)
11595     return false;
11596 
11597   const APValue &LHSVal = LHSResult.Val;
11598   const APValue &RHSVal = RHSResult.Val;
11599 
11600   // Handle cases like (unsigned long)&a + 4.
11601   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
11602     Result = LHSVal;
11603     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
11604     return true;
11605   }
11606 
11607   // Handle cases like 4 + (unsigned long)&a
11608   if (E->getOpcode() == BO_Add &&
11609       RHSVal.isLValue() && LHSVal.isInt()) {
11610     Result = RHSVal;
11611     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
11612     return true;
11613   }
11614 
11615   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
11616     // Handle (intptr_t)&&A - (intptr_t)&&B.
11617     if (!LHSVal.getLValueOffset().isZero() ||
11618         !RHSVal.getLValueOffset().isZero())
11619       return false;
11620     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
11621     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
11622     if (!LHSExpr || !RHSExpr)
11623       return false;
11624     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
11625     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
11626     if (!LHSAddrExpr || !RHSAddrExpr)
11627       return false;
11628     // Make sure both labels come from the same function.
11629     if (LHSAddrExpr->getLabel()->getDeclContext() !=
11630         RHSAddrExpr->getLabel()->getDeclContext())
11631       return false;
11632     Result = APValue(LHSAddrExpr, RHSAddrExpr);
11633     return true;
11634   }
11635 
11636   // All the remaining cases expect both operands to be an integer
11637   if (!LHSVal.isInt() || !RHSVal.isInt())
11638     return Error(E);
11639 
11640   // Set up the width and signedness manually, in case it can't be deduced
11641   // from the operation we're performing.
11642   // FIXME: Don't do this in the cases where we can deduce it.
11643   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
11644                E->getType()->isUnsignedIntegerOrEnumerationType());
11645   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
11646                          RHSVal.getInt(), Value))
11647     return false;
11648   return Success(Value, E, Result);
11649 }
11650 
11651 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
11652   Job &job = Queue.back();
11653 
11654   switch (job.Kind) {
11655     case Job::AnyExprKind: {
11656       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
11657         if (shouldEnqueue(Bop)) {
11658           job.Kind = Job::BinOpKind;
11659           enqueue(Bop->getLHS());
11660           return;
11661         }
11662       }
11663 
11664       EvaluateExpr(job.E, Result);
11665       Queue.pop_back();
11666       return;
11667     }
11668 
11669     case Job::BinOpKind: {
11670       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
11671       bool SuppressRHSDiags = false;
11672       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
11673         Queue.pop_back();
11674         return;
11675       }
11676       if (SuppressRHSDiags)
11677         job.startSpeculativeEval(Info);
11678       job.LHSResult.swap(Result);
11679       job.Kind = Job::BinOpVisitedLHSKind;
11680       enqueue(Bop->getRHS());
11681       return;
11682     }
11683 
11684     case Job::BinOpVisitedLHSKind: {
11685       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
11686       EvalResult RHS;
11687       RHS.swap(Result);
11688       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
11689       Queue.pop_back();
11690       return;
11691     }
11692   }
11693 
11694   llvm_unreachable("Invalid Job::Kind!");
11695 }
11696 
11697 namespace {
11698 /// Used when we determine that we should fail, but can keep evaluating prior to
11699 /// noting that we had a failure.
11700 class DelayedNoteFailureRAII {
11701   EvalInfo &Info;
11702   bool NoteFailure;
11703 
11704 public:
11705   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
11706       : Info(Info), NoteFailure(NoteFailure) {}
11707   ~DelayedNoteFailureRAII() {
11708     if (NoteFailure) {
11709       bool ContinueAfterFailure = Info.noteFailure();
11710       (void)ContinueAfterFailure;
11711       assert(ContinueAfterFailure &&
11712              "Shouldn't have kept evaluating on failure.");
11713     }
11714   }
11715 };
11716 
11717 enum class CmpResult {
11718   Unequal,
11719   Less,
11720   Equal,
11721   Greater,
11722   Unordered,
11723 };
11724 }
11725 
11726 template <class SuccessCB, class AfterCB>
11727 static bool
11728 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
11729                                  SuccessCB &&Success, AfterCB &&DoAfter) {
11730   assert(E->isComparisonOp() && "expected comparison operator");
11731   assert((E->getOpcode() == BO_Cmp ||
11732           E->getType()->isIntegralOrEnumerationType()) &&
11733          "unsupported binary expression evaluation");
11734   auto Error = [&](const Expr *E) {
11735     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11736     return false;
11737   };
11738 
11739   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
11740   bool IsEquality = E->isEqualityOp();
11741 
11742   QualType LHSTy = E->getLHS()->getType();
11743   QualType RHSTy = E->getRHS()->getType();
11744 
11745   if (LHSTy->isIntegralOrEnumerationType() &&
11746       RHSTy->isIntegralOrEnumerationType()) {
11747     APSInt LHS, RHS;
11748     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
11749     if (!LHSOK && !Info.noteFailure())
11750       return false;
11751     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
11752       return false;
11753     if (LHS < RHS)
11754       return Success(CmpResult::Less, E);
11755     if (LHS > RHS)
11756       return Success(CmpResult::Greater, E);
11757     return Success(CmpResult::Equal, E);
11758   }
11759 
11760   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
11761     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
11762     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
11763 
11764     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
11765     if (!LHSOK && !Info.noteFailure())
11766       return false;
11767     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
11768       return false;
11769     if (LHSFX < RHSFX)
11770       return Success(CmpResult::Less, E);
11771     if (LHSFX > RHSFX)
11772       return Success(CmpResult::Greater, E);
11773     return Success(CmpResult::Equal, E);
11774   }
11775 
11776   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
11777     ComplexValue LHS, RHS;
11778     bool LHSOK;
11779     if (E->isAssignmentOp()) {
11780       LValue LV;
11781       EvaluateLValue(E->getLHS(), LV, Info);
11782       LHSOK = false;
11783     } else if (LHSTy->isRealFloatingType()) {
11784       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
11785       if (LHSOK) {
11786         LHS.makeComplexFloat();
11787         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
11788       }
11789     } else {
11790       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
11791     }
11792     if (!LHSOK && !Info.noteFailure())
11793       return false;
11794 
11795     if (E->getRHS()->getType()->isRealFloatingType()) {
11796       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
11797         return false;
11798       RHS.makeComplexFloat();
11799       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
11800     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
11801       return false;
11802 
11803     if (LHS.isComplexFloat()) {
11804       APFloat::cmpResult CR_r =
11805         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
11806       APFloat::cmpResult CR_i =
11807         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
11808       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
11809       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
11810     } else {
11811       assert(IsEquality && "invalid complex comparison");
11812       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
11813                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
11814       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
11815     }
11816   }
11817 
11818   if (LHSTy->isRealFloatingType() &&
11819       RHSTy->isRealFloatingType()) {
11820     APFloat RHS(0.0), LHS(0.0);
11821 
11822     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
11823     if (!LHSOK && !Info.noteFailure())
11824       return false;
11825 
11826     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
11827       return false;
11828 
11829     assert(E->isComparisonOp() && "Invalid binary operator!");
11830     auto GetCmpRes = [&]() {
11831       switch (LHS.compare(RHS)) {
11832       case APFloat::cmpEqual:
11833         return CmpResult::Equal;
11834       case APFloat::cmpLessThan:
11835         return CmpResult::Less;
11836       case APFloat::cmpGreaterThan:
11837         return CmpResult::Greater;
11838       case APFloat::cmpUnordered:
11839         return CmpResult::Unordered;
11840       }
11841       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
11842     };
11843     return Success(GetCmpRes(), E);
11844   }
11845 
11846   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
11847     LValue LHSValue, RHSValue;
11848 
11849     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
11850     if (!LHSOK && !Info.noteFailure())
11851       return false;
11852 
11853     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
11854       return false;
11855 
11856     // Reject differing bases from the normal codepath; we special-case
11857     // comparisons to null.
11858     if (!HasSameBase(LHSValue, RHSValue)) {
11859       // Inequalities and subtractions between unrelated pointers have
11860       // unspecified or undefined behavior.
11861       if (!IsEquality) {
11862         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
11863         return false;
11864       }
11865       // A constant address may compare equal to the address of a symbol.
11866       // The one exception is that address of an object cannot compare equal
11867       // to a null pointer constant.
11868       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
11869           (!RHSValue.Base && !RHSValue.Offset.isZero()))
11870         return Error(E);
11871       // It's implementation-defined whether distinct literals will have
11872       // distinct addresses. In clang, the result of such a comparison is
11873       // unspecified, so it is not a constant expression. However, we do know
11874       // that the address of a literal will be non-null.
11875       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
11876           LHSValue.Base && RHSValue.Base)
11877         return Error(E);
11878       // We can't tell whether weak symbols will end up pointing to the same
11879       // object.
11880       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
11881         return Error(E);
11882       // We can't compare the address of the start of one object with the
11883       // past-the-end address of another object, per C++ DR1652.
11884       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
11885            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
11886           (RHSValue.Base && RHSValue.Offset.isZero() &&
11887            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
11888         return Error(E);
11889       // We can't tell whether an object is at the same address as another
11890       // zero sized object.
11891       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
11892           (LHSValue.Base && isZeroSized(RHSValue)))
11893         return Error(E);
11894       return Success(CmpResult::Unequal, E);
11895     }
11896 
11897     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
11898     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
11899 
11900     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
11901     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
11902 
11903     // C++11 [expr.rel]p3:
11904     //   Pointers to void (after pointer conversions) can be compared, with a
11905     //   result defined as follows: If both pointers represent the same
11906     //   address or are both the null pointer value, the result is true if the
11907     //   operator is <= or >= and false otherwise; otherwise the result is
11908     //   unspecified.
11909     // We interpret this as applying to pointers to *cv* void.
11910     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
11911       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
11912 
11913     // C++11 [expr.rel]p2:
11914     // - If two pointers point to non-static data members of the same object,
11915     //   or to subobjects or array elements fo such members, recursively, the
11916     //   pointer to the later declared member compares greater provided the
11917     //   two members have the same access control and provided their class is
11918     //   not a union.
11919     //   [...]
11920     // - Otherwise pointer comparisons are unspecified.
11921     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
11922       bool WasArrayIndex;
11923       unsigned Mismatch = FindDesignatorMismatch(
11924           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
11925       // At the point where the designators diverge, the comparison has a
11926       // specified value if:
11927       //  - we are comparing array indices
11928       //  - we are comparing fields of a union, or fields with the same access
11929       // Otherwise, the result is unspecified and thus the comparison is not a
11930       // constant expression.
11931       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
11932           Mismatch < RHSDesignator.Entries.size()) {
11933         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
11934         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
11935         if (!LF && !RF)
11936           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
11937         else if (!LF)
11938           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
11939               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
11940               << RF->getParent() << RF;
11941         else if (!RF)
11942           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
11943               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
11944               << LF->getParent() << LF;
11945         else if (!LF->getParent()->isUnion() &&
11946                  LF->getAccess() != RF->getAccess())
11947           Info.CCEDiag(E,
11948                        diag::note_constexpr_pointer_comparison_differing_access)
11949               << LF << LF->getAccess() << RF << RF->getAccess()
11950               << LF->getParent();
11951       }
11952     }
11953 
11954     // The comparison here must be unsigned, and performed with the same
11955     // width as the pointer.
11956     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
11957     uint64_t CompareLHS = LHSOffset.getQuantity();
11958     uint64_t CompareRHS = RHSOffset.getQuantity();
11959     assert(PtrSize <= 64 && "Unexpected pointer width");
11960     uint64_t Mask = ~0ULL >> (64 - PtrSize);
11961     CompareLHS &= Mask;
11962     CompareRHS &= Mask;
11963 
11964     // If there is a base and this is a relational operator, we can only
11965     // compare pointers within the object in question; otherwise, the result
11966     // depends on where the object is located in memory.
11967     if (!LHSValue.Base.isNull() && IsRelational) {
11968       QualType BaseTy = getType(LHSValue.Base);
11969       if (BaseTy->isIncompleteType())
11970         return Error(E);
11971       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
11972       uint64_t OffsetLimit = Size.getQuantity();
11973       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
11974         return Error(E);
11975     }
11976 
11977     if (CompareLHS < CompareRHS)
11978       return Success(CmpResult::Less, E);
11979     if (CompareLHS > CompareRHS)
11980       return Success(CmpResult::Greater, E);
11981     return Success(CmpResult::Equal, E);
11982   }
11983 
11984   if (LHSTy->isMemberPointerType()) {
11985     assert(IsEquality && "unexpected member pointer operation");
11986     assert(RHSTy->isMemberPointerType() && "invalid comparison");
11987 
11988     MemberPtr LHSValue, RHSValue;
11989 
11990     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
11991     if (!LHSOK && !Info.noteFailure())
11992       return false;
11993 
11994     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
11995       return false;
11996 
11997     // C++11 [expr.eq]p2:
11998     //   If both operands are null, they compare equal. Otherwise if only one is
11999     //   null, they compare unequal.
12000     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
12001       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
12002       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12003     }
12004 
12005     //   Otherwise if either is a pointer to a virtual member function, the
12006     //   result is unspecified.
12007     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
12008       if (MD->isVirtual())
12009         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12010     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
12011       if (MD->isVirtual())
12012         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12013 
12014     //   Otherwise they compare equal if and only if they would refer to the
12015     //   same member of the same most derived object or the same subobject if
12016     //   they were dereferenced with a hypothetical object of the associated
12017     //   class type.
12018     bool Equal = LHSValue == RHSValue;
12019     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12020   }
12021 
12022   if (LHSTy->isNullPtrType()) {
12023     assert(E->isComparisonOp() && "unexpected nullptr operation");
12024     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12025     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12026     // are compared, the result is true of the operator is <=, >= or ==, and
12027     // false otherwise.
12028     return Success(CmpResult::Equal, E);
12029   }
12030 
12031   return DoAfter();
12032 }
12033 
12034 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
12035   if (!CheckLiteralType(Info, E))
12036     return false;
12037 
12038   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12039     ComparisonCategoryResult CCR;
12040     switch (CR) {
12041     case CmpResult::Unequal:
12042       llvm_unreachable("should never produce Unequal for three-way comparison");
12043     case CmpResult::Less:
12044       CCR = ComparisonCategoryResult::Less;
12045       break;
12046     case CmpResult::Equal:
12047       CCR = ComparisonCategoryResult::Equal;
12048       break;
12049     case CmpResult::Greater:
12050       CCR = ComparisonCategoryResult::Greater;
12051       break;
12052     case CmpResult::Unordered:
12053       CCR = ComparisonCategoryResult::Unordered;
12054       break;
12055     }
12056     // Evaluation succeeded. Lookup the information for the comparison category
12057     // type and fetch the VarDecl for the result.
12058     const ComparisonCategoryInfo &CmpInfo =
12059         Info.Ctx.CompCategories.getInfoForType(E->getType());
12060     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
12061     // Check and evaluate the result as a constant expression.
12062     LValue LV;
12063     LV.set(VD);
12064     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12065       return false;
12066     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
12067   };
12068   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12069     return ExprEvaluatorBaseTy::VisitBinCmp(E);
12070   });
12071 }
12072 
12073 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12074   // We don't call noteFailure immediately because the assignment happens after
12075   // we evaluate LHS and RHS.
12076   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
12077     return Error(E);
12078 
12079   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
12080   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
12081     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
12082 
12083   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
12084           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
12085          "DataRecursiveIntBinOpEvaluator should have handled integral types");
12086 
12087   if (E->isComparisonOp()) {
12088     // Evaluate builtin binary comparisons by evaluating them as three-way
12089     // comparisons and then translating the result.
12090     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12091       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
12092              "should only produce Unequal for equality comparisons");
12093       bool IsEqual   = CR == CmpResult::Equal,
12094            IsLess    = CR == CmpResult::Less,
12095            IsGreater = CR == CmpResult::Greater;
12096       auto Op = E->getOpcode();
12097       switch (Op) {
12098       default:
12099         llvm_unreachable("unsupported binary operator");
12100       case BO_EQ:
12101       case BO_NE:
12102         return Success(IsEqual == (Op == BO_EQ), E);
12103       case BO_LT:
12104         return Success(IsLess, E);
12105       case BO_GT:
12106         return Success(IsGreater, E);
12107       case BO_LE:
12108         return Success(IsEqual || IsLess, E);
12109       case BO_GE:
12110         return Success(IsEqual || IsGreater, E);
12111       }
12112     };
12113     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12114       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12115     });
12116   }
12117 
12118   QualType LHSTy = E->getLHS()->getType();
12119   QualType RHSTy = E->getRHS()->getType();
12120 
12121   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
12122       E->getOpcode() == BO_Sub) {
12123     LValue LHSValue, RHSValue;
12124 
12125     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12126     if (!LHSOK && !Info.noteFailure())
12127       return false;
12128 
12129     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12130       return false;
12131 
12132     // Reject differing bases from the normal codepath; we special-case
12133     // comparisons to null.
12134     if (!HasSameBase(LHSValue, RHSValue)) {
12135       // Handle &&A - &&B.
12136       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
12137         return Error(E);
12138       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
12139       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
12140       if (!LHSExpr || !RHSExpr)
12141         return Error(E);
12142       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12143       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12144       if (!LHSAddrExpr || !RHSAddrExpr)
12145         return Error(E);
12146       // Make sure both labels come from the same function.
12147       if (LHSAddrExpr->getLabel()->getDeclContext() !=
12148           RHSAddrExpr->getLabel()->getDeclContext())
12149         return Error(E);
12150       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
12151     }
12152     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12153     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12154 
12155     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12156     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12157 
12158     // C++11 [expr.add]p6:
12159     //   Unless both pointers point to elements of the same array object, or
12160     //   one past the last element of the array object, the behavior is
12161     //   undefined.
12162     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
12163         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
12164                                 RHSDesignator))
12165       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
12166 
12167     QualType Type = E->getLHS()->getType();
12168     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
12169 
12170     CharUnits ElementSize;
12171     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
12172       return false;
12173 
12174     // As an extension, a type may have zero size (empty struct or union in
12175     // C, array of zero length). Pointer subtraction in such cases has
12176     // undefined behavior, so is not constant.
12177     if (ElementSize.isZero()) {
12178       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
12179           << ElementType;
12180       return false;
12181     }
12182 
12183     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
12184     // and produce incorrect results when it overflows. Such behavior
12185     // appears to be non-conforming, but is common, so perhaps we should
12186     // assume the standard intended for such cases to be undefined behavior
12187     // and check for them.
12188 
12189     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
12190     // overflow in the final conversion to ptrdiff_t.
12191     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
12192     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
12193     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
12194                     false);
12195     APSInt TrueResult = (LHS - RHS) / ElemSize;
12196     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
12197 
12198     if (Result.extend(65) != TrueResult &&
12199         !HandleOverflow(Info, E, TrueResult, E->getType()))
12200       return false;
12201     return Success(Result, E);
12202   }
12203 
12204   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12205 }
12206 
12207 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
12208 /// a result as the expression's type.
12209 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
12210                                     const UnaryExprOrTypeTraitExpr *E) {
12211   switch(E->getKind()) {
12212   case UETT_PreferredAlignOf:
12213   case UETT_AlignOf: {
12214     if (E->isArgumentType())
12215       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
12216                      E);
12217     else
12218       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
12219                      E);
12220   }
12221 
12222   case UETT_VecStep: {
12223     QualType Ty = E->getTypeOfArgument();
12224 
12225     if (Ty->isVectorType()) {
12226       unsigned n = Ty->castAs<VectorType>()->getNumElements();
12227 
12228       // The vec_step built-in functions that take a 3-component
12229       // vector return 4. (OpenCL 1.1 spec 6.11.12)
12230       if (n == 3)
12231         n = 4;
12232 
12233       return Success(n, E);
12234     } else
12235       return Success(1, E);
12236   }
12237 
12238   case UETT_SizeOf: {
12239     QualType SrcTy = E->getTypeOfArgument();
12240     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
12241     //   the result is the size of the referenced type."
12242     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
12243       SrcTy = Ref->getPointeeType();
12244 
12245     CharUnits Sizeof;
12246     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
12247       return false;
12248     return Success(Sizeof, E);
12249   }
12250   case UETT_OpenMPRequiredSimdAlign:
12251     assert(E->isArgumentType());
12252     return Success(
12253         Info.Ctx.toCharUnitsFromBits(
12254                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
12255             .getQuantity(),
12256         E);
12257   }
12258 
12259   llvm_unreachable("unknown expr/type trait");
12260 }
12261 
12262 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
12263   CharUnits Result;
12264   unsigned n = OOE->getNumComponents();
12265   if (n == 0)
12266     return Error(OOE);
12267   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
12268   for (unsigned i = 0; i != n; ++i) {
12269     OffsetOfNode ON = OOE->getComponent(i);
12270     switch (ON.getKind()) {
12271     case OffsetOfNode::Array: {
12272       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
12273       APSInt IdxResult;
12274       if (!EvaluateInteger(Idx, IdxResult, Info))
12275         return false;
12276       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
12277       if (!AT)
12278         return Error(OOE);
12279       CurrentType = AT->getElementType();
12280       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
12281       Result += IdxResult.getSExtValue() * ElementSize;
12282       break;
12283     }
12284 
12285     case OffsetOfNode::Field: {
12286       FieldDecl *MemberDecl = ON.getField();
12287       const RecordType *RT = CurrentType->getAs<RecordType>();
12288       if (!RT)
12289         return Error(OOE);
12290       RecordDecl *RD = RT->getDecl();
12291       if (RD->isInvalidDecl()) return false;
12292       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
12293       unsigned i = MemberDecl->getFieldIndex();
12294       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
12295       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
12296       CurrentType = MemberDecl->getType().getNonReferenceType();
12297       break;
12298     }
12299 
12300     case OffsetOfNode::Identifier:
12301       llvm_unreachable("dependent __builtin_offsetof");
12302 
12303     case OffsetOfNode::Base: {
12304       CXXBaseSpecifier *BaseSpec = ON.getBase();
12305       if (BaseSpec->isVirtual())
12306         return Error(OOE);
12307 
12308       // Find the layout of the class whose base we are looking into.
12309       const RecordType *RT = CurrentType->getAs<RecordType>();
12310       if (!RT)
12311         return Error(OOE);
12312       RecordDecl *RD = RT->getDecl();
12313       if (RD->isInvalidDecl()) return false;
12314       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
12315 
12316       // Find the base class itself.
12317       CurrentType = BaseSpec->getType();
12318       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
12319       if (!BaseRT)
12320         return Error(OOE);
12321 
12322       // Add the offset to the base.
12323       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
12324       break;
12325     }
12326     }
12327   }
12328   return Success(Result, OOE);
12329 }
12330 
12331 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12332   switch (E->getOpcode()) {
12333   default:
12334     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
12335     // See C99 6.6p3.
12336     return Error(E);
12337   case UO_Extension:
12338     // FIXME: Should extension allow i-c-e extension expressions in its scope?
12339     // If so, we could clear the diagnostic ID.
12340     return Visit(E->getSubExpr());
12341   case UO_Plus:
12342     // The result is just the value.
12343     return Visit(E->getSubExpr());
12344   case UO_Minus: {
12345     if (!Visit(E->getSubExpr()))
12346       return false;
12347     if (!Result.isInt()) return Error(E);
12348     const APSInt &Value = Result.getInt();
12349     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
12350         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
12351                         E->getType()))
12352       return false;
12353     return Success(-Value, E);
12354   }
12355   case UO_Not: {
12356     if (!Visit(E->getSubExpr()))
12357       return false;
12358     if (!Result.isInt()) return Error(E);
12359     return Success(~Result.getInt(), E);
12360   }
12361   case UO_LNot: {
12362     bool bres;
12363     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
12364       return false;
12365     return Success(!bres, E);
12366   }
12367   }
12368 }
12369 
12370 /// HandleCast - This is used to evaluate implicit or explicit casts where the
12371 /// result type is integer.
12372 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
12373   const Expr *SubExpr = E->getSubExpr();
12374   QualType DestType = E->getType();
12375   QualType SrcType = SubExpr->getType();
12376 
12377   switch (E->getCastKind()) {
12378   case CK_BaseToDerived:
12379   case CK_DerivedToBase:
12380   case CK_UncheckedDerivedToBase:
12381   case CK_Dynamic:
12382   case CK_ToUnion:
12383   case CK_ArrayToPointerDecay:
12384   case CK_FunctionToPointerDecay:
12385   case CK_NullToPointer:
12386   case CK_NullToMemberPointer:
12387   case CK_BaseToDerivedMemberPointer:
12388   case CK_DerivedToBaseMemberPointer:
12389   case CK_ReinterpretMemberPointer:
12390   case CK_ConstructorConversion:
12391   case CK_IntegralToPointer:
12392   case CK_ToVoid:
12393   case CK_VectorSplat:
12394   case CK_IntegralToFloating:
12395   case CK_FloatingCast:
12396   case CK_CPointerToObjCPointerCast:
12397   case CK_BlockPointerToObjCPointerCast:
12398   case CK_AnyPointerToBlockPointerCast:
12399   case CK_ObjCObjectLValueCast:
12400   case CK_FloatingRealToComplex:
12401   case CK_FloatingComplexToReal:
12402   case CK_FloatingComplexCast:
12403   case CK_FloatingComplexToIntegralComplex:
12404   case CK_IntegralRealToComplex:
12405   case CK_IntegralComplexCast:
12406   case CK_IntegralComplexToFloatingComplex:
12407   case CK_BuiltinFnToFnPtr:
12408   case CK_ZeroToOCLOpaqueType:
12409   case CK_NonAtomicToAtomic:
12410   case CK_AddressSpaceConversion:
12411   case CK_IntToOCLSampler:
12412   case CK_FixedPointCast:
12413   case CK_IntegralToFixedPoint:
12414     llvm_unreachable("invalid cast kind for integral value");
12415 
12416   case CK_BitCast:
12417   case CK_Dependent:
12418   case CK_LValueBitCast:
12419   case CK_ARCProduceObject:
12420   case CK_ARCConsumeObject:
12421   case CK_ARCReclaimReturnedObject:
12422   case CK_ARCExtendBlockObject:
12423   case CK_CopyAndAutoreleaseBlockObject:
12424     return Error(E);
12425 
12426   case CK_UserDefinedConversion:
12427   case CK_LValueToRValue:
12428   case CK_AtomicToNonAtomic:
12429   case CK_NoOp:
12430   case CK_LValueToRValueBitCast:
12431     return ExprEvaluatorBaseTy::VisitCastExpr(E);
12432 
12433   case CK_MemberPointerToBoolean:
12434   case CK_PointerToBoolean:
12435   case CK_IntegralToBoolean:
12436   case CK_FloatingToBoolean:
12437   case CK_BooleanToSignedIntegral:
12438   case CK_FloatingComplexToBoolean:
12439   case CK_IntegralComplexToBoolean: {
12440     bool BoolResult;
12441     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
12442       return false;
12443     uint64_t IntResult = BoolResult;
12444     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
12445       IntResult = (uint64_t)-1;
12446     return Success(IntResult, E);
12447   }
12448 
12449   case CK_FixedPointToIntegral: {
12450     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
12451     if (!EvaluateFixedPoint(SubExpr, Src, Info))
12452       return false;
12453     bool Overflowed;
12454     llvm::APSInt Result = Src.convertToInt(
12455         Info.Ctx.getIntWidth(DestType),
12456         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
12457     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
12458       return false;
12459     return Success(Result, E);
12460   }
12461 
12462   case CK_FixedPointToBoolean: {
12463     // Unsigned padding does not affect this.
12464     APValue Val;
12465     if (!Evaluate(Val, Info, SubExpr))
12466       return false;
12467     return Success(Val.getFixedPoint().getBoolValue(), E);
12468   }
12469 
12470   case CK_IntegralCast: {
12471     if (!Visit(SubExpr))
12472       return false;
12473 
12474     if (!Result.isInt()) {
12475       // Allow casts of address-of-label differences if they are no-ops
12476       // or narrowing.  (The narrowing case isn't actually guaranteed to
12477       // be constant-evaluatable except in some narrow cases which are hard
12478       // to detect here.  We let it through on the assumption the user knows
12479       // what they are doing.)
12480       if (Result.isAddrLabelDiff())
12481         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
12482       // Only allow casts of lvalues if they are lossless.
12483       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
12484     }
12485 
12486     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
12487                                       Result.getInt()), E);
12488   }
12489 
12490   case CK_PointerToIntegral: {
12491     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
12492 
12493     LValue LV;
12494     if (!EvaluatePointer(SubExpr, LV, Info))
12495       return false;
12496 
12497     if (LV.getLValueBase()) {
12498       // Only allow based lvalue casts if they are lossless.
12499       // FIXME: Allow a larger integer size than the pointer size, and allow
12500       // narrowing back down to pointer width in subsequent integral casts.
12501       // FIXME: Check integer type's active bits, not its type size.
12502       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
12503         return Error(E);
12504 
12505       LV.Designator.setInvalid();
12506       LV.moveInto(Result);
12507       return true;
12508     }
12509 
12510     APSInt AsInt;
12511     APValue V;
12512     LV.moveInto(V);
12513     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
12514       llvm_unreachable("Can't cast this!");
12515 
12516     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
12517   }
12518 
12519   case CK_IntegralComplexToReal: {
12520     ComplexValue C;
12521     if (!EvaluateComplex(SubExpr, C, Info))
12522       return false;
12523     return Success(C.getComplexIntReal(), E);
12524   }
12525 
12526   case CK_FloatingToIntegral: {
12527     APFloat F(0.0);
12528     if (!EvaluateFloat(SubExpr, F, Info))
12529       return false;
12530 
12531     APSInt Value;
12532     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
12533       return false;
12534     return Success(Value, E);
12535   }
12536   }
12537 
12538   llvm_unreachable("unknown cast resulting in integral value");
12539 }
12540 
12541 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
12542   if (E->getSubExpr()->getType()->isAnyComplexType()) {
12543     ComplexValue LV;
12544     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
12545       return false;
12546     if (!LV.isComplexInt())
12547       return Error(E);
12548     return Success(LV.getComplexIntReal(), E);
12549   }
12550 
12551   return Visit(E->getSubExpr());
12552 }
12553 
12554 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
12555   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
12556     ComplexValue LV;
12557     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
12558       return false;
12559     if (!LV.isComplexInt())
12560       return Error(E);
12561     return Success(LV.getComplexIntImag(), E);
12562   }
12563 
12564   VisitIgnoredValue(E->getSubExpr());
12565   return Success(0, E);
12566 }
12567 
12568 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
12569   return Success(E->getPackLength(), E);
12570 }
12571 
12572 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
12573   return Success(E->getValue(), E);
12574 }
12575 
12576 bool IntExprEvaluator::VisitConceptSpecializationExpr(
12577        const ConceptSpecializationExpr *E) {
12578   return Success(E->isSatisfied(), E);
12579 }
12580 
12581 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
12582   return Success(E->isSatisfied(), E);
12583 }
12584 
12585 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12586   switch (E->getOpcode()) {
12587     default:
12588       // Invalid unary operators
12589       return Error(E);
12590     case UO_Plus:
12591       // The result is just the value.
12592       return Visit(E->getSubExpr());
12593     case UO_Minus: {
12594       if (!Visit(E->getSubExpr())) return false;
12595       if (!Result.isFixedPoint())
12596         return Error(E);
12597       bool Overflowed;
12598       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
12599       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
12600         return false;
12601       return Success(Negated, E);
12602     }
12603     case UO_LNot: {
12604       bool bres;
12605       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
12606         return false;
12607       return Success(!bres, E);
12608     }
12609   }
12610 }
12611 
12612 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
12613   const Expr *SubExpr = E->getSubExpr();
12614   QualType DestType = E->getType();
12615   assert(DestType->isFixedPointType() &&
12616          "Expected destination type to be a fixed point type");
12617   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
12618 
12619   switch (E->getCastKind()) {
12620   case CK_FixedPointCast: {
12621     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
12622     if (!EvaluateFixedPoint(SubExpr, Src, Info))
12623       return false;
12624     bool Overflowed;
12625     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
12626     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
12627       return false;
12628     return Success(Result, E);
12629   }
12630   case CK_IntegralToFixedPoint: {
12631     APSInt Src;
12632     if (!EvaluateInteger(SubExpr, Src, Info))
12633       return false;
12634 
12635     bool Overflowed;
12636     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
12637         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
12638 
12639     if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
12640       return false;
12641 
12642     return Success(IntResult, E);
12643   }
12644   case CK_NoOp:
12645   case CK_LValueToRValue:
12646     return ExprEvaluatorBaseTy::VisitCastExpr(E);
12647   default:
12648     return Error(E);
12649   }
12650 }
12651 
12652 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12653   const Expr *LHS = E->getLHS();
12654   const Expr *RHS = E->getRHS();
12655   FixedPointSemantics ResultFXSema =
12656       Info.Ctx.getFixedPointSemantics(E->getType());
12657 
12658   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
12659   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
12660     return false;
12661   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
12662   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
12663     return false;
12664 
12665   switch (E->getOpcode()) {
12666   case BO_Add: {
12667     bool AddOverflow, ConversionOverflow;
12668     APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
12669                               .convert(ResultFXSema, &ConversionOverflow);
12670     if ((AddOverflow || ConversionOverflow) &&
12671         !HandleOverflow(Info, E, Result, E->getType()))
12672       return false;
12673     return Success(Result, E);
12674   }
12675   default:
12676     return false;
12677   }
12678   llvm_unreachable("Should've exited before this");
12679 }
12680 
12681 //===----------------------------------------------------------------------===//
12682 // Float Evaluation
12683 //===----------------------------------------------------------------------===//
12684 
12685 namespace {
12686 class FloatExprEvaluator
12687   : public ExprEvaluatorBase<FloatExprEvaluator> {
12688   APFloat &Result;
12689 public:
12690   FloatExprEvaluator(EvalInfo &info, APFloat &result)
12691     : ExprEvaluatorBaseTy(info), Result(result) {}
12692 
12693   bool Success(const APValue &V, const Expr *e) {
12694     Result = V.getFloat();
12695     return true;
12696   }
12697 
12698   bool ZeroInitialization(const Expr *E) {
12699     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
12700     return true;
12701   }
12702 
12703   bool VisitCallExpr(const CallExpr *E);
12704 
12705   bool VisitUnaryOperator(const UnaryOperator *E);
12706   bool VisitBinaryOperator(const BinaryOperator *E);
12707   bool VisitFloatingLiteral(const FloatingLiteral *E);
12708   bool VisitCastExpr(const CastExpr *E);
12709 
12710   bool VisitUnaryReal(const UnaryOperator *E);
12711   bool VisitUnaryImag(const UnaryOperator *E);
12712 
12713   // FIXME: Missing: array subscript of vector, member of vector
12714 };
12715 } // end anonymous namespace
12716 
12717 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
12718   assert(E->isRValue() && E->getType()->isRealFloatingType());
12719   return FloatExprEvaluator(Info, Result).Visit(E);
12720 }
12721 
12722 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
12723                                   QualType ResultTy,
12724                                   const Expr *Arg,
12725                                   bool SNaN,
12726                                   llvm::APFloat &Result) {
12727   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
12728   if (!S) return false;
12729 
12730   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
12731 
12732   llvm::APInt fill;
12733 
12734   // Treat empty strings as if they were zero.
12735   if (S->getString().empty())
12736     fill = llvm::APInt(32, 0);
12737   else if (S->getString().getAsInteger(0, fill))
12738     return false;
12739 
12740   if (Context.getTargetInfo().isNan2008()) {
12741     if (SNaN)
12742       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
12743     else
12744       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
12745   } else {
12746     // Prior to IEEE 754-2008, architectures were allowed to choose whether
12747     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
12748     // a different encoding to what became a standard in 2008, and for pre-
12749     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
12750     // sNaN. This is now known as "legacy NaN" encoding.
12751     if (SNaN)
12752       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
12753     else
12754       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
12755   }
12756 
12757   return true;
12758 }
12759 
12760 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
12761   switch (E->getBuiltinCallee()) {
12762   default:
12763     return ExprEvaluatorBaseTy::VisitCallExpr(E);
12764 
12765   case Builtin::BI__builtin_huge_val:
12766   case Builtin::BI__builtin_huge_valf:
12767   case Builtin::BI__builtin_huge_vall:
12768   case Builtin::BI__builtin_huge_valf128:
12769   case Builtin::BI__builtin_inf:
12770   case Builtin::BI__builtin_inff:
12771   case Builtin::BI__builtin_infl:
12772   case Builtin::BI__builtin_inff128: {
12773     const llvm::fltSemantics &Sem =
12774       Info.Ctx.getFloatTypeSemantics(E->getType());
12775     Result = llvm::APFloat::getInf(Sem);
12776     return true;
12777   }
12778 
12779   case Builtin::BI__builtin_nans:
12780   case Builtin::BI__builtin_nansf:
12781   case Builtin::BI__builtin_nansl:
12782   case Builtin::BI__builtin_nansf128:
12783     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
12784                                true, Result))
12785       return Error(E);
12786     return true;
12787 
12788   case Builtin::BI__builtin_nan:
12789   case Builtin::BI__builtin_nanf:
12790   case Builtin::BI__builtin_nanl:
12791   case Builtin::BI__builtin_nanf128:
12792     // If this is __builtin_nan() turn this into a nan, otherwise we
12793     // can't constant fold it.
12794     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
12795                                false, Result))
12796       return Error(E);
12797     return true;
12798 
12799   case Builtin::BI__builtin_fabs:
12800   case Builtin::BI__builtin_fabsf:
12801   case Builtin::BI__builtin_fabsl:
12802   case Builtin::BI__builtin_fabsf128:
12803     if (!EvaluateFloat(E->getArg(0), Result, Info))
12804       return false;
12805 
12806     if (Result.isNegative())
12807       Result.changeSign();
12808     return true;
12809 
12810   // FIXME: Builtin::BI__builtin_powi
12811   // FIXME: Builtin::BI__builtin_powif
12812   // FIXME: Builtin::BI__builtin_powil
12813 
12814   case Builtin::BI__builtin_copysign:
12815   case Builtin::BI__builtin_copysignf:
12816   case Builtin::BI__builtin_copysignl:
12817   case Builtin::BI__builtin_copysignf128: {
12818     APFloat RHS(0.);
12819     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
12820         !EvaluateFloat(E->getArg(1), RHS, Info))
12821       return false;
12822     Result.copySign(RHS);
12823     return true;
12824   }
12825   }
12826 }
12827 
12828 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
12829   if (E->getSubExpr()->getType()->isAnyComplexType()) {
12830     ComplexValue CV;
12831     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
12832       return false;
12833     Result = CV.FloatReal;
12834     return true;
12835   }
12836 
12837   return Visit(E->getSubExpr());
12838 }
12839 
12840 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
12841   if (E->getSubExpr()->getType()->isAnyComplexType()) {
12842     ComplexValue CV;
12843     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
12844       return false;
12845     Result = CV.FloatImag;
12846     return true;
12847   }
12848 
12849   VisitIgnoredValue(E->getSubExpr());
12850   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
12851   Result = llvm::APFloat::getZero(Sem);
12852   return true;
12853 }
12854 
12855 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12856   switch (E->getOpcode()) {
12857   default: return Error(E);
12858   case UO_Plus:
12859     return EvaluateFloat(E->getSubExpr(), Result, Info);
12860   case UO_Minus:
12861     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
12862       return false;
12863     Result.changeSign();
12864     return true;
12865   }
12866 }
12867 
12868 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12869   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
12870     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12871 
12872   APFloat RHS(0.0);
12873   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
12874   if (!LHSOK && !Info.noteFailure())
12875     return false;
12876   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
12877          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
12878 }
12879 
12880 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
12881   Result = E->getValue();
12882   return true;
12883 }
12884 
12885 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
12886   const Expr* SubExpr = E->getSubExpr();
12887 
12888   switch (E->getCastKind()) {
12889   default:
12890     return ExprEvaluatorBaseTy::VisitCastExpr(E);
12891 
12892   case CK_IntegralToFloating: {
12893     APSInt IntResult;
12894     return EvaluateInteger(SubExpr, IntResult, Info) &&
12895            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
12896                                 E->getType(), Result);
12897   }
12898 
12899   case CK_FloatingCast: {
12900     if (!Visit(SubExpr))
12901       return false;
12902     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
12903                                   Result);
12904   }
12905 
12906   case CK_FloatingComplexToReal: {
12907     ComplexValue V;
12908     if (!EvaluateComplex(SubExpr, V, Info))
12909       return false;
12910     Result = V.getComplexFloatReal();
12911     return true;
12912   }
12913   }
12914 }
12915 
12916 //===----------------------------------------------------------------------===//
12917 // Complex Evaluation (for float and integer)
12918 //===----------------------------------------------------------------------===//
12919 
12920 namespace {
12921 class ComplexExprEvaluator
12922   : public ExprEvaluatorBase<ComplexExprEvaluator> {
12923   ComplexValue &Result;
12924 
12925 public:
12926   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
12927     : ExprEvaluatorBaseTy(info), Result(Result) {}
12928 
12929   bool Success(const APValue &V, const Expr *e) {
12930     Result.setFrom(V);
12931     return true;
12932   }
12933 
12934   bool ZeroInitialization(const Expr *E);
12935 
12936   //===--------------------------------------------------------------------===//
12937   //                            Visitor Methods
12938   //===--------------------------------------------------------------------===//
12939 
12940   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
12941   bool VisitCastExpr(const CastExpr *E);
12942   bool VisitBinaryOperator(const BinaryOperator *E);
12943   bool VisitUnaryOperator(const UnaryOperator *E);
12944   bool VisitInitListExpr(const InitListExpr *E);
12945 };
12946 } // end anonymous namespace
12947 
12948 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
12949                             EvalInfo &Info) {
12950   assert(E->isRValue() && E->getType()->isAnyComplexType());
12951   return ComplexExprEvaluator(Info, Result).Visit(E);
12952 }
12953 
12954 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
12955   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
12956   if (ElemTy->isRealFloatingType()) {
12957     Result.makeComplexFloat();
12958     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
12959     Result.FloatReal = Zero;
12960     Result.FloatImag = Zero;
12961   } else {
12962     Result.makeComplexInt();
12963     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
12964     Result.IntReal = Zero;
12965     Result.IntImag = Zero;
12966   }
12967   return true;
12968 }
12969 
12970 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
12971   const Expr* SubExpr = E->getSubExpr();
12972 
12973   if (SubExpr->getType()->isRealFloatingType()) {
12974     Result.makeComplexFloat();
12975     APFloat &Imag = Result.FloatImag;
12976     if (!EvaluateFloat(SubExpr, Imag, Info))
12977       return false;
12978 
12979     Result.FloatReal = APFloat(Imag.getSemantics());
12980     return true;
12981   } else {
12982     assert(SubExpr->getType()->isIntegerType() &&
12983            "Unexpected imaginary literal.");
12984 
12985     Result.makeComplexInt();
12986     APSInt &Imag = Result.IntImag;
12987     if (!EvaluateInteger(SubExpr, Imag, Info))
12988       return false;
12989 
12990     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
12991     return true;
12992   }
12993 }
12994 
12995 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
12996 
12997   switch (E->getCastKind()) {
12998   case CK_BitCast:
12999   case CK_BaseToDerived:
13000   case CK_DerivedToBase:
13001   case CK_UncheckedDerivedToBase:
13002   case CK_Dynamic:
13003   case CK_ToUnion:
13004   case CK_ArrayToPointerDecay:
13005   case CK_FunctionToPointerDecay:
13006   case CK_NullToPointer:
13007   case CK_NullToMemberPointer:
13008   case CK_BaseToDerivedMemberPointer:
13009   case CK_DerivedToBaseMemberPointer:
13010   case CK_MemberPointerToBoolean:
13011   case CK_ReinterpretMemberPointer:
13012   case CK_ConstructorConversion:
13013   case CK_IntegralToPointer:
13014   case CK_PointerToIntegral:
13015   case CK_PointerToBoolean:
13016   case CK_ToVoid:
13017   case CK_VectorSplat:
13018   case CK_IntegralCast:
13019   case CK_BooleanToSignedIntegral:
13020   case CK_IntegralToBoolean:
13021   case CK_IntegralToFloating:
13022   case CK_FloatingToIntegral:
13023   case CK_FloatingToBoolean:
13024   case CK_FloatingCast:
13025   case CK_CPointerToObjCPointerCast:
13026   case CK_BlockPointerToObjCPointerCast:
13027   case CK_AnyPointerToBlockPointerCast:
13028   case CK_ObjCObjectLValueCast:
13029   case CK_FloatingComplexToReal:
13030   case CK_FloatingComplexToBoolean:
13031   case CK_IntegralComplexToReal:
13032   case CK_IntegralComplexToBoolean:
13033   case CK_ARCProduceObject:
13034   case CK_ARCConsumeObject:
13035   case CK_ARCReclaimReturnedObject:
13036   case CK_ARCExtendBlockObject:
13037   case CK_CopyAndAutoreleaseBlockObject:
13038   case CK_BuiltinFnToFnPtr:
13039   case CK_ZeroToOCLOpaqueType:
13040   case CK_NonAtomicToAtomic:
13041   case CK_AddressSpaceConversion:
13042   case CK_IntToOCLSampler:
13043   case CK_FixedPointCast:
13044   case CK_FixedPointToBoolean:
13045   case CK_FixedPointToIntegral:
13046   case CK_IntegralToFixedPoint:
13047     llvm_unreachable("invalid cast kind for complex value");
13048 
13049   case CK_LValueToRValue:
13050   case CK_AtomicToNonAtomic:
13051   case CK_NoOp:
13052   case CK_LValueToRValueBitCast:
13053     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13054 
13055   case CK_Dependent:
13056   case CK_LValueBitCast:
13057   case CK_UserDefinedConversion:
13058     return Error(E);
13059 
13060   case CK_FloatingRealToComplex: {
13061     APFloat &Real = Result.FloatReal;
13062     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
13063       return false;
13064 
13065     Result.makeComplexFloat();
13066     Result.FloatImag = APFloat(Real.getSemantics());
13067     return true;
13068   }
13069 
13070   case CK_FloatingComplexCast: {
13071     if (!Visit(E->getSubExpr()))
13072       return false;
13073 
13074     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13075     QualType From
13076       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13077 
13078     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
13079            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
13080   }
13081 
13082   case CK_FloatingComplexToIntegralComplex: {
13083     if (!Visit(E->getSubExpr()))
13084       return false;
13085 
13086     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13087     QualType From
13088       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13089     Result.makeComplexInt();
13090     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
13091                                 To, Result.IntReal) &&
13092            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
13093                                 To, Result.IntImag);
13094   }
13095 
13096   case CK_IntegralRealToComplex: {
13097     APSInt &Real = Result.IntReal;
13098     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
13099       return false;
13100 
13101     Result.makeComplexInt();
13102     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
13103     return true;
13104   }
13105 
13106   case CK_IntegralComplexCast: {
13107     if (!Visit(E->getSubExpr()))
13108       return false;
13109 
13110     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13111     QualType From
13112       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13113 
13114     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
13115     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
13116     return true;
13117   }
13118 
13119   case CK_IntegralComplexToFloatingComplex: {
13120     if (!Visit(E->getSubExpr()))
13121       return false;
13122 
13123     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13124     QualType From
13125       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13126     Result.makeComplexFloat();
13127     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
13128                                 To, Result.FloatReal) &&
13129            HandleIntToFloatCast(Info, E, From, Result.IntImag,
13130                                 To, Result.FloatImag);
13131   }
13132   }
13133 
13134   llvm_unreachable("unknown cast resulting in complex value");
13135 }
13136 
13137 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13138   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13139     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13140 
13141   // Track whether the LHS or RHS is real at the type system level. When this is
13142   // the case we can simplify our evaluation strategy.
13143   bool LHSReal = false, RHSReal = false;
13144 
13145   bool LHSOK;
13146   if (E->getLHS()->getType()->isRealFloatingType()) {
13147     LHSReal = true;
13148     APFloat &Real = Result.FloatReal;
13149     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
13150     if (LHSOK) {
13151       Result.makeComplexFloat();
13152       Result.FloatImag = APFloat(Real.getSemantics());
13153     }
13154   } else {
13155     LHSOK = Visit(E->getLHS());
13156   }
13157   if (!LHSOK && !Info.noteFailure())
13158     return false;
13159 
13160   ComplexValue RHS;
13161   if (E->getRHS()->getType()->isRealFloatingType()) {
13162     RHSReal = true;
13163     APFloat &Real = RHS.FloatReal;
13164     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
13165       return false;
13166     RHS.makeComplexFloat();
13167     RHS.FloatImag = APFloat(Real.getSemantics());
13168   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
13169     return false;
13170 
13171   assert(!(LHSReal && RHSReal) &&
13172          "Cannot have both operands of a complex operation be real.");
13173   switch (E->getOpcode()) {
13174   default: return Error(E);
13175   case BO_Add:
13176     if (Result.isComplexFloat()) {
13177       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
13178                                        APFloat::rmNearestTiesToEven);
13179       if (LHSReal)
13180         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
13181       else if (!RHSReal)
13182         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
13183                                          APFloat::rmNearestTiesToEven);
13184     } else {
13185       Result.getComplexIntReal() += RHS.getComplexIntReal();
13186       Result.getComplexIntImag() += RHS.getComplexIntImag();
13187     }
13188     break;
13189   case BO_Sub:
13190     if (Result.isComplexFloat()) {
13191       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
13192                                             APFloat::rmNearestTiesToEven);
13193       if (LHSReal) {
13194         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
13195         Result.getComplexFloatImag().changeSign();
13196       } else if (!RHSReal) {
13197         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
13198                                               APFloat::rmNearestTiesToEven);
13199       }
13200     } else {
13201       Result.getComplexIntReal() -= RHS.getComplexIntReal();
13202       Result.getComplexIntImag() -= RHS.getComplexIntImag();
13203     }
13204     break;
13205   case BO_Mul:
13206     if (Result.isComplexFloat()) {
13207       // This is an implementation of complex multiplication according to the
13208       // constraints laid out in C11 Annex G. The implementation uses the
13209       // following naming scheme:
13210       //   (a + ib) * (c + id)
13211       ComplexValue LHS = Result;
13212       APFloat &A = LHS.getComplexFloatReal();
13213       APFloat &B = LHS.getComplexFloatImag();
13214       APFloat &C = RHS.getComplexFloatReal();
13215       APFloat &D = RHS.getComplexFloatImag();
13216       APFloat &ResR = Result.getComplexFloatReal();
13217       APFloat &ResI = Result.getComplexFloatImag();
13218       if (LHSReal) {
13219         assert(!RHSReal && "Cannot have two real operands for a complex op!");
13220         ResR = A * C;
13221         ResI = A * D;
13222       } else if (RHSReal) {
13223         ResR = C * A;
13224         ResI = C * B;
13225       } else {
13226         // In the fully general case, we need to handle NaNs and infinities
13227         // robustly.
13228         APFloat AC = A * C;
13229         APFloat BD = B * D;
13230         APFloat AD = A * D;
13231         APFloat BC = B * C;
13232         ResR = AC - BD;
13233         ResI = AD + BC;
13234         if (ResR.isNaN() && ResI.isNaN()) {
13235           bool Recalc = false;
13236           if (A.isInfinity() || B.isInfinity()) {
13237             A = APFloat::copySign(
13238                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
13239             B = APFloat::copySign(
13240                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
13241             if (C.isNaN())
13242               C = APFloat::copySign(APFloat(C.getSemantics()), C);
13243             if (D.isNaN())
13244               D = APFloat::copySign(APFloat(D.getSemantics()), D);
13245             Recalc = true;
13246           }
13247           if (C.isInfinity() || D.isInfinity()) {
13248             C = APFloat::copySign(
13249                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
13250             D = APFloat::copySign(
13251                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
13252             if (A.isNaN())
13253               A = APFloat::copySign(APFloat(A.getSemantics()), A);
13254             if (B.isNaN())
13255               B = APFloat::copySign(APFloat(B.getSemantics()), B);
13256             Recalc = true;
13257           }
13258           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
13259                           AD.isInfinity() || BC.isInfinity())) {
13260             if (A.isNaN())
13261               A = APFloat::copySign(APFloat(A.getSemantics()), A);
13262             if (B.isNaN())
13263               B = APFloat::copySign(APFloat(B.getSemantics()), B);
13264             if (C.isNaN())
13265               C = APFloat::copySign(APFloat(C.getSemantics()), C);
13266             if (D.isNaN())
13267               D = APFloat::copySign(APFloat(D.getSemantics()), D);
13268             Recalc = true;
13269           }
13270           if (Recalc) {
13271             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
13272             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
13273           }
13274         }
13275       }
13276     } else {
13277       ComplexValue LHS = Result;
13278       Result.getComplexIntReal() =
13279         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
13280          LHS.getComplexIntImag() * RHS.getComplexIntImag());
13281       Result.getComplexIntImag() =
13282         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
13283          LHS.getComplexIntImag() * RHS.getComplexIntReal());
13284     }
13285     break;
13286   case BO_Div:
13287     if (Result.isComplexFloat()) {
13288       // This is an implementation of complex division according to the
13289       // constraints laid out in C11 Annex G. The implementation uses the
13290       // following naming scheme:
13291       //   (a + ib) / (c + id)
13292       ComplexValue LHS = Result;
13293       APFloat &A = LHS.getComplexFloatReal();
13294       APFloat &B = LHS.getComplexFloatImag();
13295       APFloat &C = RHS.getComplexFloatReal();
13296       APFloat &D = RHS.getComplexFloatImag();
13297       APFloat &ResR = Result.getComplexFloatReal();
13298       APFloat &ResI = Result.getComplexFloatImag();
13299       if (RHSReal) {
13300         ResR = A / C;
13301         ResI = B / C;
13302       } else {
13303         if (LHSReal) {
13304           // No real optimizations we can do here, stub out with zero.
13305           B = APFloat::getZero(A.getSemantics());
13306         }
13307         int DenomLogB = 0;
13308         APFloat MaxCD = maxnum(abs(C), abs(D));
13309         if (MaxCD.isFinite()) {
13310           DenomLogB = ilogb(MaxCD);
13311           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
13312           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
13313         }
13314         APFloat Denom = C * C + D * D;
13315         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
13316                       APFloat::rmNearestTiesToEven);
13317         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
13318                       APFloat::rmNearestTiesToEven);
13319         if (ResR.isNaN() && ResI.isNaN()) {
13320           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
13321             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
13322             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
13323           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
13324                      D.isFinite()) {
13325             A = APFloat::copySign(
13326                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
13327             B = APFloat::copySign(
13328                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
13329             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
13330             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
13331           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
13332             C = APFloat::copySign(
13333                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
13334             D = APFloat::copySign(
13335                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
13336             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
13337             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
13338           }
13339         }
13340       }
13341     } else {
13342       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
13343         return Error(E, diag::note_expr_divide_by_zero);
13344 
13345       ComplexValue LHS = Result;
13346       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
13347         RHS.getComplexIntImag() * RHS.getComplexIntImag();
13348       Result.getComplexIntReal() =
13349         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
13350          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
13351       Result.getComplexIntImag() =
13352         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
13353          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
13354     }
13355     break;
13356   }
13357 
13358   return true;
13359 }
13360 
13361 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13362   // Get the operand value into 'Result'.
13363   if (!Visit(E->getSubExpr()))
13364     return false;
13365 
13366   switch (E->getOpcode()) {
13367   default:
13368     return Error(E);
13369   case UO_Extension:
13370     return true;
13371   case UO_Plus:
13372     // The result is always just the subexpr.
13373     return true;
13374   case UO_Minus:
13375     if (Result.isComplexFloat()) {
13376       Result.getComplexFloatReal().changeSign();
13377       Result.getComplexFloatImag().changeSign();
13378     }
13379     else {
13380       Result.getComplexIntReal() = -Result.getComplexIntReal();
13381       Result.getComplexIntImag() = -Result.getComplexIntImag();
13382     }
13383     return true;
13384   case UO_Not:
13385     if (Result.isComplexFloat())
13386       Result.getComplexFloatImag().changeSign();
13387     else
13388       Result.getComplexIntImag() = -Result.getComplexIntImag();
13389     return true;
13390   }
13391 }
13392 
13393 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
13394   if (E->getNumInits() == 2) {
13395     if (E->getType()->isComplexType()) {
13396       Result.makeComplexFloat();
13397       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
13398         return false;
13399       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
13400         return false;
13401     } else {
13402       Result.makeComplexInt();
13403       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
13404         return false;
13405       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
13406         return false;
13407     }
13408     return true;
13409   }
13410   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
13411 }
13412 
13413 //===----------------------------------------------------------------------===//
13414 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
13415 // implicit conversion.
13416 //===----------------------------------------------------------------------===//
13417 
13418 namespace {
13419 class AtomicExprEvaluator :
13420     public ExprEvaluatorBase<AtomicExprEvaluator> {
13421   const LValue *This;
13422   APValue &Result;
13423 public:
13424   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
13425       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
13426 
13427   bool Success(const APValue &V, const Expr *E) {
13428     Result = V;
13429     return true;
13430   }
13431 
13432   bool ZeroInitialization(const Expr *E) {
13433     ImplicitValueInitExpr VIE(
13434         E->getType()->castAs<AtomicType>()->getValueType());
13435     // For atomic-qualified class (and array) types in C++, initialize the
13436     // _Atomic-wrapped subobject directly, in-place.
13437     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
13438                 : Evaluate(Result, Info, &VIE);
13439   }
13440 
13441   bool VisitCastExpr(const CastExpr *E) {
13442     switch (E->getCastKind()) {
13443     default:
13444       return ExprEvaluatorBaseTy::VisitCastExpr(E);
13445     case CK_NonAtomicToAtomic:
13446       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
13447                   : Evaluate(Result, Info, E->getSubExpr());
13448     }
13449   }
13450 };
13451 } // end anonymous namespace
13452 
13453 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
13454                            EvalInfo &Info) {
13455   assert(E->isRValue() && E->getType()->isAtomicType());
13456   return AtomicExprEvaluator(Info, This, Result).Visit(E);
13457 }
13458 
13459 //===----------------------------------------------------------------------===//
13460 // Void expression evaluation, primarily for a cast to void on the LHS of a
13461 // comma operator
13462 //===----------------------------------------------------------------------===//
13463 
13464 namespace {
13465 class VoidExprEvaluator
13466   : public ExprEvaluatorBase<VoidExprEvaluator> {
13467 public:
13468   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
13469 
13470   bool Success(const APValue &V, const Expr *e) { return true; }
13471 
13472   bool ZeroInitialization(const Expr *E) { return true; }
13473 
13474   bool VisitCastExpr(const CastExpr *E) {
13475     switch (E->getCastKind()) {
13476     default:
13477       return ExprEvaluatorBaseTy::VisitCastExpr(E);
13478     case CK_ToVoid:
13479       VisitIgnoredValue(E->getSubExpr());
13480       return true;
13481     }
13482   }
13483 
13484   bool VisitCallExpr(const CallExpr *E) {
13485     switch (E->getBuiltinCallee()) {
13486     case Builtin::BI__assume:
13487     case Builtin::BI__builtin_assume:
13488       // The argument is not evaluated!
13489       return true;
13490 
13491     case Builtin::BI__builtin_operator_delete:
13492       return HandleOperatorDeleteCall(Info, E);
13493 
13494     default:
13495       break;
13496     }
13497 
13498     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13499   }
13500 
13501   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
13502 };
13503 } // end anonymous namespace
13504 
13505 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
13506   // We cannot speculatively evaluate a delete expression.
13507   if (Info.SpeculativeEvaluationDepth)
13508     return false;
13509 
13510   FunctionDecl *OperatorDelete = E->getOperatorDelete();
13511   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
13512     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
13513         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
13514     return false;
13515   }
13516 
13517   const Expr *Arg = E->getArgument();
13518 
13519   LValue Pointer;
13520   if (!EvaluatePointer(Arg, Pointer, Info))
13521     return false;
13522   if (Pointer.Designator.Invalid)
13523     return false;
13524 
13525   // Deleting a null pointer has no effect.
13526   if (Pointer.isNullPointer()) {
13527     // This is the only case where we need to produce an extension warning:
13528     // the only other way we can succeed is if we find a dynamic allocation,
13529     // and we will have warned when we allocated it in that case.
13530     if (!Info.getLangOpts().CPlusPlus2a)
13531       Info.CCEDiag(E, diag::note_constexpr_new);
13532     return true;
13533   }
13534 
13535   Optional<DynAlloc *> Alloc = CheckDeleteKind(
13536       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
13537   if (!Alloc)
13538     return false;
13539   QualType AllocType = Pointer.Base.getDynamicAllocType();
13540 
13541   // For the non-array case, the designator must be empty if the static type
13542   // does not have a virtual destructor.
13543   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
13544       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
13545     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
13546         << Arg->getType()->getPointeeType() << AllocType;
13547     return false;
13548   }
13549 
13550   // For a class type with a virtual destructor, the selected operator delete
13551   // is the one looked up when building the destructor.
13552   if (!E->isArrayForm() && !E->isGlobalDelete()) {
13553     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
13554     if (VirtualDelete &&
13555         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
13556       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
13557           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
13558       return false;
13559     }
13560   }
13561 
13562   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
13563                          (*Alloc)->Value, AllocType))
13564     return false;
13565 
13566   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
13567     // The element was already erased. This means the destructor call also
13568     // deleted the object.
13569     // FIXME: This probably results in undefined behavior before we get this
13570     // far, and should be diagnosed elsewhere first.
13571     Info.FFDiag(E, diag::note_constexpr_double_delete);
13572     return false;
13573   }
13574 
13575   return true;
13576 }
13577 
13578 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
13579   assert(E->isRValue() && E->getType()->isVoidType());
13580   return VoidExprEvaluator(Info).Visit(E);
13581 }
13582 
13583 //===----------------------------------------------------------------------===//
13584 // Top level Expr::EvaluateAsRValue method.
13585 //===----------------------------------------------------------------------===//
13586 
13587 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
13588   // In C, function designators are not lvalues, but we evaluate them as if they
13589   // are.
13590   QualType T = E->getType();
13591   if (E->isGLValue() || T->isFunctionType()) {
13592     LValue LV;
13593     if (!EvaluateLValue(E, LV, Info))
13594       return false;
13595     LV.moveInto(Result);
13596   } else if (T->isVectorType()) {
13597     if (!EvaluateVector(E, Result, Info))
13598       return false;
13599   } else if (T->isIntegralOrEnumerationType()) {
13600     if (!IntExprEvaluator(Info, Result).Visit(E))
13601       return false;
13602   } else if (T->hasPointerRepresentation()) {
13603     LValue LV;
13604     if (!EvaluatePointer(E, LV, Info))
13605       return false;
13606     LV.moveInto(Result);
13607   } else if (T->isRealFloatingType()) {
13608     llvm::APFloat F(0.0);
13609     if (!EvaluateFloat(E, F, Info))
13610       return false;
13611     Result = APValue(F);
13612   } else if (T->isAnyComplexType()) {
13613     ComplexValue C;
13614     if (!EvaluateComplex(E, C, Info))
13615       return false;
13616     C.moveInto(Result);
13617   } else if (T->isFixedPointType()) {
13618     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
13619   } else if (T->isMemberPointerType()) {
13620     MemberPtr P;
13621     if (!EvaluateMemberPointer(E, P, Info))
13622       return false;
13623     P.moveInto(Result);
13624     return true;
13625   } else if (T->isArrayType()) {
13626     LValue LV;
13627     APValue &Value =
13628         Info.CurrentCall->createTemporary(E, T, false, LV);
13629     if (!EvaluateArray(E, LV, Value, Info))
13630       return false;
13631     Result = Value;
13632   } else if (T->isRecordType()) {
13633     LValue LV;
13634     APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV);
13635     if (!EvaluateRecord(E, LV, Value, Info))
13636       return false;
13637     Result = Value;
13638   } else if (T->isVoidType()) {
13639     if (!Info.getLangOpts().CPlusPlus11)
13640       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
13641         << E->getType();
13642     if (!EvaluateVoid(E, Info))
13643       return false;
13644   } else if (T->isAtomicType()) {
13645     QualType Unqual = T.getAtomicUnqualifiedType();
13646     if (Unqual->isArrayType() || Unqual->isRecordType()) {
13647       LValue LV;
13648       APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV);
13649       if (!EvaluateAtomic(E, &LV, Value, Info))
13650         return false;
13651     } else {
13652       if (!EvaluateAtomic(E, nullptr, Result, Info))
13653         return false;
13654     }
13655   } else if (Info.getLangOpts().CPlusPlus11) {
13656     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
13657     return false;
13658   } else {
13659     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
13660     return false;
13661   }
13662 
13663   return true;
13664 }
13665 
13666 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
13667 /// cases, the in-place evaluation is essential, since later initializers for
13668 /// an object can indirectly refer to subobjects which were initialized earlier.
13669 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
13670                             const Expr *E, bool AllowNonLiteralTypes) {
13671   assert(!E->isValueDependent());
13672 
13673   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
13674     return false;
13675 
13676   if (E->isRValue()) {
13677     // Evaluate arrays and record types in-place, so that later initializers can
13678     // refer to earlier-initialized members of the object.
13679     QualType T = E->getType();
13680     if (T->isArrayType())
13681       return EvaluateArray(E, This, Result, Info);
13682     else if (T->isRecordType())
13683       return EvaluateRecord(E, This, Result, Info);
13684     else if (T->isAtomicType()) {
13685       QualType Unqual = T.getAtomicUnqualifiedType();
13686       if (Unqual->isArrayType() || Unqual->isRecordType())
13687         return EvaluateAtomic(E, &This, Result, Info);
13688     }
13689   }
13690 
13691   // For any other type, in-place evaluation is unimportant.
13692   return Evaluate(Result, Info, E);
13693 }
13694 
13695 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
13696 /// lvalue-to-rvalue cast if it is an lvalue.
13697 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
13698   if (Info.EnableNewConstInterp) {
13699     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
13700       return false;
13701   } else {
13702     if (E->getType().isNull())
13703       return false;
13704 
13705     if (!CheckLiteralType(Info, E))
13706       return false;
13707 
13708     if (!::Evaluate(Result, Info, E))
13709       return false;
13710 
13711     if (E->isGLValue()) {
13712       LValue LV;
13713       LV.setFrom(Info.Ctx, Result);
13714       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
13715         return false;
13716     }
13717   }
13718 
13719   // Check this core constant expression is a constant expression.
13720   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) &&
13721          CheckMemoryLeaks(Info);
13722 }
13723 
13724 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
13725                                  const ASTContext &Ctx, bool &IsConst) {
13726   // Fast-path evaluations of integer literals, since we sometimes see files
13727   // containing vast quantities of these.
13728   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
13729     Result.Val = APValue(APSInt(L->getValue(),
13730                                 L->getType()->isUnsignedIntegerType()));
13731     IsConst = true;
13732     return true;
13733   }
13734 
13735   // This case should be rare, but we need to check it before we check on
13736   // the type below.
13737   if (Exp->getType().isNull()) {
13738     IsConst = false;
13739     return true;
13740   }
13741 
13742   // FIXME: Evaluating values of large array and record types can cause
13743   // performance problems. Only do so in C++11 for now.
13744   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
13745                           Exp->getType()->isRecordType()) &&
13746       !Ctx.getLangOpts().CPlusPlus11) {
13747     IsConst = false;
13748     return true;
13749   }
13750   return false;
13751 }
13752 
13753 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
13754                                       Expr::SideEffectsKind SEK) {
13755   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
13756          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
13757 }
13758 
13759 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
13760                              const ASTContext &Ctx, EvalInfo &Info) {
13761   bool IsConst;
13762   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
13763     return IsConst;
13764 
13765   return EvaluateAsRValue(Info, E, Result.Val);
13766 }
13767 
13768 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
13769                           const ASTContext &Ctx,
13770                           Expr::SideEffectsKind AllowSideEffects,
13771                           EvalInfo &Info) {
13772   if (!E->getType()->isIntegralOrEnumerationType())
13773     return false;
13774 
13775   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
13776       !ExprResult.Val.isInt() ||
13777       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13778     return false;
13779 
13780   return true;
13781 }
13782 
13783 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
13784                                  const ASTContext &Ctx,
13785                                  Expr::SideEffectsKind AllowSideEffects,
13786                                  EvalInfo &Info) {
13787   if (!E->getType()->isFixedPointType())
13788     return false;
13789 
13790   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
13791     return false;
13792 
13793   if (!ExprResult.Val.isFixedPoint() ||
13794       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13795     return false;
13796 
13797   return true;
13798 }
13799 
13800 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
13801 /// any crazy technique (that has nothing to do with language standards) that
13802 /// we want to.  If this function returns true, it returns the folded constant
13803 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
13804 /// will be applied to the result.
13805 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
13806                             bool InConstantContext) const {
13807   assert(!isValueDependent() &&
13808          "Expression evaluator can't be called on a dependent expression.");
13809   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
13810   Info.InConstantContext = InConstantContext;
13811   return ::EvaluateAsRValue(this, Result, Ctx, Info);
13812 }
13813 
13814 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
13815                                       bool InConstantContext) const {
13816   assert(!isValueDependent() &&
13817          "Expression evaluator can't be called on a dependent expression.");
13818   EvalResult Scratch;
13819   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
13820          HandleConversionToBool(Scratch.Val, Result);
13821 }
13822 
13823 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
13824                          SideEffectsKind AllowSideEffects,
13825                          bool InConstantContext) const {
13826   assert(!isValueDependent() &&
13827          "Expression evaluator can't be called on a dependent expression.");
13828   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
13829   Info.InConstantContext = InConstantContext;
13830   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
13831 }
13832 
13833 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
13834                                 SideEffectsKind AllowSideEffects,
13835                                 bool InConstantContext) const {
13836   assert(!isValueDependent() &&
13837          "Expression evaluator can't be called on a dependent expression.");
13838   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
13839   Info.InConstantContext = InConstantContext;
13840   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
13841 }
13842 
13843 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
13844                            SideEffectsKind AllowSideEffects,
13845                            bool InConstantContext) const {
13846   assert(!isValueDependent() &&
13847          "Expression evaluator can't be called on a dependent expression.");
13848 
13849   if (!getType()->isRealFloatingType())
13850     return false;
13851 
13852   EvalResult ExprResult;
13853   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
13854       !ExprResult.Val.isFloat() ||
13855       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13856     return false;
13857 
13858   Result = ExprResult.Val.getFloat();
13859   return true;
13860 }
13861 
13862 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
13863                             bool InConstantContext) const {
13864   assert(!isValueDependent() &&
13865          "Expression evaluator can't be called on a dependent expression.");
13866 
13867   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
13868   Info.InConstantContext = InConstantContext;
13869   LValue LV;
13870   CheckedTemporaries CheckedTemps;
13871   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
13872       Result.HasSideEffects ||
13873       !CheckLValueConstantExpression(Info, getExprLoc(),
13874                                      Ctx.getLValueReferenceType(getType()), LV,
13875                                      Expr::EvaluateForCodeGen, CheckedTemps))
13876     return false;
13877 
13878   LV.moveInto(Result.Val);
13879   return true;
13880 }
13881 
13882 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
13883                                   const ASTContext &Ctx, bool InPlace) const {
13884   assert(!isValueDependent() &&
13885          "Expression evaluator can't be called on a dependent expression.");
13886 
13887   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
13888   EvalInfo Info(Ctx, Result, EM);
13889   Info.InConstantContext = true;
13890 
13891   if (InPlace) {
13892     Info.setEvaluatingDecl(this, Result.Val);
13893     LValue LVal;
13894     LVal.set(this);
13895     if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
13896         Result.HasSideEffects)
13897       return false;
13898   } else if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects)
13899     return false;
13900 
13901   if (!Info.discardCleanups())
13902     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
13903 
13904   return CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
13905                                  Result.Val, Usage) &&
13906          CheckMemoryLeaks(Info);
13907 }
13908 
13909 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
13910                                  const VarDecl *VD,
13911                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
13912   assert(!isValueDependent() &&
13913          "Expression evaluator can't be called on a dependent expression.");
13914 
13915   // FIXME: Evaluating initializers for large array and record types can cause
13916   // performance problems. Only do so in C++11 for now.
13917   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
13918       !Ctx.getLangOpts().CPlusPlus11)
13919     return false;
13920 
13921   Expr::EvalStatus EStatus;
13922   EStatus.Diag = &Notes;
13923 
13924   EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
13925                                       ? EvalInfo::EM_ConstantExpression
13926                                       : EvalInfo::EM_ConstantFold);
13927   Info.setEvaluatingDecl(VD, Value);
13928   Info.InConstantContext = true;
13929 
13930   SourceLocation DeclLoc = VD->getLocation();
13931   QualType DeclTy = VD->getType();
13932 
13933   if (Info.EnableNewConstInterp) {
13934     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
13935     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
13936       return false;
13937   } else {
13938     LValue LVal;
13939     LVal.set(VD);
13940 
13941     if (!EvaluateInPlace(Value, Info, LVal, this,
13942                          /*AllowNonLiteralTypes=*/true) ||
13943         EStatus.HasSideEffects)
13944       return false;
13945 
13946     // At this point, any lifetime-extended temporaries are completely
13947     // initialized.
13948     Info.performLifetimeExtension();
13949 
13950     if (!Info.discardCleanups())
13951       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
13952   }
13953   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) &&
13954          CheckMemoryLeaks(Info);
13955 }
13956 
13957 bool VarDecl::evaluateDestruction(
13958     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
13959   Expr::EvalStatus EStatus;
13960   EStatus.Diag = &Notes;
13961 
13962   // Make a copy of the value for the destructor to mutate, if we know it.
13963   // Otherwise, treat the value as default-initialized; if the destructor works
13964   // anyway, then the destruction is constant (and must be essentially empty).
13965   APValue DestroyedValue =
13966       (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
13967           ? *getEvaluatedValue()
13968           : getDefaultInitValue(getType());
13969 
13970   EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression);
13971   Info.setEvaluatingDecl(this, DestroyedValue,
13972                          EvalInfo::EvaluatingDeclKind::Dtor);
13973   Info.InConstantContext = true;
13974 
13975   SourceLocation DeclLoc = getLocation();
13976   QualType DeclTy = getType();
13977 
13978   LValue LVal;
13979   LVal.set(this);
13980 
13981   if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) ||
13982       EStatus.HasSideEffects)
13983     return false;
13984 
13985   if (!Info.discardCleanups())
13986     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
13987 
13988   ensureEvaluatedStmt()->HasConstantDestruction = true;
13989   return true;
13990 }
13991 
13992 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
13993 /// constant folded, but discard the result.
13994 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
13995   assert(!isValueDependent() &&
13996          "Expression evaluator can't be called on a dependent expression.");
13997 
13998   EvalResult Result;
13999   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
14000          !hasUnacceptableSideEffect(Result, SEK);
14001 }
14002 
14003 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
14004                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14005   assert(!isValueDependent() &&
14006          "Expression evaluator can't be called on a dependent expression.");
14007 
14008   EvalResult EVResult;
14009   EVResult.Diag = Diag;
14010   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14011   Info.InConstantContext = true;
14012 
14013   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
14014   (void)Result;
14015   assert(Result && "Could not evaluate expression");
14016   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14017 
14018   return EVResult.Val.getInt();
14019 }
14020 
14021 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
14022     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14023   assert(!isValueDependent() &&
14024          "Expression evaluator can't be called on a dependent expression.");
14025 
14026   EvalResult EVResult;
14027   EVResult.Diag = Diag;
14028   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14029   Info.InConstantContext = true;
14030   Info.CheckingForUndefinedBehavior = true;
14031 
14032   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
14033   (void)Result;
14034   assert(Result && "Could not evaluate expression");
14035   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14036 
14037   return EVResult.Val.getInt();
14038 }
14039 
14040 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
14041   assert(!isValueDependent() &&
14042          "Expression evaluator can't be called on a dependent expression.");
14043 
14044   bool IsConst;
14045   EvalResult EVResult;
14046   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
14047     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14048     Info.CheckingForUndefinedBehavior = true;
14049     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
14050   }
14051 }
14052 
14053 bool Expr::EvalResult::isGlobalLValue() const {
14054   assert(Val.isLValue());
14055   return IsGlobalLValue(Val.getLValueBase());
14056 }
14057 
14058 
14059 /// isIntegerConstantExpr - this recursive routine will test if an expression is
14060 /// an integer constant expression.
14061 
14062 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
14063 /// comma, etc
14064 
14065 // CheckICE - This function does the fundamental ICE checking: the returned
14066 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
14067 // and a (possibly null) SourceLocation indicating the location of the problem.
14068 //
14069 // Note that to reduce code duplication, this helper does no evaluation
14070 // itself; the caller checks whether the expression is evaluatable, and
14071 // in the rare cases where CheckICE actually cares about the evaluated
14072 // value, it calls into Evaluate.
14073 
14074 namespace {
14075 
14076 enum ICEKind {
14077   /// This expression is an ICE.
14078   IK_ICE,
14079   /// This expression is not an ICE, but if it isn't evaluated, it's
14080   /// a legal subexpression for an ICE. This return value is used to handle
14081   /// the comma operator in C99 mode, and non-constant subexpressions.
14082   IK_ICEIfUnevaluated,
14083   /// This expression is not an ICE, and is not a legal subexpression for one.
14084   IK_NotICE
14085 };
14086 
14087 struct ICEDiag {
14088   ICEKind Kind;
14089   SourceLocation Loc;
14090 
14091   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
14092 };
14093 
14094 }
14095 
14096 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
14097 
14098 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
14099 
14100 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
14101   Expr::EvalResult EVResult;
14102   Expr::EvalStatus Status;
14103   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
14104 
14105   Info.InConstantContext = true;
14106   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
14107       !EVResult.Val.isInt())
14108     return ICEDiag(IK_NotICE, E->getBeginLoc());
14109 
14110   return NoDiag();
14111 }
14112 
14113 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
14114   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
14115   if (!E->getType()->isIntegralOrEnumerationType())
14116     return ICEDiag(IK_NotICE, E->getBeginLoc());
14117 
14118   switch (E->getStmtClass()) {
14119 #define ABSTRACT_STMT(Node)
14120 #define STMT(Node, Base) case Expr::Node##Class:
14121 #define EXPR(Node, Base)
14122 #include "clang/AST/StmtNodes.inc"
14123   case Expr::PredefinedExprClass:
14124   case Expr::FloatingLiteralClass:
14125   case Expr::ImaginaryLiteralClass:
14126   case Expr::StringLiteralClass:
14127   case Expr::ArraySubscriptExprClass:
14128   case Expr::OMPArraySectionExprClass:
14129   case Expr::MemberExprClass:
14130   case Expr::CompoundAssignOperatorClass:
14131   case Expr::CompoundLiteralExprClass:
14132   case Expr::ExtVectorElementExprClass:
14133   case Expr::DesignatedInitExprClass:
14134   case Expr::ArrayInitLoopExprClass:
14135   case Expr::ArrayInitIndexExprClass:
14136   case Expr::NoInitExprClass:
14137   case Expr::DesignatedInitUpdateExprClass:
14138   case Expr::ImplicitValueInitExprClass:
14139   case Expr::ParenListExprClass:
14140   case Expr::VAArgExprClass:
14141   case Expr::AddrLabelExprClass:
14142   case Expr::StmtExprClass:
14143   case Expr::CXXMemberCallExprClass:
14144   case Expr::CUDAKernelCallExprClass:
14145   case Expr::CXXDynamicCastExprClass:
14146   case Expr::CXXTypeidExprClass:
14147   case Expr::CXXUuidofExprClass:
14148   case Expr::MSPropertyRefExprClass:
14149   case Expr::MSPropertySubscriptExprClass:
14150   case Expr::CXXNullPtrLiteralExprClass:
14151   case Expr::UserDefinedLiteralClass:
14152   case Expr::CXXThisExprClass:
14153   case Expr::CXXThrowExprClass:
14154   case Expr::CXXNewExprClass:
14155   case Expr::CXXDeleteExprClass:
14156   case Expr::CXXPseudoDestructorExprClass:
14157   case Expr::UnresolvedLookupExprClass:
14158   case Expr::TypoExprClass:
14159   case Expr::DependentScopeDeclRefExprClass:
14160   case Expr::CXXConstructExprClass:
14161   case Expr::CXXInheritedCtorInitExprClass:
14162   case Expr::CXXStdInitializerListExprClass:
14163   case Expr::CXXBindTemporaryExprClass:
14164   case Expr::ExprWithCleanupsClass:
14165   case Expr::CXXTemporaryObjectExprClass:
14166   case Expr::CXXUnresolvedConstructExprClass:
14167   case Expr::CXXDependentScopeMemberExprClass:
14168   case Expr::UnresolvedMemberExprClass:
14169   case Expr::ObjCStringLiteralClass:
14170   case Expr::ObjCBoxedExprClass:
14171   case Expr::ObjCArrayLiteralClass:
14172   case Expr::ObjCDictionaryLiteralClass:
14173   case Expr::ObjCEncodeExprClass:
14174   case Expr::ObjCMessageExprClass:
14175   case Expr::ObjCSelectorExprClass:
14176   case Expr::ObjCProtocolExprClass:
14177   case Expr::ObjCIvarRefExprClass:
14178   case Expr::ObjCPropertyRefExprClass:
14179   case Expr::ObjCSubscriptRefExprClass:
14180   case Expr::ObjCIsaExprClass:
14181   case Expr::ObjCAvailabilityCheckExprClass:
14182   case Expr::ShuffleVectorExprClass:
14183   case Expr::ConvertVectorExprClass:
14184   case Expr::BlockExprClass:
14185   case Expr::NoStmtClass:
14186   case Expr::OpaqueValueExprClass:
14187   case Expr::PackExpansionExprClass:
14188   case Expr::SubstNonTypeTemplateParmPackExprClass:
14189   case Expr::FunctionParmPackExprClass:
14190   case Expr::AsTypeExprClass:
14191   case Expr::ObjCIndirectCopyRestoreExprClass:
14192   case Expr::MaterializeTemporaryExprClass:
14193   case Expr::PseudoObjectExprClass:
14194   case Expr::AtomicExprClass:
14195   case Expr::LambdaExprClass:
14196   case Expr::CXXFoldExprClass:
14197   case Expr::CoawaitExprClass:
14198   case Expr::DependentCoawaitExprClass:
14199   case Expr::CoyieldExprClass:
14200     return ICEDiag(IK_NotICE, E->getBeginLoc());
14201 
14202   case Expr::InitListExprClass: {
14203     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
14204     // form "T x = { a };" is equivalent to "T x = a;".
14205     // Unless we're initializing a reference, T is a scalar as it is known to be
14206     // of integral or enumeration type.
14207     if (E->isRValue())
14208       if (cast<InitListExpr>(E)->getNumInits() == 1)
14209         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
14210     return ICEDiag(IK_NotICE, E->getBeginLoc());
14211   }
14212 
14213   case Expr::SizeOfPackExprClass:
14214   case Expr::GNUNullExprClass:
14215   case Expr::SourceLocExprClass:
14216     return NoDiag();
14217 
14218   case Expr::SubstNonTypeTemplateParmExprClass:
14219     return
14220       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
14221 
14222   case Expr::ConstantExprClass:
14223     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
14224 
14225   case Expr::ParenExprClass:
14226     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
14227   case Expr::GenericSelectionExprClass:
14228     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
14229   case Expr::IntegerLiteralClass:
14230   case Expr::FixedPointLiteralClass:
14231   case Expr::CharacterLiteralClass:
14232   case Expr::ObjCBoolLiteralExprClass:
14233   case Expr::CXXBoolLiteralExprClass:
14234   case Expr::CXXScalarValueInitExprClass:
14235   case Expr::TypeTraitExprClass:
14236   case Expr::ConceptSpecializationExprClass:
14237   case Expr::RequiresExprClass:
14238   case Expr::ArrayTypeTraitExprClass:
14239   case Expr::ExpressionTraitExprClass:
14240   case Expr::CXXNoexceptExprClass:
14241     return NoDiag();
14242   case Expr::CallExprClass:
14243   case Expr::CXXOperatorCallExprClass: {
14244     // C99 6.6/3 allows function calls within unevaluated subexpressions of
14245     // constant expressions, but they can never be ICEs because an ICE cannot
14246     // contain an operand of (pointer to) function type.
14247     const CallExpr *CE = cast<CallExpr>(E);
14248     if (CE->getBuiltinCallee())
14249       return CheckEvalInICE(E, Ctx);
14250     return ICEDiag(IK_NotICE, E->getBeginLoc());
14251   }
14252   case Expr::CXXRewrittenBinaryOperatorClass:
14253     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
14254                     Ctx);
14255   case Expr::DeclRefExprClass: {
14256     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
14257       return NoDiag();
14258     const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
14259     if (Ctx.getLangOpts().CPlusPlus &&
14260         D && IsConstNonVolatile(D->getType())) {
14261       // Parameter variables are never constants.  Without this check,
14262       // getAnyInitializer() can find a default argument, which leads
14263       // to chaos.
14264       if (isa<ParmVarDecl>(D))
14265         return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14266 
14267       // C++ 7.1.5.1p2
14268       //   A variable of non-volatile const-qualified integral or enumeration
14269       //   type initialized by an ICE can be used in ICEs.
14270       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
14271         if (!Dcl->getType()->isIntegralOrEnumerationType())
14272           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14273 
14274         const VarDecl *VD;
14275         // Look for a declaration of this variable that has an initializer, and
14276         // check whether it is an ICE.
14277         if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
14278           return NoDiag();
14279         else
14280           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14281       }
14282     }
14283     return ICEDiag(IK_NotICE, E->getBeginLoc());
14284   }
14285   case Expr::UnaryOperatorClass: {
14286     const UnaryOperator *Exp = cast<UnaryOperator>(E);
14287     switch (Exp->getOpcode()) {
14288     case UO_PostInc:
14289     case UO_PostDec:
14290     case UO_PreInc:
14291     case UO_PreDec:
14292     case UO_AddrOf:
14293     case UO_Deref:
14294     case UO_Coawait:
14295       // C99 6.6/3 allows increment and decrement within unevaluated
14296       // subexpressions of constant expressions, but they can never be ICEs
14297       // because an ICE cannot contain an lvalue operand.
14298       return ICEDiag(IK_NotICE, E->getBeginLoc());
14299     case UO_Extension:
14300     case UO_LNot:
14301     case UO_Plus:
14302     case UO_Minus:
14303     case UO_Not:
14304     case UO_Real:
14305     case UO_Imag:
14306       return CheckICE(Exp->getSubExpr(), Ctx);
14307     }
14308     llvm_unreachable("invalid unary operator class");
14309   }
14310   case Expr::OffsetOfExprClass: {
14311     // Note that per C99, offsetof must be an ICE. And AFAIK, using
14312     // EvaluateAsRValue matches the proposed gcc behavior for cases like
14313     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
14314     // compliance: we should warn earlier for offsetof expressions with
14315     // array subscripts that aren't ICEs, and if the array subscripts
14316     // are ICEs, the value of the offsetof must be an integer constant.
14317     return CheckEvalInICE(E, Ctx);
14318   }
14319   case Expr::UnaryExprOrTypeTraitExprClass: {
14320     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
14321     if ((Exp->getKind() ==  UETT_SizeOf) &&
14322         Exp->getTypeOfArgument()->isVariableArrayType())
14323       return ICEDiag(IK_NotICE, E->getBeginLoc());
14324     return NoDiag();
14325   }
14326   case Expr::BinaryOperatorClass: {
14327     const BinaryOperator *Exp = cast<BinaryOperator>(E);
14328     switch (Exp->getOpcode()) {
14329     case BO_PtrMemD:
14330     case BO_PtrMemI:
14331     case BO_Assign:
14332     case BO_MulAssign:
14333     case BO_DivAssign:
14334     case BO_RemAssign:
14335     case BO_AddAssign:
14336     case BO_SubAssign:
14337     case BO_ShlAssign:
14338     case BO_ShrAssign:
14339     case BO_AndAssign:
14340     case BO_XorAssign:
14341     case BO_OrAssign:
14342       // C99 6.6/3 allows assignments within unevaluated subexpressions of
14343       // constant expressions, but they can never be ICEs because an ICE cannot
14344       // contain an lvalue operand.
14345       return ICEDiag(IK_NotICE, E->getBeginLoc());
14346 
14347     case BO_Mul:
14348     case BO_Div:
14349     case BO_Rem:
14350     case BO_Add:
14351     case BO_Sub:
14352     case BO_Shl:
14353     case BO_Shr:
14354     case BO_LT:
14355     case BO_GT:
14356     case BO_LE:
14357     case BO_GE:
14358     case BO_EQ:
14359     case BO_NE:
14360     case BO_And:
14361     case BO_Xor:
14362     case BO_Or:
14363     case BO_Comma:
14364     case BO_Cmp: {
14365       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
14366       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
14367       if (Exp->getOpcode() == BO_Div ||
14368           Exp->getOpcode() == BO_Rem) {
14369         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
14370         // we don't evaluate one.
14371         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
14372           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
14373           if (REval == 0)
14374             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14375           if (REval.isSigned() && REval.isAllOnesValue()) {
14376             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
14377             if (LEval.isMinSignedValue())
14378               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14379           }
14380         }
14381       }
14382       if (Exp->getOpcode() == BO_Comma) {
14383         if (Ctx.getLangOpts().C99) {
14384           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
14385           // if it isn't evaluated.
14386           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
14387             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14388         } else {
14389           // In both C89 and C++, commas in ICEs are illegal.
14390           return ICEDiag(IK_NotICE, E->getBeginLoc());
14391         }
14392       }
14393       return Worst(LHSResult, RHSResult);
14394     }
14395     case BO_LAnd:
14396     case BO_LOr: {
14397       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
14398       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
14399       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
14400         // Rare case where the RHS has a comma "side-effect"; we need
14401         // to actually check the condition to see whether the side
14402         // with the comma is evaluated.
14403         if ((Exp->getOpcode() == BO_LAnd) !=
14404             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
14405           return RHSResult;
14406         return NoDiag();
14407       }
14408 
14409       return Worst(LHSResult, RHSResult);
14410     }
14411     }
14412     llvm_unreachable("invalid binary operator kind");
14413   }
14414   case Expr::ImplicitCastExprClass:
14415   case Expr::CStyleCastExprClass:
14416   case Expr::CXXFunctionalCastExprClass:
14417   case Expr::CXXStaticCastExprClass:
14418   case Expr::CXXReinterpretCastExprClass:
14419   case Expr::CXXConstCastExprClass:
14420   case Expr::ObjCBridgedCastExprClass: {
14421     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
14422     if (isa<ExplicitCastExpr>(E)) {
14423       if (const FloatingLiteral *FL
14424             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
14425         unsigned DestWidth = Ctx.getIntWidth(E->getType());
14426         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
14427         APSInt IgnoredVal(DestWidth, !DestSigned);
14428         bool Ignored;
14429         // If the value does not fit in the destination type, the behavior is
14430         // undefined, so we are not required to treat it as a constant
14431         // expression.
14432         if (FL->getValue().convertToInteger(IgnoredVal,
14433                                             llvm::APFloat::rmTowardZero,
14434                                             &Ignored) & APFloat::opInvalidOp)
14435           return ICEDiag(IK_NotICE, E->getBeginLoc());
14436         return NoDiag();
14437       }
14438     }
14439     switch (cast<CastExpr>(E)->getCastKind()) {
14440     case CK_LValueToRValue:
14441     case CK_AtomicToNonAtomic:
14442     case CK_NonAtomicToAtomic:
14443     case CK_NoOp:
14444     case CK_IntegralToBoolean:
14445     case CK_IntegralCast:
14446       return CheckICE(SubExpr, Ctx);
14447     default:
14448       return ICEDiag(IK_NotICE, E->getBeginLoc());
14449     }
14450   }
14451   case Expr::BinaryConditionalOperatorClass: {
14452     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
14453     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
14454     if (CommonResult.Kind == IK_NotICE) return CommonResult;
14455     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
14456     if (FalseResult.Kind == IK_NotICE) return FalseResult;
14457     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
14458     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
14459         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
14460     return FalseResult;
14461   }
14462   case Expr::ConditionalOperatorClass: {
14463     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
14464     // If the condition (ignoring parens) is a __builtin_constant_p call,
14465     // then only the true side is actually considered in an integer constant
14466     // expression, and it is fully evaluated.  This is an important GNU
14467     // extension.  See GCC PR38377 for discussion.
14468     if (const CallExpr *CallCE
14469         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
14470       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
14471         return CheckEvalInICE(E, Ctx);
14472     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
14473     if (CondResult.Kind == IK_NotICE)
14474       return CondResult;
14475 
14476     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
14477     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
14478 
14479     if (TrueResult.Kind == IK_NotICE)
14480       return TrueResult;
14481     if (FalseResult.Kind == IK_NotICE)
14482       return FalseResult;
14483     if (CondResult.Kind == IK_ICEIfUnevaluated)
14484       return CondResult;
14485     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
14486       return NoDiag();
14487     // Rare case where the diagnostics depend on which side is evaluated
14488     // Note that if we get here, CondResult is 0, and at least one of
14489     // TrueResult and FalseResult is non-zero.
14490     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
14491       return FalseResult;
14492     return TrueResult;
14493   }
14494   case Expr::CXXDefaultArgExprClass:
14495     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
14496   case Expr::CXXDefaultInitExprClass:
14497     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
14498   case Expr::ChooseExprClass: {
14499     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
14500   }
14501   case Expr::BuiltinBitCastExprClass: {
14502     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
14503       return ICEDiag(IK_NotICE, E->getBeginLoc());
14504     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
14505   }
14506   }
14507 
14508   llvm_unreachable("Invalid StmtClass!");
14509 }
14510 
14511 /// Evaluate an expression as a C++11 integral constant expression.
14512 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
14513                                                     const Expr *E,
14514                                                     llvm::APSInt *Value,
14515                                                     SourceLocation *Loc) {
14516   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14517     if (Loc) *Loc = E->getExprLoc();
14518     return false;
14519   }
14520 
14521   APValue Result;
14522   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
14523     return false;
14524 
14525   if (!Result.isInt()) {
14526     if (Loc) *Loc = E->getExprLoc();
14527     return false;
14528   }
14529 
14530   if (Value) *Value = Result.getInt();
14531   return true;
14532 }
14533 
14534 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
14535                                  SourceLocation *Loc) const {
14536   assert(!isValueDependent() &&
14537          "Expression evaluator can't be called on a dependent expression.");
14538 
14539   if (Ctx.getLangOpts().CPlusPlus11)
14540     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
14541 
14542   ICEDiag D = CheckICE(this, Ctx);
14543   if (D.Kind != IK_ICE) {
14544     if (Loc) *Loc = D.Loc;
14545     return false;
14546   }
14547   return true;
14548 }
14549 
14550 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
14551                                  SourceLocation *Loc, bool isEvaluated) const {
14552   assert(!isValueDependent() &&
14553          "Expression evaluator can't be called on a dependent expression.");
14554 
14555   if (Ctx.getLangOpts().CPlusPlus11)
14556     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
14557 
14558   if (!isIntegerConstantExpr(Ctx, Loc))
14559     return false;
14560 
14561   // The only possible side-effects here are due to UB discovered in the
14562   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
14563   // required to treat the expression as an ICE, so we produce the folded
14564   // value.
14565   EvalResult ExprResult;
14566   Expr::EvalStatus Status;
14567   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
14568   Info.InConstantContext = true;
14569 
14570   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
14571     llvm_unreachable("ICE cannot be evaluated!");
14572 
14573   Value = ExprResult.Val.getInt();
14574   return true;
14575 }
14576 
14577 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
14578   assert(!isValueDependent() &&
14579          "Expression evaluator can't be called on a dependent expression.");
14580 
14581   return CheckICE(this, Ctx).Kind == IK_ICE;
14582 }
14583 
14584 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
14585                                SourceLocation *Loc) const {
14586   assert(!isValueDependent() &&
14587          "Expression evaluator can't be called on a dependent expression.");
14588 
14589   // We support this checking in C++98 mode in order to diagnose compatibility
14590   // issues.
14591   assert(Ctx.getLangOpts().CPlusPlus);
14592 
14593   // Build evaluation settings.
14594   Expr::EvalStatus Status;
14595   SmallVector<PartialDiagnosticAt, 8> Diags;
14596   Status.Diag = &Diags;
14597   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
14598 
14599   APValue Scratch;
14600   bool IsConstExpr =
14601       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
14602       // FIXME: We don't produce a diagnostic for this, but the callers that
14603       // call us on arbitrary full-expressions should generally not care.
14604       Info.discardCleanups() && !Status.HasSideEffects;
14605 
14606   if (!Diags.empty()) {
14607     IsConstExpr = false;
14608     if (Loc) *Loc = Diags[0].first;
14609   } else if (!IsConstExpr) {
14610     // FIXME: This shouldn't happen.
14611     if (Loc) *Loc = getExprLoc();
14612   }
14613 
14614   return IsConstExpr;
14615 }
14616 
14617 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
14618                                     const FunctionDecl *Callee,
14619                                     ArrayRef<const Expr*> Args,
14620                                     const Expr *This) const {
14621   assert(!isValueDependent() &&
14622          "Expression evaluator can't be called on a dependent expression.");
14623 
14624   Expr::EvalStatus Status;
14625   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
14626   Info.InConstantContext = true;
14627 
14628   LValue ThisVal;
14629   const LValue *ThisPtr = nullptr;
14630   if (This) {
14631 #ifndef NDEBUG
14632     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
14633     assert(MD && "Don't provide `this` for non-methods.");
14634     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
14635 #endif
14636     if (!This->isValueDependent() &&
14637         EvaluateObjectArgument(Info, This, ThisVal) &&
14638         !Info.EvalStatus.HasSideEffects)
14639       ThisPtr = &ThisVal;
14640 
14641     // Ignore any side-effects from a failed evaluation. This is safe because
14642     // they can't interfere with any other argument evaluation.
14643     Info.EvalStatus.HasSideEffects = false;
14644   }
14645 
14646   ArgVector ArgValues(Args.size());
14647   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
14648        I != E; ++I) {
14649     if ((*I)->isValueDependent() ||
14650         !Evaluate(ArgValues[I - Args.begin()], Info, *I) ||
14651         Info.EvalStatus.HasSideEffects)
14652       // If evaluation fails, throw away the argument entirely.
14653       ArgValues[I - Args.begin()] = APValue();
14654 
14655     // Ignore any side-effects from a failed evaluation. This is safe because
14656     // they can't interfere with any other argument evaluation.
14657     Info.EvalStatus.HasSideEffects = false;
14658   }
14659 
14660   // Parameter cleanups happen in the caller and are not part of this
14661   // evaluation.
14662   Info.discardCleanups();
14663   Info.EvalStatus.HasSideEffects = false;
14664 
14665   // Build fake call to Callee.
14666   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
14667                        ArgValues.data());
14668   // FIXME: Missing ExprWithCleanups in enable_if conditions?
14669   FullExpressionRAII Scope(Info);
14670   return Evaluate(Value, Info, this) && Scope.destroy() &&
14671          !Info.EvalStatus.HasSideEffects;
14672 }
14673 
14674 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
14675                                    SmallVectorImpl<
14676                                      PartialDiagnosticAt> &Diags) {
14677   // FIXME: It would be useful to check constexpr function templates, but at the
14678   // moment the constant expression evaluator cannot cope with the non-rigorous
14679   // ASTs which we build for dependent expressions.
14680   if (FD->isDependentContext())
14681     return true;
14682 
14683   Expr::EvalStatus Status;
14684   Status.Diag = &Diags;
14685 
14686   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
14687   Info.InConstantContext = true;
14688   Info.CheckingPotentialConstantExpression = true;
14689 
14690   // The constexpr VM attempts to compile all methods to bytecode here.
14691   if (Info.EnableNewConstInterp) {
14692     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
14693     return Diags.empty();
14694   }
14695 
14696   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
14697   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
14698 
14699   // Fabricate an arbitrary expression on the stack and pretend that it
14700   // is a temporary being used as the 'this' pointer.
14701   LValue This;
14702   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
14703   This.set({&VIE, Info.CurrentCall->Index});
14704 
14705   ArrayRef<const Expr*> Args;
14706 
14707   APValue Scratch;
14708   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
14709     // Evaluate the call as a constant initializer, to allow the construction
14710     // of objects of non-literal types.
14711     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
14712     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
14713   } else {
14714     SourceLocation Loc = FD->getLocation();
14715     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
14716                        Args, FD->getBody(), Info, Scratch, nullptr);
14717   }
14718 
14719   return Diags.empty();
14720 }
14721 
14722 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
14723                                               const FunctionDecl *FD,
14724                                               SmallVectorImpl<
14725                                                 PartialDiagnosticAt> &Diags) {
14726   assert(!E->isValueDependent() &&
14727          "Expression evaluator can't be called on a dependent expression.");
14728 
14729   Expr::EvalStatus Status;
14730   Status.Diag = &Diags;
14731 
14732   EvalInfo Info(FD->getASTContext(), Status,
14733                 EvalInfo::EM_ConstantExpressionUnevaluated);
14734   Info.InConstantContext = true;
14735   Info.CheckingPotentialConstantExpression = true;
14736 
14737   // Fabricate a call stack frame to give the arguments a plausible cover story.
14738   ArrayRef<const Expr*> Args;
14739   ArgVector ArgValues(0);
14740   bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
14741   (void)Success;
14742   assert(Success &&
14743          "Failed to set up arguments for potential constant evaluation");
14744   CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
14745 
14746   APValue ResultScratch;
14747   Evaluate(ResultScratch, Info, E);
14748   return Diags.empty();
14749 }
14750 
14751 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
14752                                  unsigned Type) const {
14753   if (!getType()->isPointerType())
14754     return false;
14755 
14756   Expr::EvalStatus Status;
14757   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
14758   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
14759 }
14760