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     AfterFields,
678     Destroying,
679     DestroyingBases
680   };
681 }
682 
683 namespace llvm {
684 template<> struct DenseMapInfo<ObjectUnderConstruction> {
685   using Base = DenseMapInfo<APValue::LValueBase>;
686   static ObjectUnderConstruction getEmptyKey() {
687     return {Base::getEmptyKey(), {}}; }
688   static ObjectUnderConstruction getTombstoneKey() {
689     return {Base::getTombstoneKey(), {}};
690   }
691   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
692     return hash_value(Object);
693   }
694   static bool isEqual(const ObjectUnderConstruction &LHS,
695                       const ObjectUnderConstruction &RHS) {
696     return LHS == RHS;
697   }
698 };
699 }
700 
701 namespace {
702   /// A dynamically-allocated heap object.
703   struct DynAlloc {
704     /// The value of this heap-allocated object.
705     APValue Value;
706     /// The allocating expression; used for diagnostics. Either a CXXNewExpr
707     /// or a CallExpr (the latter is for direct calls to operator new inside
708     /// std::allocator<T>::allocate).
709     const Expr *AllocExpr = nullptr;
710 
711     enum Kind {
712       New,
713       ArrayNew,
714       StdAllocator
715     };
716 
717     /// Get the kind of the allocation. This must match between allocation
718     /// and deallocation.
719     Kind getKind() const {
720       if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
721         return NE->isArray() ? ArrayNew : New;
722       assert(isa<CallExpr>(AllocExpr));
723       return StdAllocator;
724     }
725   };
726 
727   struct DynAllocOrder {
728     bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
729       return L.getIndex() < R.getIndex();
730     }
731   };
732 
733   /// EvalInfo - This is a private struct used by the evaluator to capture
734   /// information about a subexpression as it is folded.  It retains information
735   /// about the AST context, but also maintains information about the folded
736   /// expression.
737   ///
738   /// If an expression could be evaluated, it is still possible it is not a C
739   /// "integer constant expression" or constant expression.  If not, this struct
740   /// captures information about how and why not.
741   ///
742   /// One bit of information passed *into* the request for constant folding
743   /// indicates whether the subexpression is "evaluated" or not according to C
744   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
745   /// evaluate the expression regardless of what the RHS is, but C only allows
746   /// certain things in certain situations.
747   class EvalInfo : public interp::State {
748   public:
749     ASTContext &Ctx;
750 
751     /// EvalStatus - Contains information about the evaluation.
752     Expr::EvalStatus &EvalStatus;
753 
754     /// CurrentCall - The top of the constexpr call stack.
755     CallStackFrame *CurrentCall;
756 
757     /// CallStackDepth - The number of calls in the call stack right now.
758     unsigned CallStackDepth;
759 
760     /// NextCallIndex - The next call index to assign.
761     unsigned NextCallIndex;
762 
763     /// StepsLeft - The remaining number of evaluation steps we're permitted
764     /// to perform. This is essentially a limit for the number of statements
765     /// we will evaluate.
766     unsigned StepsLeft;
767 
768     /// Enable the experimental new constant interpreter. If an expression is
769     /// not supported by the interpreter, an error is triggered.
770     bool EnableNewConstInterp;
771 
772     /// BottomFrame - The frame in which evaluation started. This must be
773     /// initialized after CurrentCall and CallStackDepth.
774     CallStackFrame BottomFrame;
775 
776     /// A stack of values whose lifetimes end at the end of some surrounding
777     /// evaluation frame.
778     llvm::SmallVector<Cleanup, 16> CleanupStack;
779 
780     /// EvaluatingDecl - This is the declaration whose initializer is being
781     /// evaluated, if any.
782     APValue::LValueBase EvaluatingDecl;
783 
784     enum class EvaluatingDeclKind {
785       None,
786       /// We're evaluating the construction of EvaluatingDecl.
787       Ctor,
788       /// We're evaluating the destruction of EvaluatingDecl.
789       Dtor,
790     };
791     EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
792 
793     /// EvaluatingDeclValue - This is the value being constructed for the
794     /// declaration whose initializer is being evaluated, if any.
795     APValue *EvaluatingDeclValue;
796 
797     /// Set of objects that are currently being constructed.
798     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
799         ObjectsUnderConstruction;
800 
801     /// Current heap allocations, along with the location where each was
802     /// allocated. We use std::map here because we need stable addresses
803     /// for the stored APValues.
804     std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
805 
806     /// The number of heap allocations performed so far in this evaluation.
807     unsigned NumHeapAllocs = 0;
808 
809     struct EvaluatingConstructorRAII {
810       EvalInfo &EI;
811       ObjectUnderConstruction Object;
812       bool DidInsert;
813       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
814                                 bool HasBases)
815           : EI(EI), Object(Object) {
816         DidInsert =
817             EI.ObjectsUnderConstruction
818                 .insert({Object, HasBases ? ConstructionPhase::Bases
819                                           : ConstructionPhase::AfterBases})
820                 .second;
821       }
822       void finishedConstructingBases() {
823         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
824       }
825       void finishedConstructingFields() {
826         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
827       }
828       ~EvaluatingConstructorRAII() {
829         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
830       }
831     };
832 
833     struct EvaluatingDestructorRAII {
834       EvalInfo &EI;
835       ObjectUnderConstruction Object;
836       bool DidInsert;
837       EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
838           : EI(EI), Object(Object) {
839         DidInsert = EI.ObjectsUnderConstruction
840                         .insert({Object, ConstructionPhase::Destroying})
841                         .second;
842       }
843       void startedDestroyingBases() {
844         EI.ObjectsUnderConstruction[Object] =
845             ConstructionPhase::DestroyingBases;
846       }
847       ~EvaluatingDestructorRAII() {
848         if (DidInsert)
849           EI.ObjectsUnderConstruction.erase(Object);
850       }
851     };
852 
853     ConstructionPhase
854     isEvaluatingCtorDtor(APValue::LValueBase Base,
855                          ArrayRef<APValue::LValuePathEntry> Path) {
856       return ObjectsUnderConstruction.lookup({Base, Path});
857     }
858 
859     /// If we're currently speculatively evaluating, the outermost call stack
860     /// depth at which we can mutate state, otherwise 0.
861     unsigned SpeculativeEvaluationDepth = 0;
862 
863     /// The current array initialization index, if we're performing array
864     /// initialization.
865     uint64_t ArrayInitIndex = -1;
866 
867     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
868     /// notes attached to it will also be stored, otherwise they will not be.
869     bool HasActiveDiagnostic;
870 
871     /// Have we emitted a diagnostic explaining why we couldn't constant
872     /// fold (not just why it's not strictly a constant expression)?
873     bool HasFoldFailureDiagnostic;
874 
875     /// Whether or not we're in a context where the front end requires a
876     /// constant value.
877     bool InConstantContext;
878 
879     /// Whether we're checking that an expression is a potential constant
880     /// expression. If so, do not fail on constructs that could become constant
881     /// later on (such as a use of an undefined global).
882     bool CheckingPotentialConstantExpression = false;
883 
884     /// Whether we're checking for an expression that has undefined behavior.
885     /// If so, we will produce warnings if we encounter an operation that is
886     /// always undefined.
887     bool CheckingForUndefinedBehavior = false;
888 
889     enum EvaluationMode {
890       /// Evaluate as a constant expression. Stop if we find that the expression
891       /// is not a constant expression.
892       EM_ConstantExpression,
893 
894       /// Evaluate as a constant expression. Stop if we find that the expression
895       /// is not a constant expression. Some expressions can be retried in the
896       /// optimizer if we don't constant fold them here, but in an unevaluated
897       /// context we try to fold them immediately since the optimizer never
898       /// gets a chance to look at it.
899       EM_ConstantExpressionUnevaluated,
900 
901       /// Fold the expression to a constant. Stop if we hit a side-effect that
902       /// we can't model.
903       EM_ConstantFold,
904 
905       /// Evaluate in any way we know how. Don't worry about side-effects that
906       /// can't be modeled.
907       EM_IgnoreSideEffects,
908     } EvalMode;
909 
910     /// Are we checking whether the expression is a potential constant
911     /// expression?
912     bool checkingPotentialConstantExpression() const override  {
913       return CheckingPotentialConstantExpression;
914     }
915 
916     /// Are we checking an expression for overflow?
917     // FIXME: We should check for any kind of undefined or suspicious behavior
918     // in such constructs, not just overflow.
919     bool checkingForUndefinedBehavior() const override {
920       return CheckingForUndefinedBehavior;
921     }
922 
923     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
924         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
925           CallStackDepth(0), NextCallIndex(1),
926           StepsLeft(C.getLangOpts().ConstexprStepLimit),
927           EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
928           BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
929           EvaluatingDecl((const ValueDecl *)nullptr),
930           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
931           HasFoldFailureDiagnostic(false), InConstantContext(false),
932           EvalMode(Mode) {}
933 
934     ~EvalInfo() {
935       discardCleanups();
936     }
937 
938     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
939                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
940       EvaluatingDecl = Base;
941       IsEvaluatingDecl = EDK;
942       EvaluatingDeclValue = &Value;
943     }
944 
945     bool CheckCallLimit(SourceLocation Loc) {
946       // Don't perform any constexpr calls (other than the call we're checking)
947       // when checking a potential constant expression.
948       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
949         return false;
950       if (NextCallIndex == 0) {
951         // NextCallIndex has wrapped around.
952         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
953         return false;
954       }
955       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
956         return true;
957       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
958         << getLangOpts().ConstexprCallDepth;
959       return false;
960     }
961 
962     std::pair<CallStackFrame *, unsigned>
963     getCallFrameAndDepth(unsigned CallIndex) {
964       assert(CallIndex && "no call index in getCallFrameAndDepth");
965       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
966       // be null in this loop.
967       unsigned Depth = CallStackDepth;
968       CallStackFrame *Frame = CurrentCall;
969       while (Frame->Index > CallIndex) {
970         Frame = Frame->Caller;
971         --Depth;
972       }
973       if (Frame->Index == CallIndex)
974         return {Frame, Depth};
975       return {nullptr, 0};
976     }
977 
978     bool nextStep(const Stmt *S) {
979       if (!StepsLeft) {
980         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
981         return false;
982       }
983       --StepsLeft;
984       return true;
985     }
986 
987     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
988 
989     Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
990       Optional<DynAlloc*> Result;
991       auto It = HeapAllocs.find(DA);
992       if (It != HeapAllocs.end())
993         Result = &It->second;
994       return Result;
995     }
996 
997     /// Information about a stack frame for std::allocator<T>::[de]allocate.
998     struct StdAllocatorCaller {
999       unsigned FrameIndex;
1000       QualType ElemType;
1001       explicit operator bool() const { return FrameIndex != 0; };
1002     };
1003 
1004     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1005       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1006            Call = Call->Caller) {
1007         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1008         if (!MD)
1009           continue;
1010         const IdentifierInfo *FnII = MD->getIdentifier();
1011         if (!FnII || !FnII->isStr(FnName))
1012           continue;
1013 
1014         const auto *CTSD =
1015             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1016         if (!CTSD)
1017           continue;
1018 
1019         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1020         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1021         if (CTSD->isInStdNamespace() && ClassII &&
1022             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1023             TAL[0].getKind() == TemplateArgument::Type)
1024           return {Call->Index, TAL[0].getAsType()};
1025       }
1026 
1027       return {};
1028     }
1029 
1030     void performLifetimeExtension() {
1031       // Disable the cleanups for lifetime-extended temporaries.
1032       CleanupStack.erase(
1033           std::remove_if(CleanupStack.begin(), CleanupStack.end(),
1034                          [](Cleanup &C) { return C.isLifetimeExtended(); }),
1035           CleanupStack.end());
1036      }
1037 
1038     /// Throw away any remaining cleanups at the end of evaluation. If any
1039     /// cleanups would have had a side-effect, note that as an unmodeled
1040     /// side-effect and return false. Otherwise, return true.
1041     bool discardCleanups() {
1042       for (Cleanup &C : CleanupStack) {
1043         if (C.hasSideEffect() && !noteSideEffect()) {
1044           CleanupStack.clear();
1045           return false;
1046         }
1047       }
1048       CleanupStack.clear();
1049       return true;
1050     }
1051 
1052   private:
1053     interp::Frame *getCurrentFrame() override { return CurrentCall; }
1054     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1055 
1056     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1057     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1058 
1059     void setFoldFailureDiagnostic(bool Flag) override {
1060       HasFoldFailureDiagnostic = Flag;
1061     }
1062 
1063     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1064 
1065     ASTContext &getCtx() const override { return Ctx; }
1066 
1067     // If we have a prior diagnostic, it will be noting that the expression
1068     // isn't a constant expression. This diagnostic is more important,
1069     // unless we require this evaluation to produce a constant expression.
1070     //
1071     // FIXME: We might want to show both diagnostics to the user in
1072     // EM_ConstantFold mode.
1073     bool hasPriorDiagnostic() override {
1074       if (!EvalStatus.Diag->empty()) {
1075         switch (EvalMode) {
1076         case EM_ConstantFold:
1077         case EM_IgnoreSideEffects:
1078           if (!HasFoldFailureDiagnostic)
1079             break;
1080           // We've already failed to fold something. Keep that diagnostic.
1081           LLVM_FALLTHROUGH;
1082         case EM_ConstantExpression:
1083         case EM_ConstantExpressionUnevaluated:
1084           setActiveDiagnostic(false);
1085           return true;
1086         }
1087       }
1088       return false;
1089     }
1090 
1091     unsigned getCallStackDepth() override { return CallStackDepth; }
1092 
1093   public:
1094     /// Should we continue evaluation after encountering a side-effect that we
1095     /// couldn't model?
1096     bool keepEvaluatingAfterSideEffect() {
1097       switch (EvalMode) {
1098       case EM_IgnoreSideEffects:
1099         return true;
1100 
1101       case EM_ConstantExpression:
1102       case EM_ConstantExpressionUnevaluated:
1103       case EM_ConstantFold:
1104         // By default, assume any side effect might be valid in some other
1105         // evaluation of this expression from a different context.
1106         return checkingPotentialConstantExpression() ||
1107                checkingForUndefinedBehavior();
1108       }
1109       llvm_unreachable("Missed EvalMode case");
1110     }
1111 
1112     /// Note that we have had a side-effect, and determine whether we should
1113     /// keep evaluating.
1114     bool noteSideEffect() {
1115       EvalStatus.HasSideEffects = true;
1116       return keepEvaluatingAfterSideEffect();
1117     }
1118 
1119     /// Should we continue evaluation after encountering undefined behavior?
1120     bool keepEvaluatingAfterUndefinedBehavior() {
1121       switch (EvalMode) {
1122       case EM_IgnoreSideEffects:
1123       case EM_ConstantFold:
1124         return true;
1125 
1126       case EM_ConstantExpression:
1127       case EM_ConstantExpressionUnevaluated:
1128         return checkingForUndefinedBehavior();
1129       }
1130       llvm_unreachable("Missed EvalMode case");
1131     }
1132 
1133     /// Note that we hit something that was technically undefined behavior, but
1134     /// that we can evaluate past it (such as signed overflow or floating-point
1135     /// division by zero.)
1136     bool noteUndefinedBehavior() override {
1137       EvalStatus.HasUndefinedBehavior = true;
1138       return keepEvaluatingAfterUndefinedBehavior();
1139     }
1140 
1141     /// Should we continue evaluation as much as possible after encountering a
1142     /// construct which can't be reduced to a value?
1143     bool keepEvaluatingAfterFailure() const override {
1144       if (!StepsLeft)
1145         return false;
1146 
1147       switch (EvalMode) {
1148       case EM_ConstantExpression:
1149       case EM_ConstantExpressionUnevaluated:
1150       case EM_ConstantFold:
1151       case EM_IgnoreSideEffects:
1152         return checkingPotentialConstantExpression() ||
1153                checkingForUndefinedBehavior();
1154       }
1155       llvm_unreachable("Missed EvalMode case");
1156     }
1157 
1158     /// Notes that we failed to evaluate an expression that other expressions
1159     /// directly depend on, and determine if we should keep evaluating. This
1160     /// should only be called if we actually intend to keep evaluating.
1161     ///
1162     /// Call noteSideEffect() instead if we may be able to ignore the value that
1163     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1164     ///
1165     /// (Foo(), 1)      // use noteSideEffect
1166     /// (Foo() || true) // use noteSideEffect
1167     /// Foo() + 1       // use noteFailure
1168     LLVM_NODISCARD bool noteFailure() {
1169       // Failure when evaluating some expression often means there is some
1170       // subexpression whose evaluation was skipped. Therefore, (because we
1171       // don't track whether we skipped an expression when unwinding after an
1172       // evaluation failure) every evaluation failure that bubbles up from a
1173       // subexpression implies that a side-effect has potentially happened. We
1174       // skip setting the HasSideEffects flag to true until we decide to
1175       // continue evaluating after that point, which happens here.
1176       bool KeepGoing = keepEvaluatingAfterFailure();
1177       EvalStatus.HasSideEffects |= KeepGoing;
1178       return KeepGoing;
1179     }
1180 
1181     class ArrayInitLoopIndex {
1182       EvalInfo &Info;
1183       uint64_t OuterIndex;
1184 
1185     public:
1186       ArrayInitLoopIndex(EvalInfo &Info)
1187           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1188         Info.ArrayInitIndex = 0;
1189       }
1190       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1191 
1192       operator uint64_t&() { return Info.ArrayInitIndex; }
1193     };
1194   };
1195 
1196   /// Object used to treat all foldable expressions as constant expressions.
1197   struct FoldConstant {
1198     EvalInfo &Info;
1199     bool Enabled;
1200     bool HadNoPriorDiags;
1201     EvalInfo::EvaluationMode OldMode;
1202 
1203     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1204       : Info(Info),
1205         Enabled(Enabled),
1206         HadNoPriorDiags(Info.EvalStatus.Diag &&
1207                         Info.EvalStatus.Diag->empty() &&
1208                         !Info.EvalStatus.HasSideEffects),
1209         OldMode(Info.EvalMode) {
1210       if (Enabled)
1211         Info.EvalMode = EvalInfo::EM_ConstantFold;
1212     }
1213     void keepDiagnostics() { Enabled = false; }
1214     ~FoldConstant() {
1215       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1216           !Info.EvalStatus.HasSideEffects)
1217         Info.EvalStatus.Diag->clear();
1218       Info.EvalMode = OldMode;
1219     }
1220   };
1221 
1222   /// RAII object used to set the current evaluation mode to ignore
1223   /// side-effects.
1224   struct IgnoreSideEffectsRAII {
1225     EvalInfo &Info;
1226     EvalInfo::EvaluationMode OldMode;
1227     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1228         : Info(Info), OldMode(Info.EvalMode) {
1229       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1230     }
1231 
1232     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1233   };
1234 
1235   /// RAII object used to optionally suppress diagnostics and side-effects from
1236   /// a speculative evaluation.
1237   class SpeculativeEvaluationRAII {
1238     EvalInfo *Info = nullptr;
1239     Expr::EvalStatus OldStatus;
1240     unsigned OldSpeculativeEvaluationDepth;
1241 
1242     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1243       Info = Other.Info;
1244       OldStatus = Other.OldStatus;
1245       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1246       Other.Info = nullptr;
1247     }
1248 
1249     void maybeRestoreState() {
1250       if (!Info)
1251         return;
1252 
1253       Info->EvalStatus = OldStatus;
1254       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1255     }
1256 
1257   public:
1258     SpeculativeEvaluationRAII() = default;
1259 
1260     SpeculativeEvaluationRAII(
1261         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1262         : Info(&Info), OldStatus(Info.EvalStatus),
1263           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1264       Info.EvalStatus.Diag = NewDiag;
1265       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1266     }
1267 
1268     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1269     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1270       moveFromAndCancel(std::move(Other));
1271     }
1272 
1273     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1274       maybeRestoreState();
1275       moveFromAndCancel(std::move(Other));
1276       return *this;
1277     }
1278 
1279     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1280   };
1281 
1282   /// RAII object wrapping a full-expression or block scope, and handling
1283   /// the ending of the lifetime of temporaries created within it.
1284   template<bool IsFullExpression>
1285   class ScopeRAII {
1286     EvalInfo &Info;
1287     unsigned OldStackSize;
1288   public:
1289     ScopeRAII(EvalInfo &Info)
1290         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1291       // Push a new temporary version. This is needed to distinguish between
1292       // temporaries created in different iterations of a loop.
1293       Info.CurrentCall->pushTempVersion();
1294     }
1295     bool destroy(bool RunDestructors = true) {
1296       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1297       OldStackSize = -1U;
1298       return OK;
1299     }
1300     ~ScopeRAII() {
1301       if (OldStackSize != -1U)
1302         destroy(false);
1303       // Body moved to a static method to encourage the compiler to inline away
1304       // instances of this class.
1305       Info.CurrentCall->popTempVersion();
1306     }
1307   private:
1308     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1309                         unsigned OldStackSize) {
1310       assert(OldStackSize <= Info.CleanupStack.size() &&
1311              "running cleanups out of order?");
1312 
1313       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1314       // for a full-expression scope.
1315       bool Success = true;
1316       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1317         if (!(IsFullExpression &&
1318               Info.CleanupStack[I - 1].isLifetimeExtended())) {
1319           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1320             Success = false;
1321             break;
1322           }
1323         }
1324       }
1325 
1326       // Compact lifetime-extended cleanups.
1327       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1328       if (IsFullExpression)
1329         NewEnd =
1330             std::remove_if(NewEnd, Info.CleanupStack.end(),
1331                            [](Cleanup &C) { return !C.isLifetimeExtended(); });
1332       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1333       return Success;
1334     }
1335   };
1336   typedef ScopeRAII<false> BlockScopeRAII;
1337   typedef ScopeRAII<true> FullExpressionRAII;
1338 }
1339 
1340 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1341                                          CheckSubobjectKind CSK) {
1342   if (Invalid)
1343     return false;
1344   if (isOnePastTheEnd()) {
1345     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1346       << CSK;
1347     setInvalid();
1348     return false;
1349   }
1350   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1351   // must actually be at least one array element; even a VLA cannot have a
1352   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1353   return true;
1354 }
1355 
1356 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1357                                                                 const Expr *E) {
1358   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1359   // Do not set the designator as invalid: we can represent this situation,
1360   // and correct handling of __builtin_object_size requires us to do so.
1361 }
1362 
1363 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1364                                                     const Expr *E,
1365                                                     const APSInt &N) {
1366   // If we're complaining, we must be able to statically determine the size of
1367   // the most derived array.
1368   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1369     Info.CCEDiag(E, diag::note_constexpr_array_index)
1370       << N << /*array*/ 0
1371       << static_cast<unsigned>(getMostDerivedArraySize());
1372   else
1373     Info.CCEDiag(E, diag::note_constexpr_array_index)
1374       << N << /*non-array*/ 1;
1375   setInvalid();
1376 }
1377 
1378 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1379                                const FunctionDecl *Callee, const LValue *This,
1380                                APValue *Arguments)
1381     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1382       Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1383   Info.CurrentCall = this;
1384   ++Info.CallStackDepth;
1385 }
1386 
1387 CallStackFrame::~CallStackFrame() {
1388   assert(Info.CurrentCall == this && "calls retired out of order");
1389   --Info.CallStackDepth;
1390   Info.CurrentCall = Caller;
1391 }
1392 
1393 static bool isRead(AccessKinds AK) {
1394   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1395 }
1396 
1397 static bool isModification(AccessKinds AK) {
1398   switch (AK) {
1399   case AK_Read:
1400   case AK_ReadObjectRepresentation:
1401   case AK_MemberCall:
1402   case AK_DynamicCast:
1403   case AK_TypeId:
1404     return false;
1405   case AK_Assign:
1406   case AK_Increment:
1407   case AK_Decrement:
1408   case AK_Construct:
1409   case AK_Destroy:
1410     return true;
1411   }
1412   llvm_unreachable("unknown access kind");
1413 }
1414 
1415 static bool isAnyAccess(AccessKinds AK) {
1416   return isRead(AK) || isModification(AK);
1417 }
1418 
1419 /// Is this an access per the C++ definition?
1420 static bool isFormalAccess(AccessKinds AK) {
1421   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1422 }
1423 
1424 /// Is this kind of axcess valid on an indeterminate object value?
1425 static bool isValidIndeterminateAccess(AccessKinds AK) {
1426   switch (AK) {
1427   case AK_Read:
1428   case AK_Increment:
1429   case AK_Decrement:
1430     // These need the object's value.
1431     return false;
1432 
1433   case AK_ReadObjectRepresentation:
1434   case AK_Assign:
1435   case AK_Construct:
1436   case AK_Destroy:
1437     // Construction and destruction don't need the value.
1438     return true;
1439 
1440   case AK_MemberCall:
1441   case AK_DynamicCast:
1442   case AK_TypeId:
1443     // These aren't really meaningful on scalars.
1444     return true;
1445   }
1446   llvm_unreachable("unknown access kind");
1447 }
1448 
1449 namespace {
1450   struct ComplexValue {
1451   private:
1452     bool IsInt;
1453 
1454   public:
1455     APSInt IntReal, IntImag;
1456     APFloat FloatReal, FloatImag;
1457 
1458     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1459 
1460     void makeComplexFloat() { IsInt = false; }
1461     bool isComplexFloat() const { return !IsInt; }
1462     APFloat &getComplexFloatReal() { return FloatReal; }
1463     APFloat &getComplexFloatImag() { return FloatImag; }
1464 
1465     void makeComplexInt() { IsInt = true; }
1466     bool isComplexInt() const { return IsInt; }
1467     APSInt &getComplexIntReal() { return IntReal; }
1468     APSInt &getComplexIntImag() { return IntImag; }
1469 
1470     void moveInto(APValue &v) const {
1471       if (isComplexFloat())
1472         v = APValue(FloatReal, FloatImag);
1473       else
1474         v = APValue(IntReal, IntImag);
1475     }
1476     void setFrom(const APValue &v) {
1477       assert(v.isComplexFloat() || v.isComplexInt());
1478       if (v.isComplexFloat()) {
1479         makeComplexFloat();
1480         FloatReal = v.getComplexFloatReal();
1481         FloatImag = v.getComplexFloatImag();
1482       } else {
1483         makeComplexInt();
1484         IntReal = v.getComplexIntReal();
1485         IntImag = v.getComplexIntImag();
1486       }
1487     }
1488   };
1489 
1490   struct LValue {
1491     APValue::LValueBase Base;
1492     CharUnits Offset;
1493     SubobjectDesignator Designator;
1494     bool IsNullPtr : 1;
1495     bool InvalidBase : 1;
1496 
1497     const APValue::LValueBase getLValueBase() const { return Base; }
1498     CharUnits &getLValueOffset() { return Offset; }
1499     const CharUnits &getLValueOffset() const { return Offset; }
1500     SubobjectDesignator &getLValueDesignator() { return Designator; }
1501     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1502     bool isNullPointer() const { return IsNullPtr;}
1503 
1504     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1505     unsigned getLValueVersion() const { return Base.getVersion(); }
1506 
1507     void moveInto(APValue &V) const {
1508       if (Designator.Invalid)
1509         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1510       else {
1511         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1512         V = APValue(Base, Offset, Designator.Entries,
1513                     Designator.IsOnePastTheEnd, IsNullPtr);
1514       }
1515     }
1516     void setFrom(ASTContext &Ctx, const APValue &V) {
1517       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1518       Base = V.getLValueBase();
1519       Offset = V.getLValueOffset();
1520       InvalidBase = false;
1521       Designator = SubobjectDesignator(Ctx, V);
1522       IsNullPtr = V.isNullPointer();
1523     }
1524 
1525     void set(APValue::LValueBase B, bool BInvalid = false) {
1526 #ifndef NDEBUG
1527       // We only allow a few types of invalid bases. Enforce that here.
1528       if (BInvalid) {
1529         const auto *E = B.get<const Expr *>();
1530         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1531                "Unexpected type of invalid base");
1532       }
1533 #endif
1534 
1535       Base = B;
1536       Offset = CharUnits::fromQuantity(0);
1537       InvalidBase = BInvalid;
1538       Designator = SubobjectDesignator(getType(B));
1539       IsNullPtr = false;
1540     }
1541 
1542     void setNull(ASTContext &Ctx, QualType PointerTy) {
1543       Base = (Expr *)nullptr;
1544       Offset =
1545           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1546       InvalidBase = false;
1547       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1548       IsNullPtr = true;
1549     }
1550 
1551     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1552       set(B, true);
1553     }
1554 
1555     std::string toString(ASTContext &Ctx, QualType T) const {
1556       APValue Printable;
1557       moveInto(Printable);
1558       return Printable.getAsString(Ctx, T);
1559     }
1560 
1561   private:
1562     // Check that this LValue is not based on a null pointer. If it is, produce
1563     // a diagnostic and mark the designator as invalid.
1564     template <typename GenDiagType>
1565     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1566       if (Designator.Invalid)
1567         return false;
1568       if (IsNullPtr) {
1569         GenDiag();
1570         Designator.setInvalid();
1571         return false;
1572       }
1573       return true;
1574     }
1575 
1576   public:
1577     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1578                           CheckSubobjectKind CSK) {
1579       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1580         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1581       });
1582     }
1583 
1584     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1585                                        AccessKinds AK) {
1586       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1587         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1588       });
1589     }
1590 
1591     // Check this LValue refers to an object. If not, set the designator to be
1592     // invalid and emit a diagnostic.
1593     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1594       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1595              Designator.checkSubobject(Info, E, CSK);
1596     }
1597 
1598     void addDecl(EvalInfo &Info, const Expr *E,
1599                  const Decl *D, bool Virtual = false) {
1600       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1601         Designator.addDeclUnchecked(D, Virtual);
1602     }
1603     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1604       if (!Designator.Entries.empty()) {
1605         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1606         Designator.setInvalid();
1607         return;
1608       }
1609       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1610         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1611         Designator.FirstEntryIsAnUnsizedArray = true;
1612         Designator.addUnsizedArrayUnchecked(ElemTy);
1613       }
1614     }
1615     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1616       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1617         Designator.addArrayUnchecked(CAT);
1618     }
1619     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1620       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1621         Designator.addComplexUnchecked(EltTy, Imag);
1622     }
1623     void clearIsNullPointer() {
1624       IsNullPtr = false;
1625     }
1626     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1627                               const APSInt &Index, CharUnits ElementSize) {
1628       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1629       // but we're not required to diagnose it and it's valid in C++.)
1630       if (!Index)
1631         return;
1632 
1633       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1634       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1635       // offsets.
1636       uint64_t Offset64 = Offset.getQuantity();
1637       uint64_t ElemSize64 = ElementSize.getQuantity();
1638       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1639       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1640 
1641       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1642         Designator.adjustIndex(Info, E, Index);
1643       clearIsNullPointer();
1644     }
1645     void adjustOffset(CharUnits N) {
1646       Offset += N;
1647       if (N.getQuantity())
1648         clearIsNullPointer();
1649     }
1650   };
1651 
1652   struct MemberPtr {
1653     MemberPtr() {}
1654     explicit MemberPtr(const ValueDecl *Decl) :
1655       DeclAndIsDerivedMember(Decl, false), Path() {}
1656 
1657     /// The member or (direct or indirect) field referred to by this member
1658     /// pointer, or 0 if this is a null member pointer.
1659     const ValueDecl *getDecl() const {
1660       return DeclAndIsDerivedMember.getPointer();
1661     }
1662     /// Is this actually a member of some type derived from the relevant class?
1663     bool isDerivedMember() const {
1664       return DeclAndIsDerivedMember.getInt();
1665     }
1666     /// Get the class which the declaration actually lives in.
1667     const CXXRecordDecl *getContainingRecord() const {
1668       return cast<CXXRecordDecl>(
1669           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1670     }
1671 
1672     void moveInto(APValue &V) const {
1673       V = APValue(getDecl(), isDerivedMember(), Path);
1674     }
1675     void setFrom(const APValue &V) {
1676       assert(V.isMemberPointer());
1677       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1678       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1679       Path.clear();
1680       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1681       Path.insert(Path.end(), P.begin(), P.end());
1682     }
1683 
1684     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1685     /// whether the member is a member of some class derived from the class type
1686     /// of the member pointer.
1687     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1688     /// Path - The path of base/derived classes from the member declaration's
1689     /// class (exclusive) to the class type of the member pointer (inclusive).
1690     SmallVector<const CXXRecordDecl*, 4> Path;
1691 
1692     /// Perform a cast towards the class of the Decl (either up or down the
1693     /// hierarchy).
1694     bool castBack(const CXXRecordDecl *Class) {
1695       assert(!Path.empty());
1696       const CXXRecordDecl *Expected;
1697       if (Path.size() >= 2)
1698         Expected = Path[Path.size() - 2];
1699       else
1700         Expected = getContainingRecord();
1701       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1702         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1703         // if B does not contain the original member and is not a base or
1704         // derived class of the class containing the original member, the result
1705         // of the cast is undefined.
1706         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1707         // (D::*). We consider that to be a language defect.
1708         return false;
1709       }
1710       Path.pop_back();
1711       return true;
1712     }
1713     /// Perform a base-to-derived member pointer cast.
1714     bool castToDerived(const CXXRecordDecl *Derived) {
1715       if (!getDecl())
1716         return true;
1717       if (!isDerivedMember()) {
1718         Path.push_back(Derived);
1719         return true;
1720       }
1721       if (!castBack(Derived))
1722         return false;
1723       if (Path.empty())
1724         DeclAndIsDerivedMember.setInt(false);
1725       return true;
1726     }
1727     /// Perform a derived-to-base member pointer cast.
1728     bool castToBase(const CXXRecordDecl *Base) {
1729       if (!getDecl())
1730         return true;
1731       if (Path.empty())
1732         DeclAndIsDerivedMember.setInt(true);
1733       if (isDerivedMember()) {
1734         Path.push_back(Base);
1735         return true;
1736       }
1737       return castBack(Base);
1738     }
1739   };
1740 
1741   /// Compare two member pointers, which are assumed to be of the same type.
1742   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1743     if (!LHS.getDecl() || !RHS.getDecl())
1744       return !LHS.getDecl() && !RHS.getDecl();
1745     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1746       return false;
1747     return LHS.Path == RHS.Path;
1748   }
1749 }
1750 
1751 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1752 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1753                             const LValue &This, const Expr *E,
1754                             bool AllowNonLiteralTypes = false);
1755 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1756                            bool InvalidBaseOK = false);
1757 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1758                             bool InvalidBaseOK = false);
1759 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1760                                   EvalInfo &Info);
1761 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1762 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1763 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1764                                     EvalInfo &Info);
1765 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1766 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1767 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1768                            EvalInfo &Info);
1769 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1770 
1771 /// Evaluate an integer or fixed point expression into an APResult.
1772 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1773                                         EvalInfo &Info);
1774 
1775 /// Evaluate only a fixed point expression into an APResult.
1776 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1777                                EvalInfo &Info);
1778 
1779 //===----------------------------------------------------------------------===//
1780 // Misc utilities
1781 //===----------------------------------------------------------------------===//
1782 
1783 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1784 /// preserving its value (by extending by up to one bit as needed).
1785 static void negateAsSigned(APSInt &Int) {
1786   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1787     Int = Int.extend(Int.getBitWidth() + 1);
1788     Int.setIsSigned(true);
1789   }
1790   Int = -Int;
1791 }
1792 
1793 template<typename KeyT>
1794 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1795                                          bool IsLifetimeExtended, LValue &LV) {
1796   unsigned Version = getTempVersion();
1797   APValue::LValueBase Base(Key, Index, Version);
1798   LV.set(Base);
1799   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1800   assert(Result.isAbsent() && "temporary created multiple times");
1801 
1802   // If we're creating a temporary immediately in the operand of a speculative
1803   // evaluation, don't register a cleanup to be run outside the speculative
1804   // evaluation context, since we won't actually be able to initialize this
1805   // object.
1806   if (Index <= Info.SpeculativeEvaluationDepth) {
1807     if (T.isDestructedType())
1808       Info.noteSideEffect();
1809   } else {
1810     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, IsLifetimeExtended));
1811   }
1812   return Result;
1813 }
1814 
1815 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1816   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1817     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1818     return nullptr;
1819   }
1820 
1821   DynamicAllocLValue DA(NumHeapAllocs++);
1822   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1823   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1824                                    std::forward_as_tuple(DA), std::tuple<>());
1825   assert(Result.second && "reused a heap alloc index?");
1826   Result.first->second.AllocExpr = E;
1827   return &Result.first->second.Value;
1828 }
1829 
1830 /// Produce a string describing the given constexpr call.
1831 void CallStackFrame::describe(raw_ostream &Out) {
1832   unsigned ArgIndex = 0;
1833   bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1834                       !isa<CXXConstructorDecl>(Callee) &&
1835                       cast<CXXMethodDecl>(Callee)->isInstance();
1836 
1837   if (!IsMemberCall)
1838     Out << *Callee << '(';
1839 
1840   if (This && IsMemberCall) {
1841     APValue Val;
1842     This->moveInto(Val);
1843     Val.printPretty(Out, Info.Ctx,
1844                     This->Designator.MostDerivedType);
1845     // FIXME: Add parens around Val if needed.
1846     Out << "->" << *Callee << '(';
1847     IsMemberCall = false;
1848   }
1849 
1850   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1851        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1852     if (ArgIndex > (unsigned)IsMemberCall)
1853       Out << ", ";
1854 
1855     const ParmVarDecl *Param = *I;
1856     const APValue &Arg = Arguments[ArgIndex];
1857     Arg.printPretty(Out, Info.Ctx, Param->getType());
1858 
1859     if (ArgIndex == 0 && IsMemberCall)
1860       Out << "->" << *Callee << '(';
1861   }
1862 
1863   Out << ')';
1864 }
1865 
1866 /// Evaluate an expression to see if it had side-effects, and discard its
1867 /// result.
1868 /// \return \c true if the caller should keep evaluating.
1869 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1870   APValue Scratch;
1871   if (!Evaluate(Scratch, Info, E))
1872     // We don't need the value, but we might have skipped a side effect here.
1873     return Info.noteSideEffect();
1874   return true;
1875 }
1876 
1877 /// Should this call expression be treated as a string literal?
1878 static bool IsStringLiteralCall(const CallExpr *E) {
1879   unsigned Builtin = E->getBuiltinCallee();
1880   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1881           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1882 }
1883 
1884 static bool IsGlobalLValue(APValue::LValueBase B) {
1885   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1886   // constant expression of pointer type that evaluates to...
1887 
1888   // ... a null pointer value, or a prvalue core constant expression of type
1889   // std::nullptr_t.
1890   if (!B) return true;
1891 
1892   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1893     // ... the address of an object with static storage duration,
1894     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1895       return VD->hasGlobalStorage();
1896     // ... the address of a function,
1897     return isa<FunctionDecl>(D);
1898   }
1899 
1900   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1901     return true;
1902 
1903   const Expr *E = B.get<const Expr*>();
1904   switch (E->getStmtClass()) {
1905   default:
1906     return false;
1907   case Expr::CompoundLiteralExprClass: {
1908     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1909     return CLE->isFileScope() && CLE->isLValue();
1910   }
1911   case Expr::MaterializeTemporaryExprClass:
1912     // A materialized temporary might have been lifetime-extended to static
1913     // storage duration.
1914     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1915   // A string literal has static storage duration.
1916   case Expr::StringLiteralClass:
1917   case Expr::PredefinedExprClass:
1918   case Expr::ObjCStringLiteralClass:
1919   case Expr::ObjCEncodeExprClass:
1920   case Expr::CXXUuidofExprClass:
1921     return true;
1922   case Expr::ObjCBoxedExprClass:
1923     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
1924   case Expr::CallExprClass:
1925     return IsStringLiteralCall(cast<CallExpr>(E));
1926   // For GCC compatibility, &&label has static storage duration.
1927   case Expr::AddrLabelExprClass:
1928     return true;
1929   // A Block literal expression may be used as the initialization value for
1930   // Block variables at global or local static scope.
1931   case Expr::BlockExprClass:
1932     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1933   case Expr::ImplicitValueInitExprClass:
1934     // FIXME:
1935     // We can never form an lvalue with an implicit value initialization as its
1936     // base through expression evaluation, so these only appear in one case: the
1937     // implicit variable declaration we invent when checking whether a constexpr
1938     // constructor can produce a constant expression. We must assume that such
1939     // an expression might be a global lvalue.
1940     return true;
1941   }
1942 }
1943 
1944 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1945   return LVal.Base.dyn_cast<const ValueDecl*>();
1946 }
1947 
1948 static bool IsLiteralLValue(const LValue &Value) {
1949   if (Value.getLValueCallIndex())
1950     return false;
1951   const Expr *E = Value.Base.dyn_cast<const Expr*>();
1952   return E && !isa<MaterializeTemporaryExpr>(E);
1953 }
1954 
1955 static bool IsWeakLValue(const LValue &Value) {
1956   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1957   return Decl && Decl->isWeak();
1958 }
1959 
1960 static bool isZeroSized(const LValue &Value) {
1961   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1962   if (Decl && isa<VarDecl>(Decl)) {
1963     QualType Ty = Decl->getType();
1964     if (Ty->isArrayType())
1965       return Ty->isIncompleteType() ||
1966              Decl->getASTContext().getTypeSize(Ty) == 0;
1967   }
1968   return false;
1969 }
1970 
1971 static bool HasSameBase(const LValue &A, const LValue &B) {
1972   if (!A.getLValueBase())
1973     return !B.getLValueBase();
1974   if (!B.getLValueBase())
1975     return false;
1976 
1977   if (A.getLValueBase().getOpaqueValue() !=
1978       B.getLValueBase().getOpaqueValue()) {
1979     const Decl *ADecl = GetLValueBaseDecl(A);
1980     if (!ADecl)
1981       return false;
1982     const Decl *BDecl = GetLValueBaseDecl(B);
1983     if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1984       return false;
1985   }
1986 
1987   return IsGlobalLValue(A.getLValueBase()) ||
1988          (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1989           A.getLValueVersion() == B.getLValueVersion());
1990 }
1991 
1992 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1993   assert(Base && "no location for a null lvalue");
1994   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1995   if (VD)
1996     Info.Note(VD->getLocation(), diag::note_declared_at);
1997   else if (const Expr *E = Base.dyn_cast<const Expr*>())
1998     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
1999   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2000     // FIXME: Produce a note for dangling pointers too.
2001     if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
2002       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2003                 diag::note_constexpr_dynamic_alloc_here);
2004   }
2005   // We have no information to show for a typeid(T) object.
2006 }
2007 
2008 enum class CheckEvaluationResultKind {
2009   ConstantExpression,
2010   FullyInitialized,
2011 };
2012 
2013 /// Materialized temporaries that we've already checked to determine if they're
2014 /// initializsed by a constant expression.
2015 using CheckedTemporaries =
2016     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2017 
2018 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2019                                   EvalInfo &Info, SourceLocation DiagLoc,
2020                                   QualType Type, const APValue &Value,
2021                                   Expr::ConstExprUsage Usage,
2022                                   SourceLocation SubobjectLoc,
2023                                   CheckedTemporaries &CheckedTemps);
2024 
2025 /// Check that this reference or pointer core constant expression is a valid
2026 /// value for an address or reference constant expression. Return true if we
2027 /// can fold this expression, whether or not it's a constant expression.
2028 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2029                                           QualType Type, const LValue &LVal,
2030                                           Expr::ConstExprUsage Usage,
2031                                           CheckedTemporaries &CheckedTemps) {
2032   bool IsReferenceType = Type->isReferenceType();
2033 
2034   APValue::LValueBase Base = LVal.getLValueBase();
2035   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2036 
2037   if (auto *VD = LVal.getLValueBase().dyn_cast<const ValueDecl *>()) {
2038     if (auto *FD = dyn_cast<FunctionDecl>(VD)) {
2039       if (FD->isConsteval()) {
2040         Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2041             << !Type->isAnyPointerType();
2042         Info.Note(FD->getLocation(), diag::note_declared_at);
2043         return false;
2044       }
2045     }
2046   }
2047 
2048   // Check that the object is a global. Note that the fake 'this' object we
2049   // manufacture when checking potential constant expressions is conservatively
2050   // assumed to be global here.
2051   if (!IsGlobalLValue(Base)) {
2052     if (Info.getLangOpts().CPlusPlus11) {
2053       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2054       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2055         << IsReferenceType << !Designator.Entries.empty()
2056         << !!VD << VD;
2057       NoteLValueLocation(Info, Base);
2058     } else {
2059       Info.FFDiag(Loc);
2060     }
2061     // Don't allow references to temporaries to escape.
2062     return false;
2063   }
2064   assert((Info.checkingPotentialConstantExpression() ||
2065           LVal.getLValueCallIndex() == 0) &&
2066          "have call index for global lvalue");
2067 
2068   if (Base.is<DynamicAllocLValue>()) {
2069     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2070         << IsReferenceType << !Designator.Entries.empty();
2071     NoteLValueLocation(Info, Base);
2072     return false;
2073   }
2074 
2075   if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
2076     if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
2077       // Check if this is a thread-local variable.
2078       if (Var->getTLSKind())
2079         // FIXME: Diagnostic!
2080         return false;
2081 
2082       // A dllimport variable never acts like a constant.
2083       if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
2084         // FIXME: Diagnostic!
2085         return false;
2086     }
2087     if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
2088       // __declspec(dllimport) must be handled very carefully:
2089       // We must never initialize an expression with the thunk in C++.
2090       // Doing otherwise would allow the same id-expression to yield
2091       // different addresses for the same function in different translation
2092       // units.  However, this means that we must dynamically initialize the
2093       // expression with the contents of the import address table at runtime.
2094       //
2095       // The C language has no notion of ODR; furthermore, it has no notion of
2096       // dynamic initialization.  This means that we are permitted to
2097       // perform initialization with the address of the thunk.
2098       if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
2099           FD->hasAttr<DLLImportAttr>())
2100         // FIXME: Diagnostic!
2101         return false;
2102     }
2103   } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(
2104                  Base.dyn_cast<const Expr *>())) {
2105     if (CheckedTemps.insert(MTE).second) {
2106       QualType TempType = getType(Base);
2107       if (TempType.isDestructedType()) {
2108         Info.FFDiag(MTE->getExprLoc(),
2109                     diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor)
2110             << TempType;
2111         return false;
2112       }
2113 
2114       APValue *V = MTE->getOrCreateValue(false);
2115       assert(V && "evasluation result refers to uninitialised temporary");
2116       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2117                                  Info, MTE->getExprLoc(), TempType, *V,
2118                                  Usage, SourceLocation(), CheckedTemps))
2119         return false;
2120     }
2121   }
2122 
2123   // Allow address constant expressions to be past-the-end pointers. This is
2124   // an extension: the standard requires them to point to an object.
2125   if (!IsReferenceType)
2126     return true;
2127 
2128   // A reference constant expression must refer to an object.
2129   if (!Base) {
2130     // FIXME: diagnostic
2131     Info.CCEDiag(Loc);
2132     return true;
2133   }
2134 
2135   // Does this refer one past the end of some object?
2136   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2137     const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2138     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2139       << !Designator.Entries.empty() << !!VD << VD;
2140     NoteLValueLocation(Info, Base);
2141   }
2142 
2143   return true;
2144 }
2145 
2146 /// Member pointers are constant expressions unless they point to a
2147 /// non-virtual dllimport member function.
2148 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2149                                                  SourceLocation Loc,
2150                                                  QualType Type,
2151                                                  const APValue &Value,
2152                                                  Expr::ConstExprUsage Usage) {
2153   const ValueDecl *Member = Value.getMemberPointerDecl();
2154   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2155   if (!FD)
2156     return true;
2157   if (FD->isConsteval()) {
2158     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2159     Info.Note(FD->getLocation(), diag::note_declared_at);
2160     return false;
2161   }
2162   return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
2163          !FD->hasAttr<DLLImportAttr>();
2164 }
2165 
2166 /// Check that this core constant expression is of literal type, and if not,
2167 /// produce an appropriate diagnostic.
2168 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2169                              const LValue *This = nullptr) {
2170   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
2171     return true;
2172 
2173   // C++1y: A constant initializer for an object o [...] may also invoke
2174   // constexpr constructors for o and its subobjects even if those objects
2175   // are of non-literal class types.
2176   //
2177   // C++11 missed this detail for aggregates, so classes like this:
2178   //   struct foo_t { union { int i; volatile int j; } u; };
2179   // are not (obviously) initializable like so:
2180   //   __attribute__((__require_constant_initialization__))
2181   //   static const foo_t x = {{0}};
2182   // because "i" is a subobject with non-literal initialization (due to the
2183   // volatile member of the union). See:
2184   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2185   // Therefore, we use the C++1y behavior.
2186   if (This && Info.EvaluatingDecl == This->getLValueBase())
2187     return true;
2188 
2189   // Prvalue constant expressions must be of literal types.
2190   if (Info.getLangOpts().CPlusPlus11)
2191     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2192       << E->getType();
2193   else
2194     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2195   return false;
2196 }
2197 
2198 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2199                                   EvalInfo &Info, SourceLocation DiagLoc,
2200                                   QualType Type, const APValue &Value,
2201                                   Expr::ConstExprUsage Usage,
2202                                   SourceLocation SubobjectLoc,
2203                                   CheckedTemporaries &CheckedTemps) {
2204   if (!Value.hasValue()) {
2205     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2206       << true << Type;
2207     if (SubobjectLoc.isValid())
2208       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2209     return false;
2210   }
2211 
2212   // We allow _Atomic(T) to be initialized from anything that T can be
2213   // initialized from.
2214   if (const AtomicType *AT = Type->getAs<AtomicType>())
2215     Type = AT->getValueType();
2216 
2217   // Core issue 1454: For a literal constant expression of array or class type,
2218   // each subobject of its value shall have been initialized by a constant
2219   // expression.
2220   if (Value.isArray()) {
2221     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2222     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2223       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2224                                  Value.getArrayInitializedElt(I), Usage,
2225                                  SubobjectLoc, CheckedTemps))
2226         return false;
2227     }
2228     if (!Value.hasArrayFiller())
2229       return true;
2230     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2231                                  Value.getArrayFiller(), Usage, SubobjectLoc,
2232                                  CheckedTemps);
2233   }
2234   if (Value.isUnion() && Value.getUnionField()) {
2235     return CheckEvaluationResult(
2236         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2237         Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(),
2238         CheckedTemps);
2239   }
2240   if (Value.isStruct()) {
2241     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2242     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2243       unsigned BaseIndex = 0;
2244       for (const CXXBaseSpecifier &BS : CD->bases()) {
2245         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2246                                    Value.getStructBase(BaseIndex), Usage,
2247                                    BS.getBeginLoc(), CheckedTemps))
2248           return false;
2249         ++BaseIndex;
2250       }
2251     }
2252     for (const auto *I : RD->fields()) {
2253       if (I->isUnnamedBitfield())
2254         continue;
2255 
2256       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2257                                  Value.getStructField(I->getFieldIndex()),
2258                                  Usage, I->getLocation(), CheckedTemps))
2259         return false;
2260     }
2261   }
2262 
2263   if (Value.isLValue() &&
2264       CERK == CheckEvaluationResultKind::ConstantExpression) {
2265     LValue LVal;
2266     LVal.setFrom(Info.Ctx, Value);
2267     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage,
2268                                          CheckedTemps);
2269   }
2270 
2271   if (Value.isMemberPointer() &&
2272       CERK == CheckEvaluationResultKind::ConstantExpression)
2273     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
2274 
2275   // Everything else is fine.
2276   return true;
2277 }
2278 
2279 /// Check that this core constant expression value is a valid value for a
2280 /// constant expression. If not, report an appropriate diagnostic. Does not
2281 /// check that the expression is of literal type.
2282 static bool
2283 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2284                         const APValue &Value,
2285                         Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
2286   CheckedTemporaries CheckedTemps;
2287   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2288                                Info, DiagLoc, Type, Value, Usage,
2289                                SourceLocation(), CheckedTemps);
2290 }
2291 
2292 /// Check that this evaluated value is fully-initialized and can be loaded by
2293 /// an lvalue-to-rvalue conversion.
2294 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2295                                   QualType Type, const APValue &Value) {
2296   CheckedTemporaries CheckedTemps;
2297   return CheckEvaluationResult(
2298       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2299       Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps);
2300 }
2301 
2302 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2303 /// "the allocated storage is deallocated within the evaluation".
2304 static bool CheckMemoryLeaks(EvalInfo &Info) {
2305   if (!Info.HeapAllocs.empty()) {
2306     // We can still fold to a constant despite a compile-time memory leak,
2307     // so long as the heap allocation isn't referenced in the result (we check
2308     // that in CheckConstantExpression).
2309     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2310                  diag::note_constexpr_memory_leak)
2311         << unsigned(Info.HeapAllocs.size() - 1);
2312   }
2313   return true;
2314 }
2315 
2316 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2317   // A null base expression indicates a null pointer.  These are always
2318   // evaluatable, and they are false unless the offset is zero.
2319   if (!Value.getLValueBase()) {
2320     Result = !Value.getLValueOffset().isZero();
2321     return true;
2322   }
2323 
2324   // We have a non-null base.  These are generally known to be true, but if it's
2325   // a weak declaration it can be null at runtime.
2326   Result = true;
2327   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2328   return !Decl || !Decl->isWeak();
2329 }
2330 
2331 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2332   switch (Val.getKind()) {
2333   case APValue::None:
2334   case APValue::Indeterminate:
2335     return false;
2336   case APValue::Int:
2337     Result = Val.getInt().getBoolValue();
2338     return true;
2339   case APValue::FixedPoint:
2340     Result = Val.getFixedPoint().getBoolValue();
2341     return true;
2342   case APValue::Float:
2343     Result = !Val.getFloat().isZero();
2344     return true;
2345   case APValue::ComplexInt:
2346     Result = Val.getComplexIntReal().getBoolValue() ||
2347              Val.getComplexIntImag().getBoolValue();
2348     return true;
2349   case APValue::ComplexFloat:
2350     Result = !Val.getComplexFloatReal().isZero() ||
2351              !Val.getComplexFloatImag().isZero();
2352     return true;
2353   case APValue::LValue:
2354     return EvalPointerValueAsBool(Val, Result);
2355   case APValue::MemberPointer:
2356     Result = Val.getMemberPointerDecl();
2357     return true;
2358   case APValue::Vector:
2359   case APValue::Array:
2360   case APValue::Struct:
2361   case APValue::Union:
2362   case APValue::AddrLabelDiff:
2363     return false;
2364   }
2365 
2366   llvm_unreachable("unknown APValue kind");
2367 }
2368 
2369 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2370                                        EvalInfo &Info) {
2371   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2372   APValue Val;
2373   if (!Evaluate(Val, Info, E))
2374     return false;
2375   return HandleConversionToBool(Val, Result);
2376 }
2377 
2378 template<typename T>
2379 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2380                            const T &SrcValue, QualType DestType) {
2381   Info.CCEDiag(E, diag::note_constexpr_overflow)
2382     << SrcValue << DestType;
2383   return Info.noteUndefinedBehavior();
2384 }
2385 
2386 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2387                                  QualType SrcType, const APFloat &Value,
2388                                  QualType DestType, APSInt &Result) {
2389   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2390   // Determine whether we are converting to unsigned or signed.
2391   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2392 
2393   Result = APSInt(DestWidth, !DestSigned);
2394   bool ignored;
2395   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2396       & APFloat::opInvalidOp)
2397     return HandleOverflow(Info, E, Value, DestType);
2398   return true;
2399 }
2400 
2401 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2402                                    QualType SrcType, QualType DestType,
2403                                    APFloat &Result) {
2404   APFloat Value = Result;
2405   bool ignored;
2406   Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2407                  APFloat::rmNearestTiesToEven, &ignored);
2408   return true;
2409 }
2410 
2411 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2412                                  QualType DestType, QualType SrcType,
2413                                  const APSInt &Value) {
2414   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2415   // Figure out if this is a truncate, extend or noop cast.
2416   // If the input is signed, do a sign extend, noop, or truncate.
2417   APSInt Result = Value.extOrTrunc(DestWidth);
2418   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2419   if (DestType->isBooleanType())
2420     Result = Value.getBoolValue();
2421   return Result;
2422 }
2423 
2424 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2425                                  QualType SrcType, const APSInt &Value,
2426                                  QualType DestType, APFloat &Result) {
2427   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2428   Result.convertFromAPInt(Value, Value.isSigned(),
2429                           APFloat::rmNearestTiesToEven);
2430   return true;
2431 }
2432 
2433 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2434                                   APValue &Value, const FieldDecl *FD) {
2435   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2436 
2437   if (!Value.isInt()) {
2438     // Trying to store a pointer-cast-to-integer into a bitfield.
2439     // FIXME: In this case, we should provide the diagnostic for casting
2440     // a pointer to an integer.
2441     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2442     Info.FFDiag(E);
2443     return false;
2444   }
2445 
2446   APSInt &Int = Value.getInt();
2447   unsigned OldBitWidth = Int.getBitWidth();
2448   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2449   if (NewBitWidth < OldBitWidth)
2450     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2451   return true;
2452 }
2453 
2454 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2455                                   llvm::APInt &Res) {
2456   APValue SVal;
2457   if (!Evaluate(SVal, Info, E))
2458     return false;
2459   if (SVal.isInt()) {
2460     Res = SVal.getInt();
2461     return true;
2462   }
2463   if (SVal.isFloat()) {
2464     Res = SVal.getFloat().bitcastToAPInt();
2465     return true;
2466   }
2467   if (SVal.isVector()) {
2468     QualType VecTy = E->getType();
2469     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2470     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2471     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2472     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2473     Res = llvm::APInt::getNullValue(VecSize);
2474     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2475       APValue &Elt = SVal.getVectorElt(i);
2476       llvm::APInt EltAsInt;
2477       if (Elt.isInt()) {
2478         EltAsInt = Elt.getInt();
2479       } else if (Elt.isFloat()) {
2480         EltAsInt = Elt.getFloat().bitcastToAPInt();
2481       } else {
2482         // Don't try to handle vectors of anything other than int or float
2483         // (not sure if it's possible to hit this case).
2484         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2485         return false;
2486       }
2487       unsigned BaseEltSize = EltAsInt.getBitWidth();
2488       if (BigEndian)
2489         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2490       else
2491         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2492     }
2493     return true;
2494   }
2495   // Give up if the input isn't an int, float, or vector.  For example, we
2496   // reject "(v4i16)(intptr_t)&a".
2497   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2498   return false;
2499 }
2500 
2501 /// Perform the given integer operation, which is known to need at most BitWidth
2502 /// bits, and check for overflow in the original type (if that type was not an
2503 /// unsigned type).
2504 template<typename Operation>
2505 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2506                                  const APSInt &LHS, const APSInt &RHS,
2507                                  unsigned BitWidth, Operation Op,
2508                                  APSInt &Result) {
2509   if (LHS.isUnsigned()) {
2510     Result = Op(LHS, RHS);
2511     return true;
2512   }
2513 
2514   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2515   Result = Value.trunc(LHS.getBitWidth());
2516   if (Result.extend(BitWidth) != Value) {
2517     if (Info.checkingForUndefinedBehavior())
2518       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2519                                        diag::warn_integer_constant_overflow)
2520           << Result.toString(10) << E->getType();
2521     else
2522       return HandleOverflow(Info, E, Value, E->getType());
2523   }
2524   return true;
2525 }
2526 
2527 /// Perform the given binary integer operation.
2528 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2529                               BinaryOperatorKind Opcode, APSInt RHS,
2530                               APSInt &Result) {
2531   switch (Opcode) {
2532   default:
2533     Info.FFDiag(E);
2534     return false;
2535   case BO_Mul:
2536     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2537                                 std::multiplies<APSInt>(), Result);
2538   case BO_Add:
2539     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2540                                 std::plus<APSInt>(), Result);
2541   case BO_Sub:
2542     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2543                                 std::minus<APSInt>(), Result);
2544   case BO_And: Result = LHS & RHS; return true;
2545   case BO_Xor: Result = LHS ^ RHS; return true;
2546   case BO_Or:  Result = LHS | RHS; return true;
2547   case BO_Div:
2548   case BO_Rem:
2549     if (RHS == 0) {
2550       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2551       return false;
2552     }
2553     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2554     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2555     // this operation and gives the two's complement result.
2556     if (RHS.isNegative() && RHS.isAllOnesValue() &&
2557         LHS.isSigned() && LHS.isMinSignedValue())
2558       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2559                             E->getType());
2560     return true;
2561   case BO_Shl: {
2562     if (Info.getLangOpts().OpenCL)
2563       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2564       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2565                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2566                     RHS.isUnsigned());
2567     else if (RHS.isSigned() && RHS.isNegative()) {
2568       // During constant-folding, a negative shift is an opposite shift. Such
2569       // a shift is not a constant expression.
2570       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2571       RHS = -RHS;
2572       goto shift_right;
2573     }
2574   shift_left:
2575     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2576     // the shifted type.
2577     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2578     if (SA != RHS) {
2579       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2580         << RHS << E->getType() << LHS.getBitWidth();
2581     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) {
2582       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2583       // operand, and must not overflow the corresponding unsigned type.
2584       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2585       // E1 x 2^E2 module 2^N.
2586       if (LHS.isNegative())
2587         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2588       else if (LHS.countLeadingZeros() < SA)
2589         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2590     }
2591     Result = LHS << SA;
2592     return true;
2593   }
2594   case BO_Shr: {
2595     if (Info.getLangOpts().OpenCL)
2596       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2597       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2598                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2599                     RHS.isUnsigned());
2600     else if (RHS.isSigned() && RHS.isNegative()) {
2601       // During constant-folding, a negative shift is an opposite shift. Such a
2602       // shift is not a constant expression.
2603       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2604       RHS = -RHS;
2605       goto shift_left;
2606     }
2607   shift_right:
2608     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2609     // shifted type.
2610     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2611     if (SA != RHS)
2612       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2613         << RHS << E->getType() << LHS.getBitWidth();
2614     Result = LHS >> SA;
2615     return true;
2616   }
2617 
2618   case BO_LT: Result = LHS < RHS; return true;
2619   case BO_GT: Result = LHS > RHS; return true;
2620   case BO_LE: Result = LHS <= RHS; return true;
2621   case BO_GE: Result = LHS >= RHS; return true;
2622   case BO_EQ: Result = LHS == RHS; return true;
2623   case BO_NE: Result = LHS != RHS; return true;
2624   case BO_Cmp:
2625     llvm_unreachable("BO_Cmp should be handled elsewhere");
2626   }
2627 }
2628 
2629 /// Perform the given binary floating-point operation, in-place, on LHS.
2630 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2631                                   APFloat &LHS, BinaryOperatorKind Opcode,
2632                                   const APFloat &RHS) {
2633   switch (Opcode) {
2634   default:
2635     Info.FFDiag(E);
2636     return false;
2637   case BO_Mul:
2638     LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2639     break;
2640   case BO_Add:
2641     LHS.add(RHS, APFloat::rmNearestTiesToEven);
2642     break;
2643   case BO_Sub:
2644     LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2645     break;
2646   case BO_Div:
2647     // [expr.mul]p4:
2648     //   If the second operand of / or % is zero the behavior is undefined.
2649     if (RHS.isZero())
2650       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2651     LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2652     break;
2653   }
2654 
2655   // [expr.pre]p4:
2656   //   If during the evaluation of an expression, the result is not
2657   //   mathematically defined [...], the behavior is undefined.
2658   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2659   if (LHS.isNaN()) {
2660     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2661     return Info.noteUndefinedBehavior();
2662   }
2663   return true;
2664 }
2665 
2666 /// Cast an lvalue referring to a base subobject to a derived class, by
2667 /// truncating the lvalue's path to the given length.
2668 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2669                                const RecordDecl *TruncatedType,
2670                                unsigned TruncatedElements) {
2671   SubobjectDesignator &D = Result.Designator;
2672 
2673   // Check we actually point to a derived class object.
2674   if (TruncatedElements == D.Entries.size())
2675     return true;
2676   assert(TruncatedElements >= D.MostDerivedPathLength &&
2677          "not casting to a derived class");
2678   if (!Result.checkSubobject(Info, E, CSK_Derived))
2679     return false;
2680 
2681   // Truncate the path to the subobject, and remove any derived-to-base offsets.
2682   const RecordDecl *RD = TruncatedType;
2683   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2684     if (RD->isInvalidDecl()) return false;
2685     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2686     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2687     if (isVirtualBaseClass(D.Entries[I]))
2688       Result.Offset -= Layout.getVBaseClassOffset(Base);
2689     else
2690       Result.Offset -= Layout.getBaseClassOffset(Base);
2691     RD = Base;
2692   }
2693   D.Entries.resize(TruncatedElements);
2694   return true;
2695 }
2696 
2697 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2698                                    const CXXRecordDecl *Derived,
2699                                    const CXXRecordDecl *Base,
2700                                    const ASTRecordLayout *RL = nullptr) {
2701   if (!RL) {
2702     if (Derived->isInvalidDecl()) return false;
2703     RL = &Info.Ctx.getASTRecordLayout(Derived);
2704   }
2705 
2706   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2707   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2708   return true;
2709 }
2710 
2711 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2712                              const CXXRecordDecl *DerivedDecl,
2713                              const CXXBaseSpecifier *Base) {
2714   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2715 
2716   if (!Base->isVirtual())
2717     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2718 
2719   SubobjectDesignator &D = Obj.Designator;
2720   if (D.Invalid)
2721     return false;
2722 
2723   // Extract most-derived object and corresponding type.
2724   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2725   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2726     return false;
2727 
2728   // Find the virtual base class.
2729   if (DerivedDecl->isInvalidDecl()) return false;
2730   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2731   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2732   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2733   return true;
2734 }
2735 
2736 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2737                                  QualType Type, LValue &Result) {
2738   for (CastExpr::path_const_iterator PathI = E->path_begin(),
2739                                      PathE = E->path_end();
2740        PathI != PathE; ++PathI) {
2741     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2742                           *PathI))
2743       return false;
2744     Type = (*PathI)->getType();
2745   }
2746   return true;
2747 }
2748 
2749 /// Cast an lvalue referring to a derived class to a known base subobject.
2750 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2751                             const CXXRecordDecl *DerivedRD,
2752                             const CXXRecordDecl *BaseRD) {
2753   CXXBasePaths Paths(/*FindAmbiguities=*/false,
2754                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
2755   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2756     llvm_unreachable("Class must be derived from the passed in base class!");
2757 
2758   for (CXXBasePathElement &Elem : Paths.front())
2759     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2760       return false;
2761   return true;
2762 }
2763 
2764 /// Update LVal to refer to the given field, which must be a member of the type
2765 /// currently described by LVal.
2766 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2767                                const FieldDecl *FD,
2768                                const ASTRecordLayout *RL = nullptr) {
2769   if (!RL) {
2770     if (FD->getParent()->isInvalidDecl()) return false;
2771     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2772   }
2773 
2774   unsigned I = FD->getFieldIndex();
2775   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2776   LVal.addDecl(Info, E, FD);
2777   return true;
2778 }
2779 
2780 /// Update LVal to refer to the given indirect field.
2781 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2782                                        LValue &LVal,
2783                                        const IndirectFieldDecl *IFD) {
2784   for (const auto *C : IFD->chain())
2785     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2786       return false;
2787   return true;
2788 }
2789 
2790 /// Get the size of the given type in char units.
2791 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2792                          QualType Type, CharUnits &Size) {
2793   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2794   // extension.
2795   if (Type->isVoidType() || Type->isFunctionType()) {
2796     Size = CharUnits::One();
2797     return true;
2798   }
2799 
2800   if (Type->isDependentType()) {
2801     Info.FFDiag(Loc);
2802     return false;
2803   }
2804 
2805   if (!Type->isConstantSizeType()) {
2806     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2807     // FIXME: Better diagnostic.
2808     Info.FFDiag(Loc);
2809     return false;
2810   }
2811 
2812   Size = Info.Ctx.getTypeSizeInChars(Type);
2813   return true;
2814 }
2815 
2816 /// Update a pointer value to model pointer arithmetic.
2817 /// \param Info - Information about the ongoing evaluation.
2818 /// \param E - The expression being evaluated, for diagnostic purposes.
2819 /// \param LVal - The pointer value to be updated.
2820 /// \param EltTy - The pointee type represented by LVal.
2821 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2822 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2823                                         LValue &LVal, QualType EltTy,
2824                                         APSInt Adjustment) {
2825   CharUnits SizeOfPointee;
2826   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2827     return false;
2828 
2829   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2830   return true;
2831 }
2832 
2833 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2834                                         LValue &LVal, QualType EltTy,
2835                                         int64_t Adjustment) {
2836   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2837                                      APSInt::get(Adjustment));
2838 }
2839 
2840 /// Update an lvalue to refer to a component of a complex number.
2841 /// \param Info - Information about the ongoing evaluation.
2842 /// \param LVal - The lvalue to be updated.
2843 /// \param EltTy - The complex number's component type.
2844 /// \param Imag - False for the real component, true for the imaginary.
2845 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2846                                        LValue &LVal, QualType EltTy,
2847                                        bool Imag) {
2848   if (Imag) {
2849     CharUnits SizeOfComponent;
2850     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2851       return false;
2852     LVal.Offset += SizeOfComponent;
2853   }
2854   LVal.addComplex(Info, E, EltTy, Imag);
2855   return true;
2856 }
2857 
2858 /// Try to evaluate the initializer for a variable declaration.
2859 ///
2860 /// \param Info   Information about the ongoing evaluation.
2861 /// \param E      An expression to be used when printing diagnostics.
2862 /// \param VD     The variable whose initializer should be obtained.
2863 /// \param Frame  The frame in which the variable was created. Must be null
2864 ///               if this variable is not local to the evaluation.
2865 /// \param Result Filled in with a pointer to the value of the variable.
2866 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2867                                 const VarDecl *VD, CallStackFrame *Frame,
2868                                 APValue *&Result, const LValue *LVal) {
2869 
2870   // If this is a parameter to an active constexpr function call, perform
2871   // argument substitution.
2872   if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2873     // Assume arguments of a potential constant expression are unknown
2874     // constant expressions.
2875     if (Info.checkingPotentialConstantExpression())
2876       return false;
2877     if (!Frame || !Frame->Arguments) {
2878       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2879       return false;
2880     }
2881     Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2882     return true;
2883   }
2884 
2885   // If this is a local variable, dig out its value.
2886   if (Frame) {
2887     Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2888                   : Frame->getCurrentTemporary(VD);
2889     if (!Result) {
2890       // Assume variables referenced within a lambda's call operator that were
2891       // not declared within the call operator are captures and during checking
2892       // of a potential constant expression, assume they are unknown constant
2893       // expressions.
2894       assert(isLambdaCallOperator(Frame->Callee) &&
2895              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2896              "missing value for local variable");
2897       if (Info.checkingPotentialConstantExpression())
2898         return false;
2899       // FIXME: implement capture evaluation during constant expr evaluation.
2900       Info.FFDiag(E->getBeginLoc(),
2901                   diag::note_unimplemented_constexpr_lambda_feature_ast)
2902           << "captures not currently allowed";
2903       return false;
2904     }
2905     return true;
2906   }
2907 
2908   // Dig out the initializer, and use the declaration which it's attached to.
2909   const Expr *Init = VD->getAnyInitializer(VD);
2910   if (!Init || Init->isValueDependent()) {
2911     // If we're checking a potential constant expression, the variable could be
2912     // initialized later.
2913     if (!Info.checkingPotentialConstantExpression())
2914       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2915     return false;
2916   }
2917 
2918   // If we're currently evaluating the initializer of this declaration, use that
2919   // in-flight value.
2920   if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2921     Result = Info.EvaluatingDeclValue;
2922     return true;
2923   }
2924 
2925   // Never evaluate the initializer of a weak variable. We can't be sure that
2926   // this is the definition which will be used.
2927   if (VD->isWeak()) {
2928     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2929     return false;
2930   }
2931 
2932   // Check that we can fold the initializer. In C++, we will have already done
2933   // this in the cases where it matters for conformance.
2934   SmallVector<PartialDiagnosticAt, 8> Notes;
2935   if (!VD->evaluateValue(Notes)) {
2936     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2937               Notes.size() + 1) << VD;
2938     Info.Note(VD->getLocation(), diag::note_declared_at);
2939     Info.addNotes(Notes);
2940     return false;
2941   } else if (!VD->checkInitIsICE()) {
2942     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2943                  Notes.size() + 1) << VD;
2944     Info.Note(VD->getLocation(), diag::note_declared_at);
2945     Info.addNotes(Notes);
2946   }
2947 
2948   Result = VD->getEvaluatedValue();
2949   return true;
2950 }
2951 
2952 static bool IsConstNonVolatile(QualType T) {
2953   Qualifiers Quals = T.getQualifiers();
2954   return Quals.hasConst() && !Quals.hasVolatile();
2955 }
2956 
2957 /// Get the base index of the given base class within an APValue representing
2958 /// the given derived class.
2959 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2960                              const CXXRecordDecl *Base) {
2961   Base = Base->getCanonicalDecl();
2962   unsigned Index = 0;
2963   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2964          E = Derived->bases_end(); I != E; ++I, ++Index) {
2965     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2966       return Index;
2967   }
2968 
2969   llvm_unreachable("base class missing from derived class's bases list");
2970 }
2971 
2972 /// Extract the value of a character from a string literal.
2973 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2974                                             uint64_t Index) {
2975   assert(!isa<SourceLocExpr>(Lit) &&
2976          "SourceLocExpr should have already been converted to a StringLiteral");
2977 
2978   // FIXME: Support MakeStringConstant
2979   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2980     std::string Str;
2981     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2982     assert(Index <= Str.size() && "Index too large");
2983     return APSInt::getUnsigned(Str.c_str()[Index]);
2984   }
2985 
2986   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2987     Lit = PE->getFunctionName();
2988   const StringLiteral *S = cast<StringLiteral>(Lit);
2989   const ConstantArrayType *CAT =
2990       Info.Ctx.getAsConstantArrayType(S->getType());
2991   assert(CAT && "string literal isn't an array");
2992   QualType CharType = CAT->getElementType();
2993   assert(CharType->isIntegerType() && "unexpected character type");
2994 
2995   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2996                CharType->isUnsignedIntegerType());
2997   if (Index < S->getLength())
2998     Value = S->getCodeUnit(Index);
2999   return Value;
3000 }
3001 
3002 // Expand a string literal into an array of characters.
3003 //
3004 // FIXME: This is inefficient; we should probably introduce something similar
3005 // to the LLVM ConstantDataArray to make this cheaper.
3006 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3007                                 APValue &Result,
3008                                 QualType AllocType = QualType()) {
3009   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3010       AllocType.isNull() ? S->getType() : AllocType);
3011   assert(CAT && "string literal isn't an array");
3012   QualType CharType = CAT->getElementType();
3013   assert(CharType->isIntegerType() && "unexpected character type");
3014 
3015   unsigned Elts = CAT->getSize().getZExtValue();
3016   Result = APValue(APValue::UninitArray(),
3017                    std::min(S->getLength(), Elts), Elts);
3018   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3019                CharType->isUnsignedIntegerType());
3020   if (Result.hasArrayFiller())
3021     Result.getArrayFiller() = APValue(Value);
3022   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3023     Value = S->getCodeUnit(I);
3024     Result.getArrayInitializedElt(I) = APValue(Value);
3025   }
3026 }
3027 
3028 // Expand an array so that it has more than Index filled elements.
3029 static void expandArray(APValue &Array, unsigned Index) {
3030   unsigned Size = Array.getArraySize();
3031   assert(Index < Size);
3032 
3033   // Always at least double the number of elements for which we store a value.
3034   unsigned OldElts = Array.getArrayInitializedElts();
3035   unsigned NewElts = std::max(Index+1, OldElts * 2);
3036   NewElts = std::min(Size, std::max(NewElts, 8u));
3037 
3038   // Copy the data across.
3039   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3040   for (unsigned I = 0; I != OldElts; ++I)
3041     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3042   for (unsigned I = OldElts; I != NewElts; ++I)
3043     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3044   if (NewValue.hasArrayFiller())
3045     NewValue.getArrayFiller() = Array.getArrayFiller();
3046   Array.swap(NewValue);
3047 }
3048 
3049 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3050 /// conversion. If it's of class type, we may assume that the copy operation
3051 /// is trivial. Note that this is never true for a union type with fields
3052 /// (because the copy always "reads" the active member) and always true for
3053 /// a non-class type.
3054 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3055 static bool isReadByLvalueToRvalueConversion(QualType T) {
3056   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3057   return !RD || isReadByLvalueToRvalueConversion(RD);
3058 }
3059 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3060   // FIXME: A trivial copy of a union copies the object representation, even if
3061   // the union is empty.
3062   if (RD->isUnion())
3063     return !RD->field_empty();
3064   if (RD->isEmpty())
3065     return false;
3066 
3067   for (auto *Field : RD->fields())
3068     if (!Field->isUnnamedBitfield() &&
3069         isReadByLvalueToRvalueConversion(Field->getType()))
3070       return true;
3071 
3072   for (auto &BaseSpec : RD->bases())
3073     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3074       return true;
3075 
3076   return false;
3077 }
3078 
3079 /// Diagnose an attempt to read from any unreadable field within the specified
3080 /// type, which might be a class type.
3081 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3082                                   QualType T) {
3083   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3084   if (!RD)
3085     return false;
3086 
3087   if (!RD->hasMutableFields())
3088     return false;
3089 
3090   for (auto *Field : RD->fields()) {
3091     // If we're actually going to read this field in some way, then it can't
3092     // be mutable. If we're in a union, then assigning to a mutable field
3093     // (even an empty one) can change the active member, so that's not OK.
3094     // FIXME: Add core issue number for the union case.
3095     if (Field->isMutable() &&
3096         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3097       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3098       Info.Note(Field->getLocation(), diag::note_declared_at);
3099       return true;
3100     }
3101 
3102     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3103       return true;
3104   }
3105 
3106   for (auto &BaseSpec : RD->bases())
3107     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3108       return true;
3109 
3110   // All mutable fields were empty, and thus not actually read.
3111   return false;
3112 }
3113 
3114 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3115                                         APValue::LValueBase Base,
3116                                         bool MutableSubobject = false) {
3117   // A temporary we created.
3118   if (Base.getCallIndex())
3119     return true;
3120 
3121   auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3122   if (!Evaluating)
3123     return false;
3124 
3125   auto *BaseD = Base.dyn_cast<const ValueDecl*>();
3126 
3127   switch (Info.IsEvaluatingDecl) {
3128   case EvalInfo::EvaluatingDeclKind::None:
3129     return false;
3130 
3131   case EvalInfo::EvaluatingDeclKind::Ctor:
3132     // The variable whose initializer we're evaluating.
3133     if (BaseD)
3134       return declaresSameEntity(Evaluating, BaseD);
3135 
3136     // A temporary lifetime-extended by the variable whose initializer we're
3137     // evaluating.
3138     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3139       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3140         return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating);
3141     return false;
3142 
3143   case EvalInfo::EvaluatingDeclKind::Dtor:
3144     // C++2a [expr.const]p6:
3145     //   [during constant destruction] the lifetime of a and its non-mutable
3146     //   subobjects (but not its mutable subobjects) [are] considered to start
3147     //   within e.
3148     //
3149     // FIXME: We can meaningfully extend this to cover non-const objects, but
3150     // we will need special handling: we should be able to access only
3151     // subobjects of such objects that are themselves declared const.
3152     if (!BaseD ||
3153         !(BaseD->getType().isConstQualified() ||
3154           BaseD->getType()->isReferenceType()) ||
3155         MutableSubobject)
3156       return false;
3157     return declaresSameEntity(Evaluating, BaseD);
3158   }
3159 
3160   llvm_unreachable("unknown evaluating decl kind");
3161 }
3162 
3163 namespace {
3164 /// A handle to a complete object (an object that is not a subobject of
3165 /// another object).
3166 struct CompleteObject {
3167   /// The identity of the object.
3168   APValue::LValueBase Base;
3169   /// The value of the complete object.
3170   APValue *Value;
3171   /// The type of the complete object.
3172   QualType Type;
3173 
3174   CompleteObject() : Value(nullptr) {}
3175   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3176       : Base(Base), Value(Value), Type(Type) {}
3177 
3178   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3179     // If this isn't a "real" access (eg, if it's just accessing the type
3180     // info), allow it. We assume the type doesn't change dynamically for
3181     // subobjects of constexpr objects (even though we'd hit UB here if it
3182     // did). FIXME: Is this right?
3183     if (!isAnyAccess(AK))
3184       return true;
3185 
3186     // In C++14 onwards, it is permitted to read a mutable member whose
3187     // lifetime began within the evaluation.
3188     // FIXME: Should we also allow this in C++11?
3189     if (!Info.getLangOpts().CPlusPlus14)
3190       return false;
3191     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3192   }
3193 
3194   explicit operator bool() const { return !Type.isNull(); }
3195 };
3196 } // end anonymous namespace
3197 
3198 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3199                                  bool IsMutable = false) {
3200   // C++ [basic.type.qualifier]p1:
3201   // - A const object is an object of type const T or a non-mutable subobject
3202   //   of a const object.
3203   if (ObjType.isConstQualified() && !IsMutable)
3204     SubobjType.addConst();
3205   // - A volatile object is an object of type const T or a subobject of a
3206   //   volatile object.
3207   if (ObjType.isVolatileQualified())
3208     SubobjType.addVolatile();
3209   return SubobjType;
3210 }
3211 
3212 /// Find the designated sub-object of an rvalue.
3213 template<typename SubobjectHandler>
3214 typename SubobjectHandler::result_type
3215 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3216               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3217   if (Sub.Invalid)
3218     // A diagnostic will have already been produced.
3219     return handler.failed();
3220   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3221     if (Info.getLangOpts().CPlusPlus11)
3222       Info.FFDiag(E, Sub.isOnePastTheEnd()
3223                          ? diag::note_constexpr_access_past_end
3224                          : diag::note_constexpr_access_unsized_array)
3225           << handler.AccessKind;
3226     else
3227       Info.FFDiag(E);
3228     return handler.failed();
3229   }
3230 
3231   APValue *O = Obj.Value;
3232   QualType ObjType = Obj.Type;
3233   const FieldDecl *LastField = nullptr;
3234   const FieldDecl *VolatileField = nullptr;
3235 
3236   // Walk the designator's path to find the subobject.
3237   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3238     // Reading an indeterminate value is undefined, but assigning over one is OK.
3239     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3240         (O->isIndeterminate() &&
3241          !isValidIndeterminateAccess(handler.AccessKind))) {
3242       if (!Info.checkingPotentialConstantExpression())
3243         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3244             << handler.AccessKind << O->isIndeterminate();
3245       return handler.failed();
3246     }
3247 
3248     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3249     //    const and volatile semantics are not applied on an object under
3250     //    {con,de}struction.
3251     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3252         ObjType->isRecordType() &&
3253         Info.isEvaluatingCtorDtor(
3254             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3255                                          Sub.Entries.begin() + I)) !=
3256                           ConstructionPhase::None) {
3257       ObjType = Info.Ctx.getCanonicalType(ObjType);
3258       ObjType.removeLocalConst();
3259       ObjType.removeLocalVolatile();
3260     }
3261 
3262     // If this is our last pass, check that the final object type is OK.
3263     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3264       // Accesses to volatile objects are prohibited.
3265       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3266         if (Info.getLangOpts().CPlusPlus) {
3267           int DiagKind;
3268           SourceLocation Loc;
3269           const NamedDecl *Decl = nullptr;
3270           if (VolatileField) {
3271             DiagKind = 2;
3272             Loc = VolatileField->getLocation();
3273             Decl = VolatileField;
3274           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3275             DiagKind = 1;
3276             Loc = VD->getLocation();
3277             Decl = VD;
3278           } else {
3279             DiagKind = 0;
3280             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3281               Loc = E->getExprLoc();
3282           }
3283           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3284               << handler.AccessKind << DiagKind << Decl;
3285           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3286         } else {
3287           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3288         }
3289         return handler.failed();
3290       }
3291 
3292       // If we are reading an object of class type, there may still be more
3293       // things we need to check: if there are any mutable subobjects, we
3294       // cannot perform this read. (This only happens when performing a trivial
3295       // copy or assignment.)
3296       if (ObjType->isRecordType() &&
3297           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3298           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3299         return handler.failed();
3300     }
3301 
3302     if (I == N) {
3303       if (!handler.found(*O, ObjType))
3304         return false;
3305 
3306       // If we modified a bit-field, truncate it to the right width.
3307       if (isModification(handler.AccessKind) &&
3308           LastField && LastField->isBitField() &&
3309           !truncateBitfieldValue(Info, E, *O, LastField))
3310         return false;
3311 
3312       return true;
3313     }
3314 
3315     LastField = nullptr;
3316     if (ObjType->isArrayType()) {
3317       // Next subobject is an array element.
3318       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3319       assert(CAT && "vla in literal type?");
3320       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3321       if (CAT->getSize().ule(Index)) {
3322         // Note, it should not be possible to form a pointer with a valid
3323         // designator which points more than one past the end of the array.
3324         if (Info.getLangOpts().CPlusPlus11)
3325           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3326             << handler.AccessKind;
3327         else
3328           Info.FFDiag(E);
3329         return handler.failed();
3330       }
3331 
3332       ObjType = CAT->getElementType();
3333 
3334       if (O->getArrayInitializedElts() > Index)
3335         O = &O->getArrayInitializedElt(Index);
3336       else if (!isRead(handler.AccessKind)) {
3337         expandArray(*O, Index);
3338         O = &O->getArrayInitializedElt(Index);
3339       } else
3340         O = &O->getArrayFiller();
3341     } else if (ObjType->isAnyComplexType()) {
3342       // Next subobject is a complex number.
3343       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3344       if (Index > 1) {
3345         if (Info.getLangOpts().CPlusPlus11)
3346           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3347             << handler.AccessKind;
3348         else
3349           Info.FFDiag(E);
3350         return handler.failed();
3351       }
3352 
3353       ObjType = getSubobjectType(
3354           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3355 
3356       assert(I == N - 1 && "extracting subobject of scalar?");
3357       if (O->isComplexInt()) {
3358         return handler.found(Index ? O->getComplexIntImag()
3359                                    : O->getComplexIntReal(), ObjType);
3360       } else {
3361         assert(O->isComplexFloat());
3362         return handler.found(Index ? O->getComplexFloatImag()
3363                                    : O->getComplexFloatReal(), ObjType);
3364       }
3365     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3366       if (Field->isMutable() &&
3367           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3368         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3369           << handler.AccessKind << Field;
3370         Info.Note(Field->getLocation(), diag::note_declared_at);
3371         return handler.failed();
3372       }
3373 
3374       // Next subobject is a class, struct or union field.
3375       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3376       if (RD->isUnion()) {
3377         const FieldDecl *UnionField = O->getUnionField();
3378         if (!UnionField ||
3379             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3380           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3381             // Placement new onto an inactive union member makes it active.
3382             O->setUnion(Field, APValue());
3383           } else {
3384             // FIXME: If O->getUnionValue() is absent, report that there's no
3385             // active union member rather than reporting the prior active union
3386             // member. We'll need to fix nullptr_t to not use APValue() as its
3387             // representation first.
3388             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3389                 << handler.AccessKind << Field << !UnionField << UnionField;
3390             return handler.failed();
3391           }
3392         }
3393         O = &O->getUnionValue();
3394       } else
3395         O = &O->getStructField(Field->getFieldIndex());
3396 
3397       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3398       LastField = Field;
3399       if (Field->getType().isVolatileQualified())
3400         VolatileField = Field;
3401     } else {
3402       // Next subobject is a base class.
3403       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3404       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3405       O = &O->getStructBase(getBaseIndex(Derived, Base));
3406 
3407       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3408     }
3409   }
3410 }
3411 
3412 namespace {
3413 struct ExtractSubobjectHandler {
3414   EvalInfo &Info;
3415   const Expr *E;
3416   APValue &Result;
3417   const AccessKinds AccessKind;
3418 
3419   typedef bool result_type;
3420   bool failed() { return false; }
3421   bool found(APValue &Subobj, QualType SubobjType) {
3422     Result = Subobj;
3423     if (AccessKind == AK_ReadObjectRepresentation)
3424       return true;
3425     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3426   }
3427   bool found(APSInt &Value, QualType SubobjType) {
3428     Result = APValue(Value);
3429     return true;
3430   }
3431   bool found(APFloat &Value, QualType SubobjType) {
3432     Result = APValue(Value);
3433     return true;
3434   }
3435 };
3436 } // end anonymous namespace
3437 
3438 /// Extract the designated sub-object of an rvalue.
3439 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3440                              const CompleteObject &Obj,
3441                              const SubobjectDesignator &Sub, APValue &Result,
3442                              AccessKinds AK = AK_Read) {
3443   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3444   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3445   return findSubobject(Info, E, Obj, Sub, Handler);
3446 }
3447 
3448 namespace {
3449 struct ModifySubobjectHandler {
3450   EvalInfo &Info;
3451   APValue &NewVal;
3452   const Expr *E;
3453 
3454   typedef bool result_type;
3455   static const AccessKinds AccessKind = AK_Assign;
3456 
3457   bool checkConst(QualType QT) {
3458     // Assigning to a const object has undefined behavior.
3459     if (QT.isConstQualified()) {
3460       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3461       return false;
3462     }
3463     return true;
3464   }
3465 
3466   bool failed() { return false; }
3467   bool found(APValue &Subobj, QualType SubobjType) {
3468     if (!checkConst(SubobjType))
3469       return false;
3470     // We've been given ownership of NewVal, so just swap it in.
3471     Subobj.swap(NewVal);
3472     return true;
3473   }
3474   bool found(APSInt &Value, QualType SubobjType) {
3475     if (!checkConst(SubobjType))
3476       return false;
3477     if (!NewVal.isInt()) {
3478       // Maybe trying to write a cast pointer value into a complex?
3479       Info.FFDiag(E);
3480       return false;
3481     }
3482     Value = NewVal.getInt();
3483     return true;
3484   }
3485   bool found(APFloat &Value, QualType SubobjType) {
3486     if (!checkConst(SubobjType))
3487       return false;
3488     Value = NewVal.getFloat();
3489     return true;
3490   }
3491 };
3492 } // end anonymous namespace
3493 
3494 const AccessKinds ModifySubobjectHandler::AccessKind;
3495 
3496 /// Update the designated sub-object of an rvalue to the given value.
3497 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3498                             const CompleteObject &Obj,
3499                             const SubobjectDesignator &Sub,
3500                             APValue &NewVal) {
3501   ModifySubobjectHandler Handler = { Info, NewVal, E };
3502   return findSubobject(Info, E, Obj, Sub, Handler);
3503 }
3504 
3505 /// Find the position where two subobject designators diverge, or equivalently
3506 /// the length of the common initial subsequence.
3507 static unsigned FindDesignatorMismatch(QualType ObjType,
3508                                        const SubobjectDesignator &A,
3509                                        const SubobjectDesignator &B,
3510                                        bool &WasArrayIndex) {
3511   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3512   for (/**/; I != N; ++I) {
3513     if (!ObjType.isNull() &&
3514         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3515       // Next subobject is an array element.
3516       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3517         WasArrayIndex = true;
3518         return I;
3519       }
3520       if (ObjType->isAnyComplexType())
3521         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3522       else
3523         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3524     } else {
3525       if (A.Entries[I].getAsBaseOrMember() !=
3526           B.Entries[I].getAsBaseOrMember()) {
3527         WasArrayIndex = false;
3528         return I;
3529       }
3530       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3531         // Next subobject is a field.
3532         ObjType = FD->getType();
3533       else
3534         // Next subobject is a base class.
3535         ObjType = QualType();
3536     }
3537   }
3538   WasArrayIndex = false;
3539   return I;
3540 }
3541 
3542 /// Determine whether the given subobject designators refer to elements of the
3543 /// same array object.
3544 static bool AreElementsOfSameArray(QualType ObjType,
3545                                    const SubobjectDesignator &A,
3546                                    const SubobjectDesignator &B) {
3547   if (A.Entries.size() != B.Entries.size())
3548     return false;
3549 
3550   bool IsArray = A.MostDerivedIsArrayElement;
3551   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3552     // A is a subobject of the array element.
3553     return false;
3554 
3555   // If A (and B) designates an array element, the last entry will be the array
3556   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3557   // of length 1' case, and the entire path must match.
3558   bool WasArrayIndex;
3559   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3560   return CommonLength >= A.Entries.size() - IsArray;
3561 }
3562 
3563 /// Find the complete object to which an LValue refers.
3564 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3565                                          AccessKinds AK, const LValue &LVal,
3566                                          QualType LValType) {
3567   if (LVal.InvalidBase) {
3568     Info.FFDiag(E);
3569     return CompleteObject();
3570   }
3571 
3572   if (!LVal.Base) {
3573     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3574     return CompleteObject();
3575   }
3576 
3577   CallStackFrame *Frame = nullptr;
3578   unsigned Depth = 0;
3579   if (LVal.getLValueCallIndex()) {
3580     std::tie(Frame, Depth) =
3581         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3582     if (!Frame) {
3583       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3584         << AK << LVal.Base.is<const ValueDecl*>();
3585       NoteLValueLocation(Info, LVal.Base);
3586       return CompleteObject();
3587     }
3588   }
3589 
3590   bool IsAccess = isAnyAccess(AK);
3591 
3592   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3593   // is not a constant expression (even if the object is non-volatile). We also
3594   // apply this rule to C++98, in order to conform to the expected 'volatile'
3595   // semantics.
3596   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3597     if (Info.getLangOpts().CPlusPlus)
3598       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3599         << AK << LValType;
3600     else
3601       Info.FFDiag(E);
3602     return CompleteObject();
3603   }
3604 
3605   // Compute value storage location and type of base object.
3606   APValue *BaseVal = nullptr;
3607   QualType BaseType = getType(LVal.Base);
3608 
3609   if (const ConstantExpr *CE =
3610           dyn_cast_or_null<ConstantExpr>(LVal.Base.dyn_cast<const Expr *>())) {
3611     /// Nested immediate invocation have been previously removed so if we found
3612     /// a ConstantExpr it can only be the EvaluatingDecl.
3613     assert(CE->isImmediateInvocation() && CE == Info.EvaluatingDecl);
3614     (void)CE;
3615     BaseVal = Info.EvaluatingDeclValue;
3616   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
3617     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3618     // In C++11, constexpr, non-volatile variables initialized with constant
3619     // expressions are constant expressions too. Inside constexpr functions,
3620     // parameters are constant expressions even if they're non-const.
3621     // In C++1y, objects local to a constant expression (those with a Frame) are
3622     // both readable and writable inside constant expressions.
3623     // In C, such things can also be folded, although they are not ICEs.
3624     const VarDecl *VD = dyn_cast<VarDecl>(D);
3625     if (VD) {
3626       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3627         VD = VDef;
3628     }
3629     if (!VD || VD->isInvalidDecl()) {
3630       Info.FFDiag(E);
3631       return CompleteObject();
3632     }
3633 
3634     // Unless we're looking at a local variable or argument in a constexpr call,
3635     // the variable we're reading must be const.
3636     if (!Frame) {
3637       if (Info.getLangOpts().CPlusPlus14 &&
3638           lifetimeStartedInEvaluation(Info, LVal.Base)) {
3639         // OK, we can read and modify an object if we're in the process of
3640         // evaluating its initializer, because its lifetime began in this
3641         // evaluation.
3642       } else if (isModification(AK)) {
3643         // All the remaining cases do not permit modification of the object.
3644         Info.FFDiag(E, diag::note_constexpr_modify_global);
3645         return CompleteObject();
3646       } else if (VD->isConstexpr()) {
3647         // OK, we can read this variable.
3648       } else if (BaseType->isIntegralOrEnumerationType()) {
3649         // In OpenCL if a variable is in constant address space it is a const
3650         // value.
3651         if (!(BaseType.isConstQualified() ||
3652               (Info.getLangOpts().OpenCL &&
3653                BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3654           if (!IsAccess)
3655             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3656           if (Info.getLangOpts().CPlusPlus) {
3657             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3658             Info.Note(VD->getLocation(), diag::note_declared_at);
3659           } else {
3660             Info.FFDiag(E);
3661           }
3662           return CompleteObject();
3663         }
3664       } else if (!IsAccess) {
3665         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3666       } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3667         // We support folding of const floating-point types, in order to make
3668         // static const data members of such types (supported as an extension)
3669         // more useful.
3670         if (Info.getLangOpts().CPlusPlus11) {
3671           Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3672           Info.Note(VD->getLocation(), diag::note_declared_at);
3673         } else {
3674           Info.CCEDiag(E);
3675         }
3676       } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3677         Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3678         // Keep evaluating to see what we can do.
3679       } else {
3680         // FIXME: Allow folding of values of any literal type in all languages.
3681         if (Info.checkingPotentialConstantExpression() &&
3682             VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3683           // The definition of this variable could be constexpr. We can't
3684           // access it right now, but may be able to in future.
3685         } else if (Info.getLangOpts().CPlusPlus11) {
3686           Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3687           Info.Note(VD->getLocation(), diag::note_declared_at);
3688         } else {
3689           Info.FFDiag(E);
3690         }
3691         return CompleteObject();
3692       }
3693     }
3694 
3695     if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
3696       return CompleteObject();
3697   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
3698     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
3699     if (!Alloc) {
3700       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
3701       return CompleteObject();
3702     }
3703     return CompleteObject(LVal.Base, &(*Alloc)->Value,
3704                           LVal.Base.getDynamicAllocType());
3705   } else {
3706     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3707 
3708     if (!Frame) {
3709       if (const MaterializeTemporaryExpr *MTE =
3710               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
3711         assert(MTE->getStorageDuration() == SD_Static &&
3712                "should have a frame for a non-global materialized temporary");
3713 
3714         // Per C++1y [expr.const]p2:
3715         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3716         //   - a [...] glvalue of integral or enumeration type that refers to
3717         //     a non-volatile const object [...]
3718         //   [...]
3719         //   - a [...] glvalue of literal type that refers to a non-volatile
3720         //     object whose lifetime began within the evaluation of e.
3721         //
3722         // C++11 misses the 'began within the evaluation of e' check and
3723         // instead allows all temporaries, including things like:
3724         //   int &&r = 1;
3725         //   int x = ++r;
3726         //   constexpr int k = r;
3727         // Therefore we use the C++14 rules in C++11 too.
3728         //
3729         // Note that temporaries whose lifetimes began while evaluating a
3730         // variable's constructor are not usable while evaluating the
3731         // corresponding destructor, not even if they're of const-qualified
3732         // types.
3733         if (!(BaseType.isConstQualified() &&
3734               BaseType->isIntegralOrEnumerationType()) &&
3735             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
3736           if (!IsAccess)
3737             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3738           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3739           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3740           return CompleteObject();
3741         }
3742 
3743         BaseVal = MTE->getOrCreateValue(false);
3744         assert(BaseVal && "got reference to unevaluated temporary");
3745       } else {
3746         if (!IsAccess)
3747           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3748         APValue Val;
3749         LVal.moveInto(Val);
3750         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3751             << AK
3752             << Val.getAsString(Info.Ctx,
3753                                Info.Ctx.getLValueReferenceType(LValType));
3754         NoteLValueLocation(Info, LVal.Base);
3755         return CompleteObject();
3756       }
3757     } else {
3758       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
3759       assert(BaseVal && "missing value for temporary");
3760     }
3761   }
3762 
3763   // In C++14, we can't safely access any mutable state when we might be
3764   // evaluating after an unmodeled side effect.
3765   //
3766   // FIXME: Not all local state is mutable. Allow local constant subobjects
3767   // to be read here (but take care with 'mutable' fields).
3768   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3769        Info.EvalStatus.HasSideEffects) ||
3770       (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
3771     return CompleteObject();
3772 
3773   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
3774 }
3775 
3776 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
3777 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3778 /// glvalue referred to by an entity of reference type.
3779 ///
3780 /// \param Info - Information about the ongoing evaluation.
3781 /// \param Conv - The expression for which we are performing the conversion.
3782 ///               Used for diagnostics.
3783 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3784 ///               case of a non-class type).
3785 /// \param LVal - The glvalue on which we are attempting to perform this action.
3786 /// \param RVal - The produced value will be placed here.
3787 /// \param WantObjectRepresentation - If true, we're looking for the object
3788 ///               representation rather than the value, and in particular,
3789 ///               there is no requirement that the result be fully initialized.
3790 static bool
3791 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
3792                                const LValue &LVal, APValue &RVal,
3793                                bool WantObjectRepresentation = false) {
3794   if (LVal.Designator.Invalid)
3795     return false;
3796 
3797   // Check for special cases where there is no existing APValue to look at.
3798   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3799 
3800   AccessKinds AK =
3801       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
3802 
3803   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
3804     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3805       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3806       // initializer until now for such expressions. Such an expression can't be
3807       // an ICE in C, so this only matters for fold.
3808       if (Type.isVolatileQualified()) {
3809         Info.FFDiag(Conv);
3810         return false;
3811       }
3812       APValue Lit;
3813       if (!Evaluate(Lit, Info, CLE->getInitializer()))
3814         return false;
3815       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
3816       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
3817     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3818       // Special-case character extraction so we don't have to construct an
3819       // APValue for the whole string.
3820       assert(LVal.Designator.Entries.size() <= 1 &&
3821              "Can only read characters from string literals");
3822       if (LVal.Designator.Entries.empty()) {
3823         // Fail for now for LValue to RValue conversion of an array.
3824         // (This shouldn't show up in C/C++, but it could be triggered by a
3825         // weird EvaluateAsRValue call from a tool.)
3826         Info.FFDiag(Conv);
3827         return false;
3828       }
3829       if (LVal.Designator.isOnePastTheEnd()) {
3830         if (Info.getLangOpts().CPlusPlus11)
3831           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
3832         else
3833           Info.FFDiag(Conv);
3834         return false;
3835       }
3836       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
3837       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3838       return true;
3839     }
3840   }
3841 
3842   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
3843   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
3844 }
3845 
3846 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3847 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3848                              QualType LValType, APValue &Val) {
3849   if (LVal.Designator.Invalid)
3850     return false;
3851 
3852   if (!Info.getLangOpts().CPlusPlus14) {
3853     Info.FFDiag(E);
3854     return false;
3855   }
3856 
3857   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3858   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3859 }
3860 
3861 namespace {
3862 struct CompoundAssignSubobjectHandler {
3863   EvalInfo &Info;
3864   const Expr *E;
3865   QualType PromotedLHSType;
3866   BinaryOperatorKind Opcode;
3867   const APValue &RHS;
3868 
3869   static const AccessKinds AccessKind = AK_Assign;
3870 
3871   typedef bool result_type;
3872 
3873   bool checkConst(QualType QT) {
3874     // Assigning to a const object has undefined behavior.
3875     if (QT.isConstQualified()) {
3876       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3877       return false;
3878     }
3879     return true;
3880   }
3881 
3882   bool failed() { return false; }
3883   bool found(APValue &Subobj, QualType SubobjType) {
3884     switch (Subobj.getKind()) {
3885     case APValue::Int:
3886       return found(Subobj.getInt(), SubobjType);
3887     case APValue::Float:
3888       return found(Subobj.getFloat(), SubobjType);
3889     case APValue::ComplexInt:
3890     case APValue::ComplexFloat:
3891       // FIXME: Implement complex compound assignment.
3892       Info.FFDiag(E);
3893       return false;
3894     case APValue::LValue:
3895       return foundPointer(Subobj, SubobjType);
3896     default:
3897       // FIXME: can this happen?
3898       Info.FFDiag(E);
3899       return false;
3900     }
3901   }
3902   bool found(APSInt &Value, QualType SubobjType) {
3903     if (!checkConst(SubobjType))
3904       return false;
3905 
3906     if (!SubobjType->isIntegerType()) {
3907       // We don't support compound assignment on integer-cast-to-pointer
3908       // values.
3909       Info.FFDiag(E);
3910       return false;
3911     }
3912 
3913     if (RHS.isInt()) {
3914       APSInt LHS =
3915           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3916       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3917         return false;
3918       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3919       return true;
3920     } else if (RHS.isFloat()) {
3921       APFloat FValue(0.0);
3922       return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3923                                   FValue) &&
3924              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3925              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3926                                   Value);
3927     }
3928 
3929     Info.FFDiag(E);
3930     return false;
3931   }
3932   bool found(APFloat &Value, QualType SubobjType) {
3933     return checkConst(SubobjType) &&
3934            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3935                                   Value) &&
3936            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3937            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3938   }
3939   bool foundPointer(APValue &Subobj, QualType SubobjType) {
3940     if (!checkConst(SubobjType))
3941       return false;
3942 
3943     QualType PointeeType;
3944     if (const PointerType *PT = SubobjType->getAs<PointerType>())
3945       PointeeType = PT->getPointeeType();
3946 
3947     if (PointeeType.isNull() || !RHS.isInt() ||
3948         (Opcode != BO_Add && Opcode != BO_Sub)) {
3949       Info.FFDiag(E);
3950       return false;
3951     }
3952 
3953     APSInt Offset = RHS.getInt();
3954     if (Opcode == BO_Sub)
3955       negateAsSigned(Offset);
3956 
3957     LValue LVal;
3958     LVal.setFrom(Info.Ctx, Subobj);
3959     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3960       return false;
3961     LVal.moveInto(Subobj);
3962     return true;
3963   }
3964 };
3965 } // end anonymous namespace
3966 
3967 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3968 
3969 /// Perform a compound assignment of LVal <op>= RVal.
3970 static bool handleCompoundAssignment(
3971     EvalInfo &Info, const Expr *E,
3972     const LValue &LVal, QualType LValType, QualType PromotedLValType,
3973     BinaryOperatorKind Opcode, const APValue &RVal) {
3974   if (LVal.Designator.Invalid)
3975     return false;
3976 
3977   if (!Info.getLangOpts().CPlusPlus14) {
3978     Info.FFDiag(E);
3979     return false;
3980   }
3981 
3982   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3983   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3984                                              RVal };
3985   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3986 }
3987 
3988 namespace {
3989 struct IncDecSubobjectHandler {
3990   EvalInfo &Info;
3991   const UnaryOperator *E;
3992   AccessKinds AccessKind;
3993   APValue *Old;
3994 
3995   typedef bool result_type;
3996 
3997   bool checkConst(QualType QT) {
3998     // Assigning to a const object has undefined behavior.
3999     if (QT.isConstQualified()) {
4000       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4001       return false;
4002     }
4003     return true;
4004   }
4005 
4006   bool failed() { return false; }
4007   bool found(APValue &Subobj, QualType SubobjType) {
4008     // Stash the old value. Also clear Old, so we don't clobber it later
4009     // if we're post-incrementing a complex.
4010     if (Old) {
4011       *Old = Subobj;
4012       Old = nullptr;
4013     }
4014 
4015     switch (Subobj.getKind()) {
4016     case APValue::Int:
4017       return found(Subobj.getInt(), SubobjType);
4018     case APValue::Float:
4019       return found(Subobj.getFloat(), SubobjType);
4020     case APValue::ComplexInt:
4021       return found(Subobj.getComplexIntReal(),
4022                    SubobjType->castAs<ComplexType>()->getElementType()
4023                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4024     case APValue::ComplexFloat:
4025       return found(Subobj.getComplexFloatReal(),
4026                    SubobjType->castAs<ComplexType>()->getElementType()
4027                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4028     case APValue::LValue:
4029       return foundPointer(Subobj, SubobjType);
4030     default:
4031       // FIXME: can this happen?
4032       Info.FFDiag(E);
4033       return false;
4034     }
4035   }
4036   bool found(APSInt &Value, QualType SubobjType) {
4037     if (!checkConst(SubobjType))
4038       return false;
4039 
4040     if (!SubobjType->isIntegerType()) {
4041       // We don't support increment / decrement on integer-cast-to-pointer
4042       // values.
4043       Info.FFDiag(E);
4044       return false;
4045     }
4046 
4047     if (Old) *Old = APValue(Value);
4048 
4049     // bool arithmetic promotes to int, and the conversion back to bool
4050     // doesn't reduce mod 2^n, so special-case it.
4051     if (SubobjType->isBooleanType()) {
4052       if (AccessKind == AK_Increment)
4053         Value = 1;
4054       else
4055         Value = !Value;
4056       return true;
4057     }
4058 
4059     bool WasNegative = Value.isNegative();
4060     if (AccessKind == AK_Increment) {
4061       ++Value;
4062 
4063       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4064         APSInt ActualValue(Value, /*IsUnsigned*/true);
4065         return HandleOverflow(Info, E, ActualValue, SubobjType);
4066       }
4067     } else {
4068       --Value;
4069 
4070       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4071         unsigned BitWidth = Value.getBitWidth();
4072         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4073         ActualValue.setBit(BitWidth);
4074         return HandleOverflow(Info, E, ActualValue, SubobjType);
4075       }
4076     }
4077     return true;
4078   }
4079   bool found(APFloat &Value, QualType SubobjType) {
4080     if (!checkConst(SubobjType))
4081       return false;
4082 
4083     if (Old) *Old = APValue(Value);
4084 
4085     APFloat One(Value.getSemantics(), 1);
4086     if (AccessKind == AK_Increment)
4087       Value.add(One, APFloat::rmNearestTiesToEven);
4088     else
4089       Value.subtract(One, APFloat::rmNearestTiesToEven);
4090     return true;
4091   }
4092   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4093     if (!checkConst(SubobjType))
4094       return false;
4095 
4096     QualType PointeeType;
4097     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4098       PointeeType = PT->getPointeeType();
4099     else {
4100       Info.FFDiag(E);
4101       return false;
4102     }
4103 
4104     LValue LVal;
4105     LVal.setFrom(Info.Ctx, Subobj);
4106     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4107                                      AccessKind == AK_Increment ? 1 : -1))
4108       return false;
4109     LVal.moveInto(Subobj);
4110     return true;
4111   }
4112 };
4113 } // end anonymous namespace
4114 
4115 /// Perform an increment or decrement on LVal.
4116 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4117                          QualType LValType, bool IsIncrement, APValue *Old) {
4118   if (LVal.Designator.Invalid)
4119     return false;
4120 
4121   if (!Info.getLangOpts().CPlusPlus14) {
4122     Info.FFDiag(E);
4123     return false;
4124   }
4125 
4126   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4127   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4128   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4129   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4130 }
4131 
4132 /// Build an lvalue for the object argument of a member function call.
4133 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4134                                    LValue &This) {
4135   if (Object->getType()->isPointerType() && Object->isRValue())
4136     return EvaluatePointer(Object, This, Info);
4137 
4138   if (Object->isGLValue())
4139     return EvaluateLValue(Object, This, Info);
4140 
4141   if (Object->getType()->isLiteralType(Info.Ctx))
4142     return EvaluateTemporary(Object, This, Info);
4143 
4144   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4145   return false;
4146 }
4147 
4148 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4149 /// lvalue referring to the result.
4150 ///
4151 /// \param Info - Information about the ongoing evaluation.
4152 /// \param LV - An lvalue referring to the base of the member pointer.
4153 /// \param RHS - The member pointer expression.
4154 /// \param IncludeMember - Specifies whether the member itself is included in
4155 ///        the resulting LValue subobject designator. This is not possible when
4156 ///        creating a bound member function.
4157 /// \return The field or method declaration to which the member pointer refers,
4158 ///         or 0 if evaluation fails.
4159 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4160                                                   QualType LVType,
4161                                                   LValue &LV,
4162                                                   const Expr *RHS,
4163                                                   bool IncludeMember = true) {
4164   MemberPtr MemPtr;
4165   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4166     return nullptr;
4167 
4168   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4169   // member value, the behavior is undefined.
4170   if (!MemPtr.getDecl()) {
4171     // FIXME: Specific diagnostic.
4172     Info.FFDiag(RHS);
4173     return nullptr;
4174   }
4175 
4176   if (MemPtr.isDerivedMember()) {
4177     // This is a member of some derived class. Truncate LV appropriately.
4178     // The end of the derived-to-base path for the base object must match the
4179     // derived-to-base path for the member pointer.
4180     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4181         LV.Designator.Entries.size()) {
4182       Info.FFDiag(RHS);
4183       return nullptr;
4184     }
4185     unsigned PathLengthToMember =
4186         LV.Designator.Entries.size() - MemPtr.Path.size();
4187     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4188       const CXXRecordDecl *LVDecl = getAsBaseClass(
4189           LV.Designator.Entries[PathLengthToMember + I]);
4190       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4191       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4192         Info.FFDiag(RHS);
4193         return nullptr;
4194       }
4195     }
4196 
4197     // Truncate the lvalue to the appropriate derived class.
4198     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4199                             PathLengthToMember))
4200       return nullptr;
4201   } else if (!MemPtr.Path.empty()) {
4202     // Extend the LValue path with the member pointer's path.
4203     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4204                                   MemPtr.Path.size() + IncludeMember);
4205 
4206     // Walk down to the appropriate base class.
4207     if (const PointerType *PT = LVType->getAs<PointerType>())
4208       LVType = PT->getPointeeType();
4209     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4210     assert(RD && "member pointer access on non-class-type expression");
4211     // The first class in the path is that of the lvalue.
4212     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4213       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4214       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4215         return nullptr;
4216       RD = Base;
4217     }
4218     // Finally cast to the class containing the member.
4219     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4220                                 MemPtr.getContainingRecord()))
4221       return nullptr;
4222   }
4223 
4224   // Add the member. Note that we cannot build bound member functions here.
4225   if (IncludeMember) {
4226     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4227       if (!HandleLValueMember(Info, RHS, LV, FD))
4228         return nullptr;
4229     } else if (const IndirectFieldDecl *IFD =
4230                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4231       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4232         return nullptr;
4233     } else {
4234       llvm_unreachable("can't construct reference to bound member function");
4235     }
4236   }
4237 
4238   return MemPtr.getDecl();
4239 }
4240 
4241 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4242                                                   const BinaryOperator *BO,
4243                                                   LValue &LV,
4244                                                   bool IncludeMember = true) {
4245   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4246 
4247   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4248     if (Info.noteFailure()) {
4249       MemberPtr MemPtr;
4250       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4251     }
4252     return nullptr;
4253   }
4254 
4255   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4256                                    BO->getRHS(), IncludeMember);
4257 }
4258 
4259 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4260 /// the provided lvalue, which currently refers to the base object.
4261 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4262                                     LValue &Result) {
4263   SubobjectDesignator &D = Result.Designator;
4264   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4265     return false;
4266 
4267   QualType TargetQT = E->getType();
4268   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4269     TargetQT = PT->getPointeeType();
4270 
4271   // Check this cast lands within the final derived-to-base subobject path.
4272   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4273     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4274       << D.MostDerivedType << TargetQT;
4275     return false;
4276   }
4277 
4278   // Check the type of the final cast. We don't need to check the path,
4279   // since a cast can only be formed if the path is unique.
4280   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4281   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4282   const CXXRecordDecl *FinalType;
4283   if (NewEntriesSize == D.MostDerivedPathLength)
4284     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4285   else
4286     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4287   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4288     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4289       << D.MostDerivedType << TargetQT;
4290     return false;
4291   }
4292 
4293   // Truncate the lvalue to the appropriate derived class.
4294   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4295 }
4296 
4297 /// Get the value to use for a default-initialized object of type T.
4298 static APValue getDefaultInitValue(QualType T) {
4299   if (auto *RD = T->getAsCXXRecordDecl()) {
4300     if (RD->isUnion())
4301       return APValue((const FieldDecl*)nullptr);
4302 
4303     APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
4304                    std::distance(RD->field_begin(), RD->field_end()));
4305 
4306     unsigned Index = 0;
4307     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4308            End = RD->bases_end(); I != End; ++I, ++Index)
4309       Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
4310 
4311     for (const auto *I : RD->fields()) {
4312       if (I->isUnnamedBitfield())
4313         continue;
4314       Struct.getStructField(I->getFieldIndex()) =
4315           getDefaultInitValue(I->getType());
4316     }
4317     return Struct;
4318   }
4319 
4320   if (auto *AT =
4321           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4322     APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4323     if (Array.hasArrayFiller())
4324       Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
4325     return Array;
4326   }
4327 
4328   return APValue::IndeterminateValue();
4329 }
4330 
4331 namespace {
4332 enum EvalStmtResult {
4333   /// Evaluation failed.
4334   ESR_Failed,
4335   /// Hit a 'return' statement.
4336   ESR_Returned,
4337   /// Evaluation succeeded.
4338   ESR_Succeeded,
4339   /// Hit a 'continue' statement.
4340   ESR_Continue,
4341   /// Hit a 'break' statement.
4342   ESR_Break,
4343   /// Still scanning for 'case' or 'default' statement.
4344   ESR_CaseNotFound
4345 };
4346 }
4347 
4348 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4349   // We don't need to evaluate the initializer for a static local.
4350   if (!VD->hasLocalStorage())
4351     return true;
4352 
4353   LValue Result;
4354   APValue &Val =
4355       Info.CurrentCall->createTemporary(VD, VD->getType(), true, Result);
4356 
4357   const Expr *InitE = VD->getInit();
4358   if (!InitE) {
4359     Val = getDefaultInitValue(VD->getType());
4360     return true;
4361   }
4362 
4363   if (InitE->isValueDependent())
4364     return false;
4365 
4366   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4367     // Wipe out any partially-computed value, to allow tracking that this
4368     // evaluation failed.
4369     Val = APValue();
4370     return false;
4371   }
4372 
4373   return true;
4374 }
4375 
4376 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4377   bool OK = true;
4378 
4379   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4380     OK &= EvaluateVarDecl(Info, VD);
4381 
4382   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4383     for (auto *BD : DD->bindings())
4384       if (auto *VD = BD->getHoldingVar())
4385         OK &= EvaluateDecl(Info, VD);
4386 
4387   return OK;
4388 }
4389 
4390 
4391 /// Evaluate a condition (either a variable declaration or an expression).
4392 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4393                          const Expr *Cond, bool &Result) {
4394   FullExpressionRAII Scope(Info);
4395   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4396     return false;
4397   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4398     return false;
4399   return Scope.destroy();
4400 }
4401 
4402 namespace {
4403 /// A location where the result (returned value) of evaluating a
4404 /// statement should be stored.
4405 struct StmtResult {
4406   /// The APValue that should be filled in with the returned value.
4407   APValue &Value;
4408   /// The location containing the result, if any (used to support RVO).
4409   const LValue *Slot;
4410 };
4411 
4412 struct TempVersionRAII {
4413   CallStackFrame &Frame;
4414 
4415   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4416     Frame.pushTempVersion();
4417   }
4418 
4419   ~TempVersionRAII() {
4420     Frame.popTempVersion();
4421   }
4422 };
4423 
4424 }
4425 
4426 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4427                                    const Stmt *S,
4428                                    const SwitchCase *SC = nullptr);
4429 
4430 /// Evaluate the body of a loop, and translate the result as appropriate.
4431 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4432                                        const Stmt *Body,
4433                                        const SwitchCase *Case = nullptr) {
4434   BlockScopeRAII Scope(Info);
4435 
4436   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4437   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4438     ESR = ESR_Failed;
4439 
4440   switch (ESR) {
4441   case ESR_Break:
4442     return ESR_Succeeded;
4443   case ESR_Succeeded:
4444   case ESR_Continue:
4445     return ESR_Continue;
4446   case ESR_Failed:
4447   case ESR_Returned:
4448   case ESR_CaseNotFound:
4449     return ESR;
4450   }
4451   llvm_unreachable("Invalid EvalStmtResult!");
4452 }
4453 
4454 /// Evaluate a switch statement.
4455 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4456                                      const SwitchStmt *SS) {
4457   BlockScopeRAII Scope(Info);
4458 
4459   // Evaluate the switch condition.
4460   APSInt Value;
4461   {
4462     if (const Stmt *Init = SS->getInit()) {
4463       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4464       if (ESR != ESR_Succeeded) {
4465         if (ESR != ESR_Failed && !Scope.destroy())
4466           ESR = ESR_Failed;
4467         return ESR;
4468       }
4469     }
4470 
4471     FullExpressionRAII CondScope(Info);
4472     if (SS->getConditionVariable() &&
4473         !EvaluateDecl(Info, SS->getConditionVariable()))
4474       return ESR_Failed;
4475     if (!EvaluateInteger(SS->getCond(), Value, Info))
4476       return ESR_Failed;
4477     if (!CondScope.destroy())
4478       return ESR_Failed;
4479   }
4480 
4481   // Find the switch case corresponding to the value of the condition.
4482   // FIXME: Cache this lookup.
4483   const SwitchCase *Found = nullptr;
4484   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4485        SC = SC->getNextSwitchCase()) {
4486     if (isa<DefaultStmt>(SC)) {
4487       Found = SC;
4488       continue;
4489     }
4490 
4491     const CaseStmt *CS = cast<CaseStmt>(SC);
4492     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4493     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4494                               : LHS;
4495     if (LHS <= Value && Value <= RHS) {
4496       Found = SC;
4497       break;
4498     }
4499   }
4500 
4501   if (!Found)
4502     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4503 
4504   // Search the switch body for the switch case and evaluate it from there.
4505   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4506   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4507     return ESR_Failed;
4508 
4509   switch (ESR) {
4510   case ESR_Break:
4511     return ESR_Succeeded;
4512   case ESR_Succeeded:
4513   case ESR_Continue:
4514   case ESR_Failed:
4515   case ESR_Returned:
4516     return ESR;
4517   case ESR_CaseNotFound:
4518     // This can only happen if the switch case is nested within a statement
4519     // expression. We have no intention of supporting that.
4520     Info.FFDiag(Found->getBeginLoc(),
4521                 diag::note_constexpr_stmt_expr_unsupported);
4522     return ESR_Failed;
4523   }
4524   llvm_unreachable("Invalid EvalStmtResult!");
4525 }
4526 
4527 // Evaluate a statement.
4528 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4529                                    const Stmt *S, const SwitchCase *Case) {
4530   if (!Info.nextStep(S))
4531     return ESR_Failed;
4532 
4533   // If we're hunting down a 'case' or 'default' label, recurse through
4534   // substatements until we hit the label.
4535   if (Case) {
4536     switch (S->getStmtClass()) {
4537     case Stmt::CompoundStmtClass:
4538       // FIXME: Precompute which substatement of a compound statement we
4539       // would jump to, and go straight there rather than performing a
4540       // linear scan each time.
4541     case Stmt::LabelStmtClass:
4542     case Stmt::AttributedStmtClass:
4543     case Stmt::DoStmtClass:
4544       break;
4545 
4546     case Stmt::CaseStmtClass:
4547     case Stmt::DefaultStmtClass:
4548       if (Case == S)
4549         Case = nullptr;
4550       break;
4551 
4552     case Stmt::IfStmtClass: {
4553       // FIXME: Precompute which side of an 'if' we would jump to, and go
4554       // straight there rather than scanning both sides.
4555       const IfStmt *IS = cast<IfStmt>(S);
4556 
4557       // Wrap the evaluation in a block scope, in case it's a DeclStmt
4558       // preceded by our switch label.
4559       BlockScopeRAII Scope(Info);
4560 
4561       // Step into the init statement in case it brings an (uninitialized)
4562       // variable into scope.
4563       if (const Stmt *Init = IS->getInit()) {
4564         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4565         if (ESR != ESR_CaseNotFound) {
4566           assert(ESR != ESR_Succeeded);
4567           return ESR;
4568         }
4569       }
4570 
4571       // Condition variable must be initialized if it exists.
4572       // FIXME: We can skip evaluating the body if there's a condition
4573       // variable, as there can't be any case labels within it.
4574       // (The same is true for 'for' statements.)
4575 
4576       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4577       if (ESR == ESR_Failed)
4578         return ESR;
4579       if (ESR != ESR_CaseNotFound)
4580         return Scope.destroy() ? ESR : ESR_Failed;
4581       if (!IS->getElse())
4582         return ESR_CaseNotFound;
4583 
4584       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
4585       if (ESR == ESR_Failed)
4586         return ESR;
4587       if (ESR != ESR_CaseNotFound)
4588         return Scope.destroy() ? ESR : ESR_Failed;
4589       return ESR_CaseNotFound;
4590     }
4591 
4592     case Stmt::WhileStmtClass: {
4593       EvalStmtResult ESR =
4594           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4595       if (ESR != ESR_Continue)
4596         return ESR;
4597       break;
4598     }
4599 
4600     case Stmt::ForStmtClass: {
4601       const ForStmt *FS = cast<ForStmt>(S);
4602       BlockScopeRAII Scope(Info);
4603 
4604       // Step into the init statement in case it brings an (uninitialized)
4605       // variable into scope.
4606       if (const Stmt *Init = FS->getInit()) {
4607         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4608         if (ESR != ESR_CaseNotFound) {
4609           assert(ESR != ESR_Succeeded);
4610           return ESR;
4611         }
4612       }
4613 
4614       EvalStmtResult ESR =
4615           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4616       if (ESR != ESR_Continue)
4617         return ESR;
4618       if (FS->getInc()) {
4619         FullExpressionRAII IncScope(Info);
4620         if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
4621           return ESR_Failed;
4622       }
4623       break;
4624     }
4625 
4626     case Stmt::DeclStmtClass: {
4627       // Start the lifetime of any uninitialized variables we encounter. They
4628       // might be used by the selected branch of the switch.
4629       const DeclStmt *DS = cast<DeclStmt>(S);
4630       for (const auto *D : DS->decls()) {
4631         if (const auto *VD = dyn_cast<VarDecl>(D)) {
4632           if (VD->hasLocalStorage() && !VD->getInit())
4633             if (!EvaluateVarDecl(Info, VD))
4634               return ESR_Failed;
4635           // FIXME: If the variable has initialization that can't be jumped
4636           // over, bail out of any immediately-surrounding compound-statement
4637           // too. There can't be any case labels here.
4638         }
4639       }
4640       return ESR_CaseNotFound;
4641     }
4642 
4643     default:
4644       return ESR_CaseNotFound;
4645     }
4646   }
4647 
4648   switch (S->getStmtClass()) {
4649   default:
4650     if (const Expr *E = dyn_cast<Expr>(S)) {
4651       // Don't bother evaluating beyond an expression-statement which couldn't
4652       // be evaluated.
4653       // FIXME: Do we need the FullExpressionRAII object here?
4654       // VisitExprWithCleanups should create one when necessary.
4655       FullExpressionRAII Scope(Info);
4656       if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
4657         return ESR_Failed;
4658       return ESR_Succeeded;
4659     }
4660 
4661     Info.FFDiag(S->getBeginLoc());
4662     return ESR_Failed;
4663 
4664   case Stmt::NullStmtClass:
4665     return ESR_Succeeded;
4666 
4667   case Stmt::DeclStmtClass: {
4668     const DeclStmt *DS = cast<DeclStmt>(S);
4669     for (const auto *D : DS->decls()) {
4670       // Each declaration initialization is its own full-expression.
4671       FullExpressionRAII Scope(Info);
4672       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
4673         return ESR_Failed;
4674       if (!Scope.destroy())
4675         return ESR_Failed;
4676     }
4677     return ESR_Succeeded;
4678   }
4679 
4680   case Stmt::ReturnStmtClass: {
4681     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
4682     FullExpressionRAII Scope(Info);
4683     if (RetExpr &&
4684         !(Result.Slot
4685               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4686               : Evaluate(Result.Value, Info, RetExpr)))
4687       return ESR_Failed;
4688     return Scope.destroy() ? ESR_Returned : ESR_Failed;
4689   }
4690 
4691   case Stmt::CompoundStmtClass: {
4692     BlockScopeRAII Scope(Info);
4693 
4694     const CompoundStmt *CS = cast<CompoundStmt>(S);
4695     for (const auto *BI : CS->body()) {
4696       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
4697       if (ESR == ESR_Succeeded)
4698         Case = nullptr;
4699       else if (ESR != ESR_CaseNotFound) {
4700         if (ESR != ESR_Failed && !Scope.destroy())
4701           return ESR_Failed;
4702         return ESR;
4703       }
4704     }
4705     if (Case)
4706       return ESR_CaseNotFound;
4707     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4708   }
4709 
4710   case Stmt::IfStmtClass: {
4711     const IfStmt *IS = cast<IfStmt>(S);
4712 
4713     // Evaluate the condition, as either a var decl or as an expression.
4714     BlockScopeRAII Scope(Info);
4715     if (const Stmt *Init = IS->getInit()) {
4716       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4717       if (ESR != ESR_Succeeded) {
4718         if (ESR != ESR_Failed && !Scope.destroy())
4719           return ESR_Failed;
4720         return ESR;
4721       }
4722     }
4723     bool Cond;
4724     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4725       return ESR_Failed;
4726 
4727     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4728       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4729       if (ESR != ESR_Succeeded) {
4730         if (ESR != ESR_Failed && !Scope.destroy())
4731           return ESR_Failed;
4732         return ESR;
4733       }
4734     }
4735     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4736   }
4737 
4738   case Stmt::WhileStmtClass: {
4739     const WhileStmt *WS = cast<WhileStmt>(S);
4740     while (true) {
4741       BlockScopeRAII Scope(Info);
4742       bool Continue;
4743       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4744                         Continue))
4745         return ESR_Failed;
4746       if (!Continue)
4747         break;
4748 
4749       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4750       if (ESR != ESR_Continue) {
4751         if (ESR != ESR_Failed && !Scope.destroy())
4752           return ESR_Failed;
4753         return ESR;
4754       }
4755       if (!Scope.destroy())
4756         return ESR_Failed;
4757     }
4758     return ESR_Succeeded;
4759   }
4760 
4761   case Stmt::DoStmtClass: {
4762     const DoStmt *DS = cast<DoStmt>(S);
4763     bool Continue;
4764     do {
4765       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4766       if (ESR != ESR_Continue)
4767         return ESR;
4768       Case = nullptr;
4769 
4770       FullExpressionRAII CondScope(Info);
4771       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
4772           !CondScope.destroy())
4773         return ESR_Failed;
4774     } while (Continue);
4775     return ESR_Succeeded;
4776   }
4777 
4778   case Stmt::ForStmtClass: {
4779     const ForStmt *FS = cast<ForStmt>(S);
4780     BlockScopeRAII ForScope(Info);
4781     if (FS->getInit()) {
4782       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4783       if (ESR != ESR_Succeeded) {
4784         if (ESR != ESR_Failed && !ForScope.destroy())
4785           return ESR_Failed;
4786         return ESR;
4787       }
4788     }
4789     while (true) {
4790       BlockScopeRAII IterScope(Info);
4791       bool Continue = true;
4792       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4793                                          FS->getCond(), Continue))
4794         return ESR_Failed;
4795       if (!Continue)
4796         break;
4797 
4798       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4799       if (ESR != ESR_Continue) {
4800         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
4801           return ESR_Failed;
4802         return ESR;
4803       }
4804 
4805       if (FS->getInc()) {
4806         FullExpressionRAII IncScope(Info);
4807         if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
4808           return ESR_Failed;
4809       }
4810 
4811       if (!IterScope.destroy())
4812         return ESR_Failed;
4813     }
4814     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
4815   }
4816 
4817   case Stmt::CXXForRangeStmtClass: {
4818     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4819     BlockScopeRAII Scope(Info);
4820 
4821     // Evaluate the init-statement if present.
4822     if (FS->getInit()) {
4823       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4824       if (ESR != ESR_Succeeded) {
4825         if (ESR != ESR_Failed && !Scope.destroy())
4826           return ESR_Failed;
4827         return ESR;
4828       }
4829     }
4830 
4831     // Initialize the __range variable.
4832     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4833     if (ESR != ESR_Succeeded) {
4834       if (ESR != ESR_Failed && !Scope.destroy())
4835         return ESR_Failed;
4836       return ESR;
4837     }
4838 
4839     // Create the __begin and __end iterators.
4840     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4841     if (ESR != ESR_Succeeded) {
4842       if (ESR != ESR_Failed && !Scope.destroy())
4843         return ESR_Failed;
4844       return ESR;
4845     }
4846     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4847     if (ESR != ESR_Succeeded) {
4848       if (ESR != ESR_Failed && !Scope.destroy())
4849         return ESR_Failed;
4850       return ESR;
4851     }
4852 
4853     while (true) {
4854       // Condition: __begin != __end.
4855       {
4856         bool Continue = true;
4857         FullExpressionRAII CondExpr(Info);
4858         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4859           return ESR_Failed;
4860         if (!Continue)
4861           break;
4862       }
4863 
4864       // User's variable declaration, initialized by *__begin.
4865       BlockScopeRAII InnerScope(Info);
4866       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4867       if (ESR != ESR_Succeeded) {
4868         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
4869           return ESR_Failed;
4870         return ESR;
4871       }
4872 
4873       // Loop body.
4874       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4875       if (ESR != ESR_Continue) {
4876         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
4877           return ESR_Failed;
4878         return ESR;
4879       }
4880 
4881       // Increment: ++__begin
4882       if (!EvaluateIgnoredValue(Info, FS->getInc()))
4883         return ESR_Failed;
4884 
4885       if (!InnerScope.destroy())
4886         return ESR_Failed;
4887     }
4888 
4889     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4890   }
4891 
4892   case Stmt::SwitchStmtClass:
4893     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4894 
4895   case Stmt::ContinueStmtClass:
4896     return ESR_Continue;
4897 
4898   case Stmt::BreakStmtClass:
4899     return ESR_Break;
4900 
4901   case Stmt::LabelStmtClass:
4902     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4903 
4904   case Stmt::AttributedStmtClass:
4905     // As a general principle, C++11 attributes can be ignored without
4906     // any semantic impact.
4907     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4908                         Case);
4909 
4910   case Stmt::CaseStmtClass:
4911   case Stmt::DefaultStmtClass:
4912     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4913   case Stmt::CXXTryStmtClass:
4914     // Evaluate try blocks by evaluating all sub statements.
4915     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
4916   }
4917 }
4918 
4919 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4920 /// default constructor. If so, we'll fold it whether or not it's marked as
4921 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4922 /// so we need special handling.
4923 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4924                                            const CXXConstructorDecl *CD,
4925                                            bool IsValueInitialization) {
4926   if (!CD->isTrivial() || !CD->isDefaultConstructor())
4927     return false;
4928 
4929   // Value-initialization does not call a trivial default constructor, so such a
4930   // call is a core constant expression whether or not the constructor is
4931   // constexpr.
4932   if (!CD->isConstexpr() && !IsValueInitialization) {
4933     if (Info.getLangOpts().CPlusPlus11) {
4934       // FIXME: If DiagDecl is an implicitly-declared special member function,
4935       // we should be much more explicit about why it's not constexpr.
4936       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4937         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4938       Info.Note(CD->getLocation(), diag::note_declared_at);
4939     } else {
4940       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4941     }
4942   }
4943   return true;
4944 }
4945 
4946 /// CheckConstexprFunction - Check that a function can be called in a constant
4947 /// expression.
4948 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4949                                    const FunctionDecl *Declaration,
4950                                    const FunctionDecl *Definition,
4951                                    const Stmt *Body) {
4952   // Potential constant expressions can contain calls to declared, but not yet
4953   // defined, constexpr functions.
4954   if (Info.checkingPotentialConstantExpression() && !Definition &&
4955       Declaration->isConstexpr())
4956     return false;
4957 
4958   // Bail out if the function declaration itself is invalid.  We will
4959   // have produced a relevant diagnostic while parsing it, so just
4960   // note the problematic sub-expression.
4961   if (Declaration->isInvalidDecl()) {
4962     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4963     return false;
4964   }
4965 
4966   // DR1872: An instantiated virtual constexpr function can't be called in a
4967   // constant expression (prior to C++20). We can still constant-fold such a
4968   // call.
4969   if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
4970       cast<CXXMethodDecl>(Declaration)->isVirtual())
4971     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
4972 
4973   if (Definition && Definition->isInvalidDecl()) {
4974     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4975     return false;
4976   }
4977 
4978   // Can we evaluate this function call?
4979   if (Definition && Definition->isConstexpr() && Body)
4980     return true;
4981 
4982   if (Info.getLangOpts().CPlusPlus11) {
4983     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4984 
4985     // If this function is not constexpr because it is an inherited
4986     // non-constexpr constructor, diagnose that directly.
4987     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4988     if (CD && CD->isInheritingConstructor()) {
4989       auto *Inherited = CD->getInheritedConstructor().getConstructor();
4990       if (!Inherited->isConstexpr())
4991         DiagDecl = CD = Inherited;
4992     }
4993 
4994     // FIXME: If DiagDecl is an implicitly-declared special member function
4995     // or an inheriting constructor, we should be much more explicit about why
4996     // it's not constexpr.
4997     if (CD && CD->isInheritingConstructor())
4998       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4999         << CD->getInheritedConstructor().getConstructor()->getParent();
5000     else
5001       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5002         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5003     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5004   } else {
5005     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5006   }
5007   return false;
5008 }
5009 
5010 namespace {
5011 struct CheckDynamicTypeHandler {
5012   AccessKinds AccessKind;
5013   typedef bool result_type;
5014   bool failed() { return false; }
5015   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5016   bool found(APSInt &Value, QualType SubobjType) { return true; }
5017   bool found(APFloat &Value, QualType SubobjType) { return true; }
5018 };
5019 } // end anonymous namespace
5020 
5021 /// Check that we can access the notional vptr of an object / determine its
5022 /// dynamic type.
5023 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5024                              AccessKinds AK, bool Polymorphic) {
5025   if (This.Designator.Invalid)
5026     return false;
5027 
5028   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5029 
5030   if (!Obj)
5031     return false;
5032 
5033   if (!Obj.Value) {
5034     // The object is not usable in constant expressions, so we can't inspect
5035     // its value to see if it's in-lifetime or what the active union members
5036     // are. We can still check for a one-past-the-end lvalue.
5037     if (This.Designator.isOnePastTheEnd() ||
5038         This.Designator.isMostDerivedAnUnsizedArray()) {
5039       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5040                          ? diag::note_constexpr_access_past_end
5041                          : diag::note_constexpr_access_unsized_array)
5042           << AK;
5043       return false;
5044     } else if (Polymorphic) {
5045       // Conservatively refuse to perform a polymorphic operation if we would
5046       // not be able to read a notional 'vptr' value.
5047       APValue Val;
5048       This.moveInto(Val);
5049       QualType StarThisType =
5050           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5051       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5052           << AK << Val.getAsString(Info.Ctx, StarThisType);
5053       return false;
5054     }
5055     return true;
5056   }
5057 
5058   CheckDynamicTypeHandler Handler{AK};
5059   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5060 }
5061 
5062 /// Check that the pointee of the 'this' pointer in a member function call is
5063 /// either within its lifetime or in its period of construction or destruction.
5064 static bool
5065 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5066                                      const LValue &This,
5067                                      const CXXMethodDecl *NamedMember) {
5068   return checkDynamicType(
5069       Info, E, This,
5070       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5071 }
5072 
5073 struct DynamicType {
5074   /// The dynamic class type of the object.
5075   const CXXRecordDecl *Type;
5076   /// The corresponding path length in the lvalue.
5077   unsigned PathLength;
5078 };
5079 
5080 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5081                                              unsigned PathLength) {
5082   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5083       Designator.Entries.size() && "invalid path length");
5084   return (PathLength == Designator.MostDerivedPathLength)
5085              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5086              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5087 }
5088 
5089 /// Determine the dynamic type of an object.
5090 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5091                                                 LValue &This, AccessKinds AK) {
5092   // If we don't have an lvalue denoting an object of class type, there is no
5093   // meaningful dynamic type. (We consider objects of non-class type to have no
5094   // dynamic type.)
5095   if (!checkDynamicType(Info, E, This, AK, true))
5096     return None;
5097 
5098   // Refuse to compute a dynamic type in the presence of virtual bases. This
5099   // shouldn't happen other than in constant-folding situations, since literal
5100   // types can't have virtual bases.
5101   //
5102   // Note that consumers of DynamicType assume that the type has no virtual
5103   // bases, and will need modifications if this restriction is relaxed.
5104   const CXXRecordDecl *Class =
5105       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5106   if (!Class || Class->getNumVBases()) {
5107     Info.FFDiag(E);
5108     return None;
5109   }
5110 
5111   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5112   // binary search here instead. But the overwhelmingly common case is that
5113   // we're not in the middle of a constructor, so it probably doesn't matter
5114   // in practice.
5115   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5116   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5117        PathLength <= Path.size(); ++PathLength) {
5118     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5119                                       Path.slice(0, PathLength))) {
5120     case ConstructionPhase::Bases:
5121     case ConstructionPhase::DestroyingBases:
5122       // We're constructing or destroying a base class. This is not the dynamic
5123       // type.
5124       break;
5125 
5126     case ConstructionPhase::None:
5127     case ConstructionPhase::AfterBases:
5128     case ConstructionPhase::AfterFields:
5129     case ConstructionPhase::Destroying:
5130       // We've finished constructing the base classes and not yet started
5131       // destroying them again, so this is the dynamic type.
5132       return DynamicType{getBaseClassType(This.Designator, PathLength),
5133                          PathLength};
5134     }
5135   }
5136 
5137   // CWG issue 1517: we're constructing a base class of the object described by
5138   // 'This', so that object has not yet begun its period of construction and
5139   // any polymorphic operation on it results in undefined behavior.
5140   Info.FFDiag(E);
5141   return None;
5142 }
5143 
5144 /// Perform virtual dispatch.
5145 static const CXXMethodDecl *HandleVirtualDispatch(
5146     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5147     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5148   Optional<DynamicType> DynType = ComputeDynamicType(
5149       Info, E, This,
5150       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5151   if (!DynType)
5152     return nullptr;
5153 
5154   // Find the final overrider. It must be declared in one of the classes on the
5155   // path from the dynamic type to the static type.
5156   // FIXME: If we ever allow literal types to have virtual base classes, that
5157   // won't be true.
5158   const CXXMethodDecl *Callee = Found;
5159   unsigned PathLength = DynType->PathLength;
5160   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5161     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5162     const CXXMethodDecl *Overrider =
5163         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5164     if (Overrider) {
5165       Callee = Overrider;
5166       break;
5167     }
5168   }
5169 
5170   // C++2a [class.abstract]p6:
5171   //   the effect of making a virtual call to a pure virtual function [...] is
5172   //   undefined
5173   if (Callee->isPure()) {
5174     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5175     Info.Note(Callee->getLocation(), diag::note_declared_at);
5176     return nullptr;
5177   }
5178 
5179   // If necessary, walk the rest of the path to determine the sequence of
5180   // covariant adjustment steps to apply.
5181   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5182                                        Found->getReturnType())) {
5183     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5184     for (unsigned CovariantPathLength = PathLength + 1;
5185          CovariantPathLength != This.Designator.Entries.size();
5186          ++CovariantPathLength) {
5187       const CXXRecordDecl *NextClass =
5188           getBaseClassType(This.Designator, CovariantPathLength);
5189       const CXXMethodDecl *Next =
5190           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5191       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5192                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5193         CovariantAdjustmentPath.push_back(Next->getReturnType());
5194     }
5195     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5196                                          CovariantAdjustmentPath.back()))
5197       CovariantAdjustmentPath.push_back(Found->getReturnType());
5198   }
5199 
5200   // Perform 'this' adjustment.
5201   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5202     return nullptr;
5203 
5204   return Callee;
5205 }
5206 
5207 /// Perform the adjustment from a value returned by a virtual function to
5208 /// a value of the statically expected type, which may be a pointer or
5209 /// reference to a base class of the returned type.
5210 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5211                                             APValue &Result,
5212                                             ArrayRef<QualType> Path) {
5213   assert(Result.isLValue() &&
5214          "unexpected kind of APValue for covariant return");
5215   if (Result.isNullPointer())
5216     return true;
5217 
5218   LValue LVal;
5219   LVal.setFrom(Info.Ctx, Result);
5220 
5221   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5222   for (unsigned I = 1; I != Path.size(); ++I) {
5223     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5224     assert(OldClass && NewClass && "unexpected kind of covariant return");
5225     if (OldClass != NewClass &&
5226         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5227       return false;
5228     OldClass = NewClass;
5229   }
5230 
5231   LVal.moveInto(Result);
5232   return true;
5233 }
5234 
5235 /// Determine whether \p Base, which is known to be a direct base class of
5236 /// \p Derived, is a public base class.
5237 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5238                               const CXXRecordDecl *Base) {
5239   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5240     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5241     if (BaseClass && declaresSameEntity(BaseClass, Base))
5242       return BaseSpec.getAccessSpecifier() == AS_public;
5243   }
5244   llvm_unreachable("Base is not a direct base of Derived");
5245 }
5246 
5247 /// Apply the given dynamic cast operation on the provided lvalue.
5248 ///
5249 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5250 /// to find a suitable target subobject.
5251 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5252                               LValue &Ptr) {
5253   // We can't do anything with a non-symbolic pointer value.
5254   SubobjectDesignator &D = Ptr.Designator;
5255   if (D.Invalid)
5256     return false;
5257 
5258   // C++ [expr.dynamic.cast]p6:
5259   //   If v is a null pointer value, the result is a null pointer value.
5260   if (Ptr.isNullPointer() && !E->isGLValue())
5261     return true;
5262 
5263   // For all the other cases, we need the pointer to point to an object within
5264   // its lifetime / period of construction / destruction, and we need to know
5265   // its dynamic type.
5266   Optional<DynamicType> DynType =
5267       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5268   if (!DynType)
5269     return false;
5270 
5271   // C++ [expr.dynamic.cast]p7:
5272   //   If T is "pointer to cv void", then the result is a pointer to the most
5273   //   derived object
5274   if (E->getType()->isVoidPointerType())
5275     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5276 
5277   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5278   assert(C && "dynamic_cast target is not void pointer nor class");
5279   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5280 
5281   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5282     // C++ [expr.dynamic.cast]p9:
5283     if (!E->isGLValue()) {
5284       //   The value of a failed cast to pointer type is the null pointer value
5285       //   of the required result type.
5286       Ptr.setNull(Info.Ctx, E->getType());
5287       return true;
5288     }
5289 
5290     //   A failed cast to reference type throws [...] std::bad_cast.
5291     unsigned DiagKind;
5292     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5293                    DynType->Type->isDerivedFrom(C)))
5294       DiagKind = 0;
5295     else if (!Paths || Paths->begin() == Paths->end())
5296       DiagKind = 1;
5297     else if (Paths->isAmbiguous(CQT))
5298       DiagKind = 2;
5299     else {
5300       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5301       DiagKind = 3;
5302     }
5303     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5304         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5305         << Info.Ctx.getRecordType(DynType->Type)
5306         << E->getType().getUnqualifiedType();
5307     return false;
5308   };
5309 
5310   // Runtime check, phase 1:
5311   //   Walk from the base subobject towards the derived object looking for the
5312   //   target type.
5313   for (int PathLength = Ptr.Designator.Entries.size();
5314        PathLength >= (int)DynType->PathLength; --PathLength) {
5315     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5316     if (declaresSameEntity(Class, C))
5317       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5318     // We can only walk across public inheritance edges.
5319     if (PathLength > (int)DynType->PathLength &&
5320         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5321                            Class))
5322       return RuntimeCheckFailed(nullptr);
5323   }
5324 
5325   // Runtime check, phase 2:
5326   //   Search the dynamic type for an unambiguous public base of type C.
5327   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5328                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5329   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5330       Paths.front().Access == AS_public) {
5331     // Downcast to the dynamic type...
5332     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5333       return false;
5334     // ... then upcast to the chosen base class subobject.
5335     for (CXXBasePathElement &Elem : Paths.front())
5336       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5337         return false;
5338     return true;
5339   }
5340 
5341   // Otherwise, the runtime check fails.
5342   return RuntimeCheckFailed(&Paths);
5343 }
5344 
5345 namespace {
5346 struct StartLifetimeOfUnionMemberHandler {
5347   EvalInfo &Info;
5348   const Expr *LHSExpr;
5349   const FieldDecl *Field;
5350   bool DuringInit;
5351 
5352   static const AccessKinds AccessKind = AK_Assign;
5353 
5354   typedef bool result_type;
5355   bool failed() { return false; }
5356   bool found(APValue &Subobj, QualType SubobjType) {
5357     // We are supposed to perform no initialization but begin the lifetime of
5358     // the object. We interpret that as meaning to do what default
5359     // initialization of the object would do if all constructors involved were
5360     // trivial:
5361     //  * All base, non-variant member, and array element subobjects' lifetimes
5362     //    begin
5363     //  * No variant members' lifetimes begin
5364     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5365     assert(SubobjType->isUnionType());
5366     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5367       // This union member is already active. If it's also in-lifetime, there's
5368       // nothing to do.
5369       if (Subobj.getUnionValue().hasValue())
5370         return true;
5371     } else if (DuringInit) {
5372       // We're currently in the process of initializing a different union
5373       // member.  If we carried on, that initialization would attempt to
5374       // store to an inactive union member, resulting in undefined behavior.
5375       Info.FFDiag(LHSExpr,
5376                   diag::note_constexpr_union_member_change_during_init);
5377       return false;
5378     }
5379 
5380     Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
5381     return true;
5382   }
5383   bool found(APSInt &Value, QualType SubobjType) {
5384     llvm_unreachable("wrong value kind for union object");
5385   }
5386   bool found(APFloat &Value, QualType SubobjType) {
5387     llvm_unreachable("wrong value kind for union object");
5388   }
5389 };
5390 } // end anonymous namespace
5391 
5392 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5393 
5394 /// Handle a builtin simple-assignment or a call to a trivial assignment
5395 /// operator whose left-hand side might involve a union member access. If it
5396 /// does, implicitly start the lifetime of any accessed union elements per
5397 /// C++20 [class.union]5.
5398 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5399                                           const LValue &LHS) {
5400   if (LHS.InvalidBase || LHS.Designator.Invalid)
5401     return false;
5402 
5403   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5404   // C++ [class.union]p5:
5405   //   define the set S(E) of subexpressions of E as follows:
5406   unsigned PathLength = LHS.Designator.Entries.size();
5407   for (const Expr *E = LHSExpr; E != nullptr;) {
5408     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5409     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5410       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5411       // Note that we can't implicitly start the lifetime of a reference,
5412       // so we don't need to proceed any further if we reach one.
5413       if (!FD || FD->getType()->isReferenceType())
5414         break;
5415 
5416       //    ... and also contains A.B if B names a union member ...
5417       if (FD->getParent()->isUnion()) {
5418         //    ... of a non-class, non-array type, or of a class type with a
5419         //    trivial default constructor that is not deleted, or an array of
5420         //    such types.
5421         auto *RD =
5422             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5423         if (!RD || RD->hasTrivialDefaultConstructor())
5424           UnionPathLengths.push_back({PathLength - 1, FD});
5425       }
5426 
5427       E = ME->getBase();
5428       --PathLength;
5429       assert(declaresSameEntity(FD,
5430                                 LHS.Designator.Entries[PathLength]
5431                                     .getAsBaseOrMember().getPointer()));
5432 
5433       //   -- If E is of the form A[B] and is interpreted as a built-in array
5434       //      subscripting operator, S(E) is [S(the array operand, if any)].
5435     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5436       // Step over an ArrayToPointerDecay implicit cast.
5437       auto *Base = ASE->getBase()->IgnoreImplicit();
5438       if (!Base->getType()->isArrayType())
5439         break;
5440 
5441       E = Base;
5442       --PathLength;
5443 
5444     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5445       // Step over a derived-to-base conversion.
5446       E = ICE->getSubExpr();
5447       if (ICE->getCastKind() == CK_NoOp)
5448         continue;
5449       if (ICE->getCastKind() != CK_DerivedToBase &&
5450           ICE->getCastKind() != CK_UncheckedDerivedToBase)
5451         break;
5452       // Walk path backwards as we walk up from the base to the derived class.
5453       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5454         --PathLength;
5455         (void)Elt;
5456         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5457                                   LHS.Designator.Entries[PathLength]
5458                                       .getAsBaseOrMember().getPointer()));
5459       }
5460 
5461     //   -- Otherwise, S(E) is empty.
5462     } else {
5463       break;
5464     }
5465   }
5466 
5467   // Common case: no unions' lifetimes are started.
5468   if (UnionPathLengths.empty())
5469     return true;
5470 
5471   //   if modification of X [would access an inactive union member], an object
5472   //   of the type of X is implicitly created
5473   CompleteObject Obj =
5474       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5475   if (!Obj)
5476     return false;
5477   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5478            llvm::reverse(UnionPathLengths)) {
5479     // Form a designator for the union object.
5480     SubobjectDesignator D = LHS.Designator;
5481     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5482 
5483     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
5484                       ConstructionPhase::AfterBases;
5485     StartLifetimeOfUnionMemberHandler StartLifetime{
5486         Info, LHSExpr, LengthAndField.second, DuringInit};
5487     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5488       return false;
5489   }
5490 
5491   return true;
5492 }
5493 
5494 namespace {
5495 typedef SmallVector<APValue, 8> ArgVector;
5496 }
5497 
5498 /// EvaluateArgs - Evaluate the arguments to a function call.
5499 static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
5500                          EvalInfo &Info, const FunctionDecl *Callee) {
5501   bool Success = true;
5502   llvm::SmallBitVector ForbiddenNullArgs;
5503   if (Callee->hasAttr<NonNullAttr>()) {
5504     ForbiddenNullArgs.resize(Args.size());
5505     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5506       if (!Attr->args_size()) {
5507         ForbiddenNullArgs.set();
5508         break;
5509       } else
5510         for (auto Idx : Attr->args()) {
5511           unsigned ASTIdx = Idx.getASTIndex();
5512           if (ASTIdx >= Args.size())
5513             continue;
5514           ForbiddenNullArgs[ASTIdx] = 1;
5515         }
5516     }
5517   }
5518   // FIXME: This is the wrong evaluation order for an assignment operator
5519   // called via operator syntax.
5520   for (unsigned Idx = 0; Idx < Args.size(); Idx++) {
5521     if (!Evaluate(ArgValues[Idx], Info, Args[Idx])) {
5522       // If we're checking for a potential constant expression, evaluate all
5523       // initializers even if some of them fail.
5524       if (!Info.noteFailure())
5525         return false;
5526       Success = false;
5527     } else if (!ForbiddenNullArgs.empty() &&
5528                ForbiddenNullArgs[Idx] &&
5529                ArgValues[Idx].isLValue() &&
5530                ArgValues[Idx].isNullPointer()) {
5531       Info.CCEDiag(Args[Idx], diag::note_non_null_attribute_failed);
5532       if (!Info.noteFailure())
5533         return false;
5534       Success = false;
5535     }
5536   }
5537   return Success;
5538 }
5539 
5540 /// Evaluate a function call.
5541 static bool HandleFunctionCall(SourceLocation CallLoc,
5542                                const FunctionDecl *Callee, const LValue *This,
5543                                ArrayRef<const Expr*> Args, const Stmt *Body,
5544                                EvalInfo &Info, APValue &Result,
5545                                const LValue *ResultSlot) {
5546   ArgVector ArgValues(Args.size());
5547   if (!EvaluateArgs(Args, ArgValues, Info, Callee))
5548     return false;
5549 
5550   if (!Info.CheckCallLimit(CallLoc))
5551     return false;
5552 
5553   CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
5554 
5555   // For a trivial copy or move assignment, perform an APValue copy. This is
5556   // essential for unions, where the operations performed by the assignment
5557   // operator cannot be represented as statements.
5558   //
5559   // Skip this for non-union classes with no fields; in that case, the defaulted
5560   // copy/move does not actually read the object.
5561   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
5562   if (MD && MD->isDefaulted() &&
5563       (MD->getParent()->isUnion() ||
5564        (MD->isTrivial() &&
5565         isReadByLvalueToRvalueConversion(MD->getParent())))) {
5566     assert(This &&
5567            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
5568     LValue RHS;
5569     RHS.setFrom(Info.Ctx, ArgValues[0]);
5570     APValue RHSValue;
5571     if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS,
5572                                         RHSValue, MD->getParent()->isUnion()))
5573       return false;
5574     if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
5575         !HandleUnionActiveMemberChange(Info, Args[0], *This))
5576       return false;
5577     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
5578                           RHSValue))
5579       return false;
5580     This->moveInto(Result);
5581     return true;
5582   } else if (MD && isLambdaCallOperator(MD)) {
5583     // We're in a lambda; determine the lambda capture field maps unless we're
5584     // just constexpr checking a lambda's call operator. constexpr checking is
5585     // done before the captures have been added to the closure object (unless
5586     // we're inferring constexpr-ness), so we don't have access to them in this
5587     // case. But since we don't need the captures to constexpr check, we can
5588     // just ignore them.
5589     if (!Info.checkingPotentialConstantExpression())
5590       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5591                                         Frame.LambdaThisCaptureField);
5592   }
5593 
5594   StmtResult Ret = {Result, ResultSlot};
5595   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
5596   if (ESR == ESR_Succeeded) {
5597     if (Callee->getReturnType()->isVoidType())
5598       return true;
5599     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
5600   }
5601   return ESR == ESR_Returned;
5602 }
5603 
5604 /// Evaluate a constructor call.
5605 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5606                                   APValue *ArgValues,
5607                                   const CXXConstructorDecl *Definition,
5608                                   EvalInfo &Info, APValue &Result) {
5609   SourceLocation CallLoc = E->getExprLoc();
5610   if (!Info.CheckCallLimit(CallLoc))
5611     return false;
5612 
5613   const CXXRecordDecl *RD = Definition->getParent();
5614   if (RD->getNumVBases()) {
5615     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5616     return false;
5617   }
5618 
5619   EvalInfo::EvaluatingConstructorRAII EvalObj(
5620       Info,
5621       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5622       RD->getNumBases());
5623   CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
5624 
5625   // FIXME: Creating an APValue just to hold a nonexistent return value is
5626   // wasteful.
5627   APValue RetVal;
5628   StmtResult Ret = {RetVal, nullptr};
5629 
5630   // If it's a delegating constructor, delegate.
5631   if (Definition->isDelegatingConstructor()) {
5632     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
5633     {
5634       FullExpressionRAII InitScope(Info);
5635       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
5636           !InitScope.destroy())
5637         return false;
5638     }
5639     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5640   }
5641 
5642   // For a trivial copy or move constructor, perform an APValue copy. This is
5643   // essential for unions (or classes with anonymous union members), where the
5644   // operations performed by the constructor cannot be represented by
5645   // ctor-initializers.
5646   //
5647   // Skip this for empty non-union classes; we should not perform an
5648   // lvalue-to-rvalue conversion on them because their copy constructor does not
5649   // actually read them.
5650   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
5651       (Definition->getParent()->isUnion() ||
5652        (Definition->isTrivial() &&
5653         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
5654     LValue RHS;
5655     RHS.setFrom(Info.Ctx, ArgValues[0]);
5656     return handleLValueToRValueConversion(
5657         Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
5658         RHS, Result, Definition->getParent()->isUnion());
5659   }
5660 
5661   // Reserve space for the struct members.
5662   if (!Result.hasValue()) {
5663     if (!RD->isUnion())
5664       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5665                        std::distance(RD->field_begin(), RD->field_end()));
5666     else
5667       // A union starts with no active member.
5668       Result = APValue((const FieldDecl*)nullptr);
5669   }
5670 
5671   if (RD->isInvalidDecl()) return false;
5672   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5673 
5674   // A scope for temporaries lifetime-extended by reference members.
5675   BlockScopeRAII LifetimeExtendedScope(Info);
5676 
5677   bool Success = true;
5678   unsigned BasesSeen = 0;
5679 #ifndef NDEBUG
5680   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5681 #endif
5682   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
5683   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
5684     // We might be initializing the same field again if this is an indirect
5685     // field initialization.
5686     if (FieldIt == RD->field_end() ||
5687         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
5688       assert(Indirect && "fields out of order?");
5689       return;
5690     }
5691 
5692     // Default-initialize any fields with no explicit initializer.
5693     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
5694       assert(FieldIt != RD->field_end() && "missing field?");
5695       if (!FieldIt->isUnnamedBitfield())
5696         Result.getStructField(FieldIt->getFieldIndex()) =
5697             getDefaultInitValue(FieldIt->getType());
5698     }
5699     ++FieldIt;
5700   };
5701   for (const auto *I : Definition->inits()) {
5702     LValue Subobject = This;
5703     LValue SubobjectParent = This;
5704     APValue *Value = &Result;
5705 
5706     // Determine the subobject to initialize.
5707     FieldDecl *FD = nullptr;
5708     if (I->isBaseInitializer()) {
5709       QualType BaseType(I->getBaseClass(), 0);
5710 #ifndef NDEBUG
5711       // Non-virtual base classes are initialized in the order in the class
5712       // definition. We have already checked for virtual base classes.
5713       assert(!BaseIt->isVirtual() && "virtual base for literal type");
5714       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5715              "base class initializers not in expected order");
5716       ++BaseIt;
5717 #endif
5718       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
5719                                   BaseType->getAsCXXRecordDecl(), &Layout))
5720         return false;
5721       Value = &Result.getStructBase(BasesSeen++);
5722     } else if ((FD = I->getMember())) {
5723       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
5724         return false;
5725       if (RD->isUnion()) {
5726         Result = APValue(FD);
5727         Value = &Result.getUnionValue();
5728       } else {
5729         SkipToField(FD, false);
5730         Value = &Result.getStructField(FD->getFieldIndex());
5731       }
5732     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
5733       // Walk the indirect field decl's chain to find the object to initialize,
5734       // and make sure we've initialized every step along it.
5735       auto IndirectFieldChain = IFD->chain();
5736       for (auto *C : IndirectFieldChain) {
5737         FD = cast<FieldDecl>(C);
5738         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5739         // Switch the union field if it differs. This happens if we had
5740         // preceding zero-initialization, and we're now initializing a union
5741         // subobject other than the first.
5742         // FIXME: In this case, the values of the other subobjects are
5743         // specified, since zero-initialization sets all padding bits to zero.
5744         if (!Value->hasValue() ||
5745             (Value->isUnion() && Value->getUnionField() != FD)) {
5746           if (CD->isUnion())
5747             *Value = APValue(FD);
5748           else
5749             // FIXME: This immediately starts the lifetime of all members of an
5750             // anonymous struct. It would be preferable to strictly start member
5751             // lifetime in initialization order.
5752             *Value = getDefaultInitValue(Info.Ctx.getRecordType(CD));
5753         }
5754         // Store Subobject as its parent before updating it for the last element
5755         // in the chain.
5756         if (C == IndirectFieldChain.back())
5757           SubobjectParent = Subobject;
5758         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
5759           return false;
5760         if (CD->isUnion())
5761           Value = &Value->getUnionValue();
5762         else {
5763           if (C == IndirectFieldChain.front() && !RD->isUnion())
5764             SkipToField(FD, true);
5765           Value = &Value->getStructField(FD->getFieldIndex());
5766         }
5767       }
5768     } else {
5769       llvm_unreachable("unknown base initializer kind");
5770     }
5771 
5772     // Need to override This for implicit field initializers as in this case
5773     // This refers to innermost anonymous struct/union containing initializer,
5774     // not to currently constructed class.
5775     const Expr *Init = I->getInit();
5776     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
5777                                   isa<CXXDefaultInitExpr>(Init));
5778     FullExpressionRAII InitScope(Info);
5779     if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
5780         (FD && FD->isBitField() &&
5781          !truncateBitfieldValue(Info, Init, *Value, FD))) {
5782       // If we're checking for a potential constant expression, evaluate all
5783       // initializers even if some of them fail.
5784       if (!Info.noteFailure())
5785         return false;
5786       Success = false;
5787     }
5788 
5789     // This is the point at which the dynamic type of the object becomes this
5790     // class type.
5791     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
5792       EvalObj.finishedConstructingBases();
5793   }
5794 
5795   // Default-initialize any remaining fields.
5796   if (!RD->isUnion()) {
5797     for (; FieldIt != RD->field_end(); ++FieldIt) {
5798       if (!FieldIt->isUnnamedBitfield())
5799         Result.getStructField(FieldIt->getFieldIndex()) =
5800             getDefaultInitValue(FieldIt->getType());
5801     }
5802   }
5803 
5804   EvalObj.finishedConstructingFields();
5805 
5806   return Success &&
5807          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
5808          LifetimeExtendedScope.destroy();
5809 }
5810 
5811 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5812                                   ArrayRef<const Expr*> Args,
5813                                   const CXXConstructorDecl *Definition,
5814                                   EvalInfo &Info, APValue &Result) {
5815   ArgVector ArgValues(Args.size());
5816   if (!EvaluateArgs(Args, ArgValues, Info, Definition))
5817     return false;
5818 
5819   return HandleConstructorCall(E, This, ArgValues.data(), Definition,
5820                                Info, Result);
5821 }
5822 
5823 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
5824                                   const LValue &This, APValue &Value,
5825                                   QualType T) {
5826   // Objects can only be destroyed while they're within their lifetimes.
5827   // FIXME: We have no representation for whether an object of type nullptr_t
5828   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
5829   // as indeterminate instead?
5830   if (Value.isAbsent() && !T->isNullPtrType()) {
5831     APValue Printable;
5832     This.moveInto(Printable);
5833     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
5834       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
5835     return false;
5836   }
5837 
5838   // Invent an expression for location purposes.
5839   // FIXME: We shouldn't need to do this.
5840   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue);
5841 
5842   // For arrays, destroy elements right-to-left.
5843   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
5844     uint64_t Size = CAT->getSize().getZExtValue();
5845     QualType ElemT = CAT->getElementType();
5846 
5847     LValue ElemLV = This;
5848     ElemLV.addArray(Info, &LocE, CAT);
5849     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
5850       return false;
5851 
5852     // Ensure that we have actual array elements available to destroy; the
5853     // destructors might mutate the value, so we can't run them on the array
5854     // filler.
5855     if (Size && Size > Value.getArrayInitializedElts())
5856       expandArray(Value, Value.getArraySize() - 1);
5857 
5858     for (; Size != 0; --Size) {
5859       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
5860       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
5861           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
5862         return false;
5863     }
5864 
5865     // End the lifetime of this array now.
5866     Value = APValue();
5867     return true;
5868   }
5869 
5870   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
5871   if (!RD) {
5872     if (T.isDestructedType()) {
5873       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
5874       return false;
5875     }
5876 
5877     Value = APValue();
5878     return true;
5879   }
5880 
5881   if (RD->getNumVBases()) {
5882     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5883     return false;
5884   }
5885 
5886   const CXXDestructorDecl *DD = RD->getDestructor();
5887   if (!DD && !RD->hasTrivialDestructor()) {
5888     Info.FFDiag(CallLoc);
5889     return false;
5890   }
5891 
5892   if (!DD || DD->isTrivial() ||
5893       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
5894     // A trivial destructor just ends the lifetime of the object. Check for
5895     // this case before checking for a body, because we might not bother
5896     // building a body for a trivial destructor. Note that it doesn't matter
5897     // whether the destructor is constexpr in this case; all trivial
5898     // destructors are constexpr.
5899     //
5900     // If an anonymous union would be destroyed, some enclosing destructor must
5901     // have been explicitly defined, and the anonymous union destruction should
5902     // have no effect.
5903     Value = APValue();
5904     return true;
5905   }
5906 
5907   if (!Info.CheckCallLimit(CallLoc))
5908     return false;
5909 
5910   const FunctionDecl *Definition = nullptr;
5911   const Stmt *Body = DD->getBody(Definition);
5912 
5913   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
5914     return false;
5915 
5916   CallStackFrame Frame(Info, CallLoc, Definition, &This, nullptr);
5917 
5918   // We're now in the period of destruction of this object.
5919   unsigned BasesLeft = RD->getNumBases();
5920   EvalInfo::EvaluatingDestructorRAII EvalObj(
5921       Info,
5922       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
5923   if (!EvalObj.DidInsert) {
5924     // C++2a [class.dtor]p19:
5925     //   the behavior is undefined if the destructor is invoked for an object
5926     //   whose lifetime has ended
5927     // (Note that formally the lifetime ends when the period of destruction
5928     // begins, even though certain uses of the object remain valid until the
5929     // period of destruction ends.)
5930     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
5931     return false;
5932   }
5933 
5934   // FIXME: Creating an APValue just to hold a nonexistent return value is
5935   // wasteful.
5936   APValue RetVal;
5937   StmtResult Ret = {RetVal, nullptr};
5938   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
5939     return false;
5940 
5941   // A union destructor does not implicitly destroy its members.
5942   if (RD->isUnion())
5943     return true;
5944 
5945   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5946 
5947   // We don't have a good way to iterate fields in reverse, so collect all the
5948   // fields first and then walk them backwards.
5949   SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
5950   for (const FieldDecl *FD : llvm::reverse(Fields)) {
5951     if (FD->isUnnamedBitfield())
5952       continue;
5953 
5954     LValue Subobject = This;
5955     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
5956       return false;
5957 
5958     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
5959     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
5960                                FD->getType()))
5961       return false;
5962   }
5963 
5964   if (BasesLeft != 0)
5965     EvalObj.startedDestroyingBases();
5966 
5967   // Destroy base classes in reverse order.
5968   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
5969     --BasesLeft;
5970 
5971     QualType BaseType = Base.getType();
5972     LValue Subobject = This;
5973     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
5974                                 BaseType->getAsCXXRecordDecl(), &Layout))
5975       return false;
5976 
5977     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
5978     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
5979                                BaseType))
5980       return false;
5981   }
5982   assert(BasesLeft == 0 && "NumBases was wrong?");
5983 
5984   // The period of destruction ends now. The object is gone.
5985   Value = APValue();
5986   return true;
5987 }
5988 
5989 namespace {
5990 struct DestroyObjectHandler {
5991   EvalInfo &Info;
5992   const Expr *E;
5993   const LValue &This;
5994   const AccessKinds AccessKind;
5995 
5996   typedef bool result_type;
5997   bool failed() { return false; }
5998   bool found(APValue &Subobj, QualType SubobjType) {
5999     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6000                                  SubobjType);
6001   }
6002   bool found(APSInt &Value, QualType SubobjType) {
6003     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6004     return false;
6005   }
6006   bool found(APFloat &Value, QualType SubobjType) {
6007     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6008     return false;
6009   }
6010 };
6011 }
6012 
6013 /// Perform a destructor or pseudo-destructor call on the given object, which
6014 /// might in general not be a complete object.
6015 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6016                               const LValue &This, QualType ThisType) {
6017   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6018   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6019   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6020 }
6021 
6022 /// Destroy and end the lifetime of the given complete object.
6023 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6024                               APValue::LValueBase LVBase, APValue &Value,
6025                               QualType T) {
6026   // If we've had an unmodeled side-effect, we can't rely on mutable state
6027   // (such as the object we're about to destroy) being correct.
6028   if (Info.EvalStatus.HasSideEffects)
6029     return false;
6030 
6031   LValue LV;
6032   LV.set({LVBase});
6033   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6034 }
6035 
6036 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6037 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6038                                   LValue &Result) {
6039   if (Info.checkingPotentialConstantExpression() ||
6040       Info.SpeculativeEvaluationDepth)
6041     return false;
6042 
6043   // This is permitted only within a call to std::allocator<T>::allocate.
6044   auto Caller = Info.getStdAllocatorCaller("allocate");
6045   if (!Caller) {
6046     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus2a
6047                                      ? diag::note_constexpr_new_untyped
6048                                      : diag::note_constexpr_new);
6049     return false;
6050   }
6051 
6052   QualType ElemType = Caller.ElemType;
6053   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6054     Info.FFDiag(E->getExprLoc(),
6055                 diag::note_constexpr_new_not_complete_object_type)
6056         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6057     return false;
6058   }
6059 
6060   APSInt ByteSize;
6061   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6062     return false;
6063   bool IsNothrow = false;
6064   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6065     EvaluateIgnoredValue(Info, E->getArg(I));
6066     IsNothrow |= E->getType()->isNothrowT();
6067   }
6068 
6069   CharUnits ElemSize;
6070   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6071     return false;
6072   APInt Size, Remainder;
6073   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6074   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6075   if (Remainder != 0) {
6076     // This likely indicates a bug in the implementation of 'std::allocator'.
6077     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6078         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6079     return false;
6080   }
6081 
6082   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6083     if (IsNothrow) {
6084       Result.setNull(Info.Ctx, E->getType());
6085       return true;
6086     }
6087 
6088     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6089     return false;
6090   }
6091 
6092   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6093                                                      ArrayType::Normal, 0);
6094   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6095   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6096   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6097   return true;
6098 }
6099 
6100 static bool hasVirtualDestructor(QualType T) {
6101   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6102     if (CXXDestructorDecl *DD = RD->getDestructor())
6103       return DD->isVirtual();
6104   return false;
6105 }
6106 
6107 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6108   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6109     if (CXXDestructorDecl *DD = RD->getDestructor())
6110       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6111   return nullptr;
6112 }
6113 
6114 /// Check that the given object is a suitable pointer to a heap allocation that
6115 /// still exists and is of the right kind for the purpose of a deletion.
6116 ///
6117 /// On success, returns the heap allocation to deallocate. On failure, produces
6118 /// a diagnostic and returns None.
6119 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6120                                             const LValue &Pointer,
6121                                             DynAlloc::Kind DeallocKind) {
6122   auto PointerAsString = [&] {
6123     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6124   };
6125 
6126   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6127   if (!DA) {
6128     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6129         << PointerAsString();
6130     if (Pointer.Base)
6131       NoteLValueLocation(Info, Pointer.Base);
6132     return None;
6133   }
6134 
6135   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6136   if (!Alloc) {
6137     Info.FFDiag(E, diag::note_constexpr_double_delete);
6138     return None;
6139   }
6140 
6141   QualType AllocType = Pointer.Base.getDynamicAllocType();
6142   if (DeallocKind != (*Alloc)->getKind()) {
6143     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6144         << DeallocKind << (*Alloc)->getKind() << AllocType;
6145     NoteLValueLocation(Info, Pointer.Base);
6146     return None;
6147   }
6148 
6149   bool Subobject = false;
6150   if (DeallocKind == DynAlloc::New) {
6151     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6152                 Pointer.Designator.isOnePastTheEnd();
6153   } else {
6154     Subobject = Pointer.Designator.Entries.size() != 1 ||
6155                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6156   }
6157   if (Subobject) {
6158     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6159         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6160     return None;
6161   }
6162 
6163   return Alloc;
6164 }
6165 
6166 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6167 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6168   if (Info.checkingPotentialConstantExpression() ||
6169       Info.SpeculativeEvaluationDepth)
6170     return false;
6171 
6172   // This is permitted only within a call to std::allocator<T>::deallocate.
6173   if (!Info.getStdAllocatorCaller("deallocate")) {
6174     Info.FFDiag(E->getExprLoc());
6175     return true;
6176   }
6177 
6178   LValue Pointer;
6179   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6180     return false;
6181   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6182     EvaluateIgnoredValue(Info, E->getArg(I));
6183 
6184   if (Pointer.Designator.Invalid)
6185     return false;
6186 
6187   // Deleting a null pointer has no effect.
6188   if (Pointer.isNullPointer())
6189     return true;
6190 
6191   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6192     return false;
6193 
6194   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6195   return true;
6196 }
6197 
6198 //===----------------------------------------------------------------------===//
6199 // Generic Evaluation
6200 //===----------------------------------------------------------------------===//
6201 namespace {
6202 
6203 class BitCastBuffer {
6204   // FIXME: We're going to need bit-level granularity when we support
6205   // bit-fields.
6206   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6207   // we don't support a host or target where that is the case. Still, we should
6208   // use a more generic type in case we ever do.
6209   SmallVector<Optional<unsigned char>, 32> Bytes;
6210 
6211   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6212                 "Need at least 8 bit unsigned char");
6213 
6214   bool TargetIsLittleEndian;
6215 
6216 public:
6217   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6218       : Bytes(Width.getQuantity()),
6219         TargetIsLittleEndian(TargetIsLittleEndian) {}
6220 
6221   LLVM_NODISCARD
6222   bool readObject(CharUnits Offset, CharUnits Width,
6223                   SmallVectorImpl<unsigned char> &Output) const {
6224     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6225       // If a byte of an integer is uninitialized, then the whole integer is
6226       // uninitalized.
6227       if (!Bytes[I.getQuantity()])
6228         return false;
6229       Output.push_back(*Bytes[I.getQuantity()]);
6230     }
6231     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6232       std::reverse(Output.begin(), Output.end());
6233     return true;
6234   }
6235 
6236   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6237     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6238       std::reverse(Input.begin(), Input.end());
6239 
6240     size_t Index = 0;
6241     for (unsigned char Byte : Input) {
6242       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6243       Bytes[Offset.getQuantity() + Index] = Byte;
6244       ++Index;
6245     }
6246   }
6247 
6248   size_t size() { return Bytes.size(); }
6249 };
6250 
6251 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6252 /// target would represent the value at runtime.
6253 class APValueToBufferConverter {
6254   EvalInfo &Info;
6255   BitCastBuffer Buffer;
6256   const CastExpr *BCE;
6257 
6258   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6259                            const CastExpr *BCE)
6260       : Info(Info),
6261         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6262         BCE(BCE) {}
6263 
6264   bool visit(const APValue &Val, QualType Ty) {
6265     return visit(Val, Ty, CharUnits::fromQuantity(0));
6266   }
6267 
6268   // Write out Val with type Ty into Buffer starting at Offset.
6269   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6270     assert((size_t)Offset.getQuantity() <= Buffer.size());
6271 
6272     // As a special case, nullptr_t has an indeterminate value.
6273     if (Ty->isNullPtrType())
6274       return true;
6275 
6276     // Dig through Src to find the byte at SrcOffset.
6277     switch (Val.getKind()) {
6278     case APValue::Indeterminate:
6279     case APValue::None:
6280       return true;
6281 
6282     case APValue::Int:
6283       return visitInt(Val.getInt(), Ty, Offset);
6284     case APValue::Float:
6285       return visitFloat(Val.getFloat(), Ty, Offset);
6286     case APValue::Array:
6287       return visitArray(Val, Ty, Offset);
6288     case APValue::Struct:
6289       return visitRecord(Val, Ty, Offset);
6290 
6291     case APValue::ComplexInt:
6292     case APValue::ComplexFloat:
6293     case APValue::Vector:
6294     case APValue::FixedPoint:
6295       // FIXME: We should support these.
6296 
6297     case APValue::Union:
6298     case APValue::MemberPointer:
6299     case APValue::AddrLabelDiff: {
6300       Info.FFDiag(BCE->getBeginLoc(),
6301                   diag::note_constexpr_bit_cast_unsupported_type)
6302           << Ty;
6303       return false;
6304     }
6305 
6306     case APValue::LValue:
6307       llvm_unreachable("LValue subobject in bit_cast?");
6308     }
6309     llvm_unreachable("Unhandled APValue::ValueKind");
6310   }
6311 
6312   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6313     const RecordDecl *RD = Ty->getAsRecordDecl();
6314     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6315 
6316     // Visit the base classes.
6317     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6318       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6319         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6320         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6321 
6322         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6323                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6324           return false;
6325       }
6326     }
6327 
6328     // Visit the fields.
6329     unsigned FieldIdx = 0;
6330     for (FieldDecl *FD : RD->fields()) {
6331       if (FD->isBitField()) {
6332         Info.FFDiag(BCE->getBeginLoc(),
6333                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6334         return false;
6335       }
6336 
6337       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6338 
6339       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6340              "only bit-fields can have sub-char alignment");
6341       CharUnits FieldOffset =
6342           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6343       QualType FieldTy = FD->getType();
6344       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6345         return false;
6346       ++FieldIdx;
6347     }
6348 
6349     return true;
6350   }
6351 
6352   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6353     const auto *CAT =
6354         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6355     if (!CAT)
6356       return false;
6357 
6358     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6359     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6360     unsigned ArraySize = Val.getArraySize();
6361     // First, initialize the initialized elements.
6362     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6363       const APValue &SubObj = Val.getArrayInitializedElt(I);
6364       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6365         return false;
6366     }
6367 
6368     // Next, initialize the rest of the array using the filler.
6369     if (Val.hasArrayFiller()) {
6370       const APValue &Filler = Val.getArrayFiller();
6371       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6372         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6373           return false;
6374       }
6375     }
6376 
6377     return true;
6378   }
6379 
6380   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6381     CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
6382     SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
6383     llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
6384     Buffer.writeObject(Offset, Bytes);
6385     return true;
6386   }
6387 
6388   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6389     APSInt AsInt(Val.bitcastToAPInt());
6390     return visitInt(AsInt, Ty, Offset);
6391   }
6392 
6393 public:
6394   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6395                                          const CastExpr *BCE) {
6396     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6397     APValueToBufferConverter Converter(Info, DstSize, BCE);
6398     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6399       return None;
6400     return Converter.Buffer;
6401   }
6402 };
6403 
6404 /// Write an BitCastBuffer into an APValue.
6405 class BufferToAPValueConverter {
6406   EvalInfo &Info;
6407   const BitCastBuffer &Buffer;
6408   const CastExpr *BCE;
6409 
6410   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6411                            const CastExpr *BCE)
6412       : Info(Info), Buffer(Buffer), BCE(BCE) {}
6413 
6414   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6415   // with an invalid type, so anything left is a deficiency on our part (FIXME).
6416   // Ideally this will be unreachable.
6417   llvm::NoneType unsupportedType(QualType Ty) {
6418     Info.FFDiag(BCE->getBeginLoc(),
6419                 diag::note_constexpr_bit_cast_unsupported_type)
6420         << Ty;
6421     return None;
6422   }
6423 
6424   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6425                           const EnumType *EnumSugar = nullptr) {
6426     if (T->isNullPtrType()) {
6427       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6428       return APValue((Expr *)nullptr,
6429                      /*Offset=*/CharUnits::fromQuantity(NullValue),
6430                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6431     }
6432 
6433     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6434     SmallVector<uint8_t, 8> Bytes;
6435     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
6436       // If this is std::byte or unsigned char, then its okay to store an
6437       // indeterminate value.
6438       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
6439       bool IsUChar =
6440           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
6441                          T->isSpecificBuiltinType(BuiltinType::Char_U));
6442       if (!IsStdByte && !IsUChar) {
6443         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
6444         Info.FFDiag(BCE->getExprLoc(),
6445                     diag::note_constexpr_bit_cast_indet_dest)
6446             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
6447         return None;
6448       }
6449 
6450       return APValue::IndeterminateValue();
6451     }
6452 
6453     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
6454     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
6455 
6456     if (T->isIntegralOrEnumerationType()) {
6457       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
6458       return APValue(Val);
6459     }
6460 
6461     if (T->isRealFloatingType()) {
6462       const llvm::fltSemantics &Semantics =
6463           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6464       return APValue(APFloat(Semantics, Val));
6465     }
6466 
6467     return unsupportedType(QualType(T, 0));
6468   }
6469 
6470   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
6471     const RecordDecl *RD = RTy->getAsRecordDecl();
6472     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6473 
6474     unsigned NumBases = 0;
6475     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6476       NumBases = CXXRD->getNumBases();
6477 
6478     APValue ResultVal(APValue::UninitStruct(), NumBases,
6479                       std::distance(RD->field_begin(), RD->field_end()));
6480 
6481     // Visit the base classes.
6482     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6483       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6484         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6485         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6486         if (BaseDecl->isEmpty() ||
6487             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
6488           continue;
6489 
6490         Optional<APValue> SubObj = visitType(
6491             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
6492         if (!SubObj)
6493           return None;
6494         ResultVal.getStructBase(I) = *SubObj;
6495       }
6496     }
6497 
6498     // Visit the fields.
6499     unsigned FieldIdx = 0;
6500     for (FieldDecl *FD : RD->fields()) {
6501       // FIXME: We don't currently support bit-fields. A lot of the logic for
6502       // this is in CodeGen, so we need to factor it around.
6503       if (FD->isBitField()) {
6504         Info.FFDiag(BCE->getBeginLoc(),
6505                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6506         return None;
6507       }
6508 
6509       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6510       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
6511 
6512       CharUnits FieldOffset =
6513           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
6514           Offset;
6515       QualType FieldTy = FD->getType();
6516       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
6517       if (!SubObj)
6518         return None;
6519       ResultVal.getStructField(FieldIdx) = *SubObj;
6520       ++FieldIdx;
6521     }
6522 
6523     return ResultVal;
6524   }
6525 
6526   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
6527     QualType RepresentationType = Ty->getDecl()->getIntegerType();
6528     assert(!RepresentationType.isNull() &&
6529            "enum forward decl should be caught by Sema");
6530     const auto *AsBuiltin =
6531         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
6532     // Recurse into the underlying type. Treat std::byte transparently as
6533     // unsigned char.
6534     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
6535   }
6536 
6537   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
6538     size_t Size = Ty->getSize().getLimitedValue();
6539     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
6540 
6541     APValue ArrayValue(APValue::UninitArray(), Size, Size);
6542     for (size_t I = 0; I != Size; ++I) {
6543       Optional<APValue> ElementValue =
6544           visitType(Ty->getElementType(), Offset + I * ElementWidth);
6545       if (!ElementValue)
6546         return None;
6547       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
6548     }
6549 
6550     return ArrayValue;
6551   }
6552 
6553   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
6554     return unsupportedType(QualType(Ty, 0));
6555   }
6556 
6557   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
6558     QualType Can = Ty.getCanonicalType();
6559 
6560     switch (Can->getTypeClass()) {
6561 #define TYPE(Class, Base)                                                      \
6562   case Type::Class:                                                            \
6563     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
6564 #define ABSTRACT_TYPE(Class, Base)
6565 #define NON_CANONICAL_TYPE(Class, Base)                                        \
6566   case Type::Class:                                                            \
6567     llvm_unreachable("non-canonical type should be impossible!");
6568 #define DEPENDENT_TYPE(Class, Base)                                            \
6569   case Type::Class:                                                            \
6570     llvm_unreachable(                                                          \
6571         "dependent types aren't supported in the constant evaluator!");
6572 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
6573   case Type::Class:                                                            \
6574     llvm_unreachable("either dependent or not canonical!");
6575 #include "clang/AST/TypeNodes.inc"
6576     }
6577     llvm_unreachable("Unhandled Type::TypeClass");
6578   }
6579 
6580 public:
6581   // Pull out a full value of type DstType.
6582   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
6583                                    const CastExpr *BCE) {
6584     BufferToAPValueConverter Converter(Info, Buffer, BCE);
6585     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
6586   }
6587 };
6588 
6589 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
6590                                                  QualType Ty, EvalInfo *Info,
6591                                                  const ASTContext &Ctx,
6592                                                  bool CheckingDest) {
6593   Ty = Ty.getCanonicalType();
6594 
6595   auto diag = [&](int Reason) {
6596     if (Info)
6597       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
6598           << CheckingDest << (Reason == 4) << Reason;
6599     return false;
6600   };
6601   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
6602     if (Info)
6603       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
6604           << NoteTy << Construct << Ty;
6605     return false;
6606   };
6607 
6608   if (Ty->isUnionType())
6609     return diag(0);
6610   if (Ty->isPointerType())
6611     return diag(1);
6612   if (Ty->isMemberPointerType())
6613     return diag(2);
6614   if (Ty.isVolatileQualified())
6615     return diag(3);
6616 
6617   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
6618     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
6619       for (CXXBaseSpecifier &BS : CXXRD->bases())
6620         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
6621                                                   CheckingDest))
6622           return note(1, BS.getType(), BS.getBeginLoc());
6623     }
6624     for (FieldDecl *FD : Record->fields()) {
6625       if (FD->getType()->isReferenceType())
6626         return diag(4);
6627       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
6628                                                 CheckingDest))
6629         return note(0, FD->getType(), FD->getBeginLoc());
6630     }
6631   }
6632 
6633   if (Ty->isArrayType() &&
6634       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
6635                                             Info, Ctx, CheckingDest))
6636     return false;
6637 
6638   return true;
6639 }
6640 
6641 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
6642                                              const ASTContext &Ctx,
6643                                              const CastExpr *BCE) {
6644   bool DestOK = checkBitCastConstexprEligibilityType(
6645       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
6646   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
6647                                 BCE->getBeginLoc(),
6648                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
6649   return SourceOK;
6650 }
6651 
6652 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
6653                                         APValue &SourceValue,
6654                                         const CastExpr *BCE) {
6655   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
6656          "no host or target supports non 8-bit chars");
6657   assert(SourceValue.isLValue() &&
6658          "LValueToRValueBitcast requires an lvalue operand!");
6659 
6660   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
6661     return false;
6662 
6663   LValue SourceLValue;
6664   APValue SourceRValue;
6665   SourceLValue.setFrom(Info.Ctx, SourceValue);
6666   if (!handleLValueToRValueConversion(
6667           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
6668           SourceRValue, /*WantObjectRepresentation=*/true))
6669     return false;
6670 
6671   // Read out SourceValue into a char buffer.
6672   Optional<BitCastBuffer> Buffer =
6673       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
6674   if (!Buffer)
6675     return false;
6676 
6677   // Write out the buffer into a new APValue.
6678   Optional<APValue> MaybeDestValue =
6679       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
6680   if (!MaybeDestValue)
6681     return false;
6682 
6683   DestValue = std::move(*MaybeDestValue);
6684   return true;
6685 }
6686 
6687 template <class Derived>
6688 class ExprEvaluatorBase
6689   : public ConstStmtVisitor<Derived, bool> {
6690 private:
6691   Derived &getDerived() { return static_cast<Derived&>(*this); }
6692   bool DerivedSuccess(const APValue &V, const Expr *E) {
6693     return getDerived().Success(V, E);
6694   }
6695   bool DerivedZeroInitialization(const Expr *E) {
6696     return getDerived().ZeroInitialization(E);
6697   }
6698 
6699   // Check whether a conditional operator with a non-constant condition is a
6700   // potential constant expression. If neither arm is a potential constant
6701   // expression, then the conditional operator is not either.
6702   template<typename ConditionalOperator>
6703   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
6704     assert(Info.checkingPotentialConstantExpression());
6705 
6706     // Speculatively evaluate both arms.
6707     SmallVector<PartialDiagnosticAt, 8> Diag;
6708     {
6709       SpeculativeEvaluationRAII Speculate(Info, &Diag);
6710       StmtVisitorTy::Visit(E->getFalseExpr());
6711       if (Diag.empty())
6712         return;
6713     }
6714 
6715     {
6716       SpeculativeEvaluationRAII Speculate(Info, &Diag);
6717       Diag.clear();
6718       StmtVisitorTy::Visit(E->getTrueExpr());
6719       if (Diag.empty())
6720         return;
6721     }
6722 
6723     Error(E, diag::note_constexpr_conditional_never_const);
6724   }
6725 
6726 
6727   template<typename ConditionalOperator>
6728   bool HandleConditionalOperator(const ConditionalOperator *E) {
6729     bool BoolResult;
6730     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
6731       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
6732         CheckPotentialConstantConditional(E);
6733         return false;
6734       }
6735       if (Info.noteFailure()) {
6736         StmtVisitorTy::Visit(E->getTrueExpr());
6737         StmtVisitorTy::Visit(E->getFalseExpr());
6738       }
6739       return false;
6740     }
6741 
6742     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
6743     return StmtVisitorTy::Visit(EvalExpr);
6744   }
6745 
6746 protected:
6747   EvalInfo &Info;
6748   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
6749   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
6750 
6751   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6752     return Info.CCEDiag(E, D);
6753   }
6754 
6755   bool ZeroInitialization(const Expr *E) { return Error(E); }
6756 
6757 public:
6758   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
6759 
6760   EvalInfo &getEvalInfo() { return Info; }
6761 
6762   /// Report an evaluation error. This should only be called when an error is
6763   /// first discovered. When propagating an error, just return false.
6764   bool Error(const Expr *E, diag::kind D) {
6765     Info.FFDiag(E, D);
6766     return false;
6767   }
6768   bool Error(const Expr *E) {
6769     return Error(E, diag::note_invalid_subexpr_in_const_expr);
6770   }
6771 
6772   bool VisitStmt(const Stmt *) {
6773     llvm_unreachable("Expression evaluator should not be called on stmts");
6774   }
6775   bool VisitExpr(const Expr *E) {
6776     return Error(E);
6777   }
6778 
6779   bool VisitConstantExpr(const ConstantExpr *E) {
6780     if (E->hasAPValueResult())
6781       return DerivedSuccess(E->getAPValueResult(), E);
6782 
6783     return StmtVisitorTy::Visit(E->getSubExpr());
6784   }
6785 
6786   bool VisitParenExpr(const ParenExpr *E)
6787     { return StmtVisitorTy::Visit(E->getSubExpr()); }
6788   bool VisitUnaryExtension(const UnaryOperator *E)
6789     { return StmtVisitorTy::Visit(E->getSubExpr()); }
6790   bool VisitUnaryPlus(const UnaryOperator *E)
6791     { return StmtVisitorTy::Visit(E->getSubExpr()); }
6792   bool VisitChooseExpr(const ChooseExpr *E)
6793     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
6794   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
6795     { return StmtVisitorTy::Visit(E->getResultExpr()); }
6796   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
6797     { return StmtVisitorTy::Visit(E->getReplacement()); }
6798   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
6799     TempVersionRAII RAII(*Info.CurrentCall);
6800     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
6801     return StmtVisitorTy::Visit(E->getExpr());
6802   }
6803   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
6804     TempVersionRAII RAII(*Info.CurrentCall);
6805     // The initializer may not have been parsed yet, or might be erroneous.
6806     if (!E->getExpr())
6807       return Error(E);
6808     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
6809     return StmtVisitorTy::Visit(E->getExpr());
6810   }
6811 
6812   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
6813     FullExpressionRAII Scope(Info);
6814     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
6815   }
6816 
6817   // Temporaries are registered when created, so we don't care about
6818   // CXXBindTemporaryExpr.
6819   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
6820     return StmtVisitorTy::Visit(E->getSubExpr());
6821   }
6822 
6823   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
6824     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
6825     return static_cast<Derived*>(this)->VisitCastExpr(E);
6826   }
6827   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
6828     if (!Info.Ctx.getLangOpts().CPlusPlus2a)
6829       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
6830     return static_cast<Derived*>(this)->VisitCastExpr(E);
6831   }
6832   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
6833     return static_cast<Derived*>(this)->VisitCastExpr(E);
6834   }
6835 
6836   bool VisitBinaryOperator(const BinaryOperator *E) {
6837     switch (E->getOpcode()) {
6838     default:
6839       return Error(E);
6840 
6841     case BO_Comma:
6842       VisitIgnoredValue(E->getLHS());
6843       return StmtVisitorTy::Visit(E->getRHS());
6844 
6845     case BO_PtrMemD:
6846     case BO_PtrMemI: {
6847       LValue Obj;
6848       if (!HandleMemberPointerAccess(Info, E, Obj))
6849         return false;
6850       APValue Result;
6851       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
6852         return false;
6853       return DerivedSuccess(Result, E);
6854     }
6855     }
6856   }
6857 
6858   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
6859     return StmtVisitorTy::Visit(E->getSemanticForm());
6860   }
6861 
6862   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
6863     // Evaluate and cache the common expression. We treat it as a temporary,
6864     // even though it's not quite the same thing.
6865     LValue CommonLV;
6866     if (!Evaluate(Info.CurrentCall->createTemporary(
6867                       E->getOpaqueValue(),
6868                       getStorageType(Info.Ctx, E->getOpaqueValue()), false,
6869                       CommonLV),
6870                   Info, E->getCommon()))
6871       return false;
6872 
6873     return HandleConditionalOperator(E);
6874   }
6875 
6876   bool VisitConditionalOperator(const ConditionalOperator *E) {
6877     bool IsBcpCall = false;
6878     // If the condition (ignoring parens) is a __builtin_constant_p call,
6879     // the result is a constant expression if it can be folded without
6880     // side-effects. This is an important GNU extension. See GCC PR38377
6881     // for discussion.
6882     if (const CallExpr *CallCE =
6883           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
6884       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
6885         IsBcpCall = true;
6886 
6887     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
6888     // constant expression; we can't check whether it's potentially foldable.
6889     // FIXME: We should instead treat __builtin_constant_p as non-constant if
6890     // it would return 'false' in this mode.
6891     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
6892       return false;
6893 
6894     FoldConstant Fold(Info, IsBcpCall);
6895     if (!HandleConditionalOperator(E)) {
6896       Fold.keepDiagnostics();
6897       return false;
6898     }
6899 
6900     return true;
6901   }
6902 
6903   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
6904     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
6905       return DerivedSuccess(*Value, E);
6906 
6907     const Expr *Source = E->getSourceExpr();
6908     if (!Source)
6909       return Error(E);
6910     if (Source == E) { // sanity checking.
6911       assert(0 && "OpaqueValueExpr recursively refers to itself");
6912       return Error(E);
6913     }
6914     return StmtVisitorTy::Visit(Source);
6915   }
6916 
6917   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
6918     for (const Expr *SemE : E->semantics()) {
6919       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
6920         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
6921         // result expression: there could be two different LValues that would
6922         // refer to the same object in that case, and we can't model that.
6923         if (SemE == E->getResultExpr())
6924           return Error(E);
6925 
6926         // Unique OVEs get evaluated if and when we encounter them when
6927         // emitting the rest of the semantic form, rather than eagerly.
6928         if (OVE->isUnique())
6929           continue;
6930 
6931         LValue LV;
6932         if (!Evaluate(Info.CurrentCall->createTemporary(
6933                           OVE, getStorageType(Info.Ctx, OVE), false, LV),
6934                       Info, OVE->getSourceExpr()))
6935           return false;
6936       } else if (SemE == E->getResultExpr()) {
6937         if (!StmtVisitorTy::Visit(SemE))
6938           return false;
6939       } else {
6940         if (!EvaluateIgnoredValue(Info, SemE))
6941           return false;
6942       }
6943     }
6944     return true;
6945   }
6946 
6947   bool VisitCallExpr(const CallExpr *E) {
6948     APValue Result;
6949     if (!handleCallExpr(E, Result, nullptr))
6950       return false;
6951     return DerivedSuccess(Result, E);
6952   }
6953 
6954   bool handleCallExpr(const CallExpr *E, APValue &Result,
6955                      const LValue *ResultSlot) {
6956     const Expr *Callee = E->getCallee()->IgnoreParens();
6957     QualType CalleeType = Callee->getType();
6958 
6959     const FunctionDecl *FD = nullptr;
6960     LValue *This = nullptr, ThisVal;
6961     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
6962     bool HasQualifier = false;
6963 
6964     // Extract function decl and 'this' pointer from the callee.
6965     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
6966       const CXXMethodDecl *Member = nullptr;
6967       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
6968         // Explicit bound member calls, such as x.f() or p->g();
6969         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
6970           return false;
6971         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
6972         if (!Member)
6973           return Error(Callee);
6974         This = &ThisVal;
6975         HasQualifier = ME->hasQualifier();
6976       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
6977         // Indirect bound member calls ('.*' or '->*').
6978         const ValueDecl *D =
6979             HandleMemberPointerAccess(Info, BE, ThisVal, false);
6980         if (!D)
6981           return false;
6982         Member = dyn_cast<CXXMethodDecl>(D);
6983         if (!Member)
6984           return Error(Callee);
6985         This = &ThisVal;
6986       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
6987         if (!Info.getLangOpts().CPlusPlus2a)
6988           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
6989         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
6990                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
6991       } else
6992         return Error(Callee);
6993       FD = Member;
6994     } else if (CalleeType->isFunctionPointerType()) {
6995       LValue Call;
6996       if (!EvaluatePointer(Callee, Call, Info))
6997         return false;
6998 
6999       if (!Call.getLValueOffset().isZero())
7000         return Error(Callee);
7001       FD = dyn_cast_or_null<FunctionDecl>(
7002                              Call.getLValueBase().dyn_cast<const ValueDecl*>());
7003       if (!FD)
7004         return Error(Callee);
7005       // Don't call function pointers which have been cast to some other type.
7006       // Per DR (no number yet), the caller and callee can differ in noexcept.
7007       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7008         CalleeType->getPointeeType(), FD->getType())) {
7009         return Error(E);
7010       }
7011 
7012       // Overloaded operator calls to member functions are represented as normal
7013       // calls with '*this' as the first argument.
7014       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7015       if (MD && !MD->isStatic()) {
7016         // FIXME: When selecting an implicit conversion for an overloaded
7017         // operator delete, we sometimes try to evaluate calls to conversion
7018         // operators without a 'this' parameter!
7019         if (Args.empty())
7020           return Error(E);
7021 
7022         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7023           return false;
7024         This = &ThisVal;
7025         Args = Args.slice(1);
7026       } else if (MD && MD->isLambdaStaticInvoker()) {
7027         // Map the static invoker for the lambda back to the call operator.
7028         // Conveniently, we don't have to slice out the 'this' argument (as is
7029         // being done for the non-static case), since a static member function
7030         // doesn't have an implicit argument passed in.
7031         const CXXRecordDecl *ClosureClass = MD->getParent();
7032         assert(
7033             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7034             "Number of captures must be zero for conversion to function-ptr");
7035 
7036         const CXXMethodDecl *LambdaCallOp =
7037             ClosureClass->getLambdaCallOperator();
7038 
7039         // Set 'FD', the function that will be called below, to the call
7040         // operator.  If the closure object represents a generic lambda, find
7041         // the corresponding specialization of the call operator.
7042 
7043         if (ClosureClass->isGenericLambda()) {
7044           assert(MD->isFunctionTemplateSpecialization() &&
7045                  "A generic lambda's static-invoker function must be a "
7046                  "template specialization");
7047           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7048           FunctionTemplateDecl *CallOpTemplate =
7049               LambdaCallOp->getDescribedFunctionTemplate();
7050           void *InsertPos = nullptr;
7051           FunctionDecl *CorrespondingCallOpSpecialization =
7052               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7053           assert(CorrespondingCallOpSpecialization &&
7054                  "We must always have a function call operator specialization "
7055                  "that corresponds to our static invoker specialization");
7056           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7057         } else
7058           FD = LambdaCallOp;
7059       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7060         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7061             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7062           LValue Ptr;
7063           if (!HandleOperatorNewCall(Info, E, Ptr))
7064             return false;
7065           Ptr.moveInto(Result);
7066           return true;
7067         } else {
7068           return HandleOperatorDeleteCall(Info, E);
7069         }
7070       }
7071     } else
7072       return Error(E);
7073 
7074     SmallVector<QualType, 4> CovariantAdjustmentPath;
7075     if (This) {
7076       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7077       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7078         // Perform virtual dispatch, if necessary.
7079         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7080                                    CovariantAdjustmentPath);
7081         if (!FD)
7082           return false;
7083       } else {
7084         // Check that the 'this' pointer points to an object of the right type.
7085         // FIXME: If this is an assignment operator call, we may need to change
7086         // the active union member before we check this.
7087         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7088           return false;
7089       }
7090     }
7091 
7092     // Destructor calls are different enough that they have their own codepath.
7093     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7094       assert(This && "no 'this' pointer for destructor call");
7095       return HandleDestruction(Info, E, *This,
7096                                Info.Ctx.getRecordType(DD->getParent()));
7097     }
7098 
7099     const FunctionDecl *Definition = nullptr;
7100     Stmt *Body = FD->getBody(Definition);
7101 
7102     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7103         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
7104                             Result, ResultSlot))
7105       return false;
7106 
7107     if (!CovariantAdjustmentPath.empty() &&
7108         !HandleCovariantReturnAdjustment(Info, E, Result,
7109                                          CovariantAdjustmentPath))
7110       return false;
7111 
7112     return true;
7113   }
7114 
7115   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7116     return StmtVisitorTy::Visit(E->getInitializer());
7117   }
7118   bool VisitInitListExpr(const InitListExpr *E) {
7119     if (E->getNumInits() == 0)
7120       return DerivedZeroInitialization(E);
7121     if (E->getNumInits() == 1)
7122       return StmtVisitorTy::Visit(E->getInit(0));
7123     return Error(E);
7124   }
7125   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7126     return DerivedZeroInitialization(E);
7127   }
7128   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7129     return DerivedZeroInitialization(E);
7130   }
7131   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7132     return DerivedZeroInitialization(E);
7133   }
7134 
7135   /// A member expression where the object is a prvalue is itself a prvalue.
7136   bool VisitMemberExpr(const MemberExpr *E) {
7137     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7138            "missing temporary materialization conversion");
7139     assert(!E->isArrow() && "missing call to bound member function?");
7140 
7141     APValue Val;
7142     if (!Evaluate(Val, Info, E->getBase()))
7143       return false;
7144 
7145     QualType BaseTy = E->getBase()->getType();
7146 
7147     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7148     if (!FD) return Error(E);
7149     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7150     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7151            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7152 
7153     // Note: there is no lvalue base here. But this case should only ever
7154     // happen in C or in C++98, where we cannot be evaluating a constexpr
7155     // constructor, which is the only case the base matters.
7156     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7157     SubobjectDesignator Designator(BaseTy);
7158     Designator.addDeclUnchecked(FD);
7159 
7160     APValue Result;
7161     return extractSubobject(Info, E, Obj, Designator, Result) &&
7162            DerivedSuccess(Result, E);
7163   }
7164 
7165   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7166     APValue Val;
7167     if (!Evaluate(Val, Info, E->getBase()))
7168       return false;
7169 
7170     if (Val.isVector()) {
7171       SmallVector<uint32_t, 4> Indices;
7172       E->getEncodedElementAccess(Indices);
7173       if (Indices.size() == 1) {
7174         // Return scalar.
7175         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7176       } else {
7177         // Construct new APValue vector.
7178         SmallVector<APValue, 4> Elts;
7179         for (unsigned I = 0; I < Indices.size(); ++I) {
7180           Elts.push_back(Val.getVectorElt(Indices[I]));
7181         }
7182         APValue VecResult(Elts.data(), Indices.size());
7183         return DerivedSuccess(VecResult, E);
7184       }
7185     }
7186 
7187     return false;
7188   }
7189 
7190   bool VisitCastExpr(const CastExpr *E) {
7191     switch (E->getCastKind()) {
7192     default:
7193       break;
7194 
7195     case CK_AtomicToNonAtomic: {
7196       APValue AtomicVal;
7197       // This does not need to be done in place even for class/array types:
7198       // atomic-to-non-atomic conversion implies copying the object
7199       // representation.
7200       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7201         return false;
7202       return DerivedSuccess(AtomicVal, E);
7203     }
7204 
7205     case CK_NoOp:
7206     case CK_UserDefinedConversion:
7207       return StmtVisitorTy::Visit(E->getSubExpr());
7208 
7209     case CK_LValueToRValue: {
7210       LValue LVal;
7211       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7212         return false;
7213       APValue RVal;
7214       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7215       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7216                                           LVal, RVal))
7217         return false;
7218       return DerivedSuccess(RVal, E);
7219     }
7220     case CK_LValueToRValueBitCast: {
7221       APValue DestValue, SourceValue;
7222       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7223         return false;
7224       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7225         return false;
7226       return DerivedSuccess(DestValue, E);
7227     }
7228 
7229     case CK_AddressSpaceConversion: {
7230       APValue Value;
7231       if (!Evaluate(Value, Info, E->getSubExpr()))
7232         return false;
7233       return DerivedSuccess(Value, E);
7234     }
7235     }
7236 
7237     return Error(E);
7238   }
7239 
7240   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7241     return VisitUnaryPostIncDec(UO);
7242   }
7243   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7244     return VisitUnaryPostIncDec(UO);
7245   }
7246   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7247     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7248       return Error(UO);
7249 
7250     LValue LVal;
7251     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7252       return false;
7253     APValue RVal;
7254     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7255                       UO->isIncrementOp(), &RVal))
7256       return false;
7257     return DerivedSuccess(RVal, UO);
7258   }
7259 
7260   bool VisitStmtExpr(const StmtExpr *E) {
7261     // We will have checked the full-expressions inside the statement expression
7262     // when they were completed, and don't need to check them again now.
7263     if (Info.checkingForUndefinedBehavior())
7264       return Error(E);
7265 
7266     const CompoundStmt *CS = E->getSubStmt();
7267     if (CS->body_empty())
7268       return true;
7269 
7270     BlockScopeRAII Scope(Info);
7271     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7272                                            BE = CS->body_end();
7273          /**/; ++BI) {
7274       if (BI + 1 == BE) {
7275         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7276         if (!FinalExpr) {
7277           Info.FFDiag((*BI)->getBeginLoc(),
7278                       diag::note_constexpr_stmt_expr_unsupported);
7279           return false;
7280         }
7281         return this->Visit(FinalExpr) && Scope.destroy();
7282       }
7283 
7284       APValue ReturnValue;
7285       StmtResult Result = { ReturnValue, nullptr };
7286       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7287       if (ESR != ESR_Succeeded) {
7288         // FIXME: If the statement-expression terminated due to 'return',
7289         // 'break', or 'continue', it would be nice to propagate that to
7290         // the outer statement evaluation rather than bailing out.
7291         if (ESR != ESR_Failed)
7292           Info.FFDiag((*BI)->getBeginLoc(),
7293                       diag::note_constexpr_stmt_expr_unsupported);
7294         return false;
7295       }
7296     }
7297 
7298     llvm_unreachable("Return from function from the loop above.");
7299   }
7300 
7301   /// Visit a value which is evaluated, but whose value is ignored.
7302   void VisitIgnoredValue(const Expr *E) {
7303     EvaluateIgnoredValue(Info, E);
7304   }
7305 
7306   /// Potentially visit a MemberExpr's base expression.
7307   void VisitIgnoredBaseExpression(const Expr *E) {
7308     // While MSVC doesn't evaluate the base expression, it does diagnose the
7309     // presence of side-effecting behavior.
7310     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7311       return;
7312     VisitIgnoredValue(E);
7313   }
7314 };
7315 
7316 } // namespace
7317 
7318 //===----------------------------------------------------------------------===//
7319 // Common base class for lvalue and temporary evaluation.
7320 //===----------------------------------------------------------------------===//
7321 namespace {
7322 template<class Derived>
7323 class LValueExprEvaluatorBase
7324   : public ExprEvaluatorBase<Derived> {
7325 protected:
7326   LValue &Result;
7327   bool InvalidBaseOK;
7328   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7329   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7330 
7331   bool Success(APValue::LValueBase B) {
7332     Result.set(B);
7333     return true;
7334   }
7335 
7336   bool evaluatePointer(const Expr *E, LValue &Result) {
7337     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7338   }
7339 
7340 public:
7341   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7342       : ExprEvaluatorBaseTy(Info), Result(Result),
7343         InvalidBaseOK(InvalidBaseOK) {}
7344 
7345   bool Success(const APValue &V, const Expr *E) {
7346     Result.setFrom(this->Info.Ctx, V);
7347     return true;
7348   }
7349 
7350   bool VisitMemberExpr(const MemberExpr *E) {
7351     // Handle non-static data members.
7352     QualType BaseTy;
7353     bool EvalOK;
7354     if (E->isArrow()) {
7355       EvalOK = evaluatePointer(E->getBase(), Result);
7356       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
7357     } else if (E->getBase()->isRValue()) {
7358       assert(E->getBase()->getType()->isRecordType());
7359       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
7360       BaseTy = E->getBase()->getType();
7361     } else {
7362       EvalOK = this->Visit(E->getBase());
7363       BaseTy = E->getBase()->getType();
7364     }
7365     if (!EvalOK) {
7366       if (!InvalidBaseOK)
7367         return false;
7368       Result.setInvalid(E);
7369       return true;
7370     }
7371 
7372     const ValueDecl *MD = E->getMemberDecl();
7373     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
7374       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7375              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7376       (void)BaseTy;
7377       if (!HandleLValueMember(this->Info, E, Result, FD))
7378         return false;
7379     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
7380       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
7381         return false;
7382     } else
7383       return this->Error(E);
7384 
7385     if (MD->getType()->isReferenceType()) {
7386       APValue RefValue;
7387       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
7388                                           RefValue))
7389         return false;
7390       return Success(RefValue, E);
7391     }
7392     return true;
7393   }
7394 
7395   bool VisitBinaryOperator(const BinaryOperator *E) {
7396     switch (E->getOpcode()) {
7397     default:
7398       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7399 
7400     case BO_PtrMemD:
7401     case BO_PtrMemI:
7402       return HandleMemberPointerAccess(this->Info, E, Result);
7403     }
7404   }
7405 
7406   bool VisitCastExpr(const CastExpr *E) {
7407     switch (E->getCastKind()) {
7408     default:
7409       return ExprEvaluatorBaseTy::VisitCastExpr(E);
7410 
7411     case CK_DerivedToBase:
7412     case CK_UncheckedDerivedToBase:
7413       if (!this->Visit(E->getSubExpr()))
7414         return false;
7415 
7416       // Now figure out the necessary offset to add to the base LV to get from
7417       // the derived class to the base class.
7418       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
7419                                   Result);
7420     }
7421   }
7422 };
7423 }
7424 
7425 //===----------------------------------------------------------------------===//
7426 // LValue Evaluation
7427 //
7428 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
7429 // function designators (in C), decl references to void objects (in C), and
7430 // temporaries (if building with -Wno-address-of-temporary).
7431 //
7432 // LValue evaluation produces values comprising a base expression of one of the
7433 // following types:
7434 // - Declarations
7435 //  * VarDecl
7436 //  * FunctionDecl
7437 // - Literals
7438 //  * CompoundLiteralExpr in C (and in global scope in C++)
7439 //  * StringLiteral
7440 //  * PredefinedExpr
7441 //  * ObjCStringLiteralExpr
7442 //  * ObjCEncodeExpr
7443 //  * AddrLabelExpr
7444 //  * BlockExpr
7445 //  * CallExpr for a MakeStringConstant builtin
7446 // - typeid(T) expressions, as TypeInfoLValues
7447 // - Locals and temporaries
7448 //  * MaterializeTemporaryExpr
7449 //  * Any Expr, with a CallIndex indicating the function in which the temporary
7450 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
7451 //    from the AST (FIXME).
7452 //  * A MaterializeTemporaryExpr that has static storage duration, with no
7453 //    CallIndex, for a lifetime-extended temporary.
7454 //  * The ConstantExpr that is currently being evaluated during evaluation of an
7455 //    immediate invocation.
7456 // plus an offset in bytes.
7457 //===----------------------------------------------------------------------===//
7458 namespace {
7459 class LValueExprEvaluator
7460   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
7461 public:
7462   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
7463     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
7464 
7465   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
7466   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
7467 
7468   bool VisitDeclRefExpr(const DeclRefExpr *E);
7469   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
7470   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
7471   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
7472   bool VisitMemberExpr(const MemberExpr *E);
7473   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
7474   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
7475   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
7476   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
7477   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
7478   bool VisitUnaryDeref(const UnaryOperator *E);
7479   bool VisitUnaryReal(const UnaryOperator *E);
7480   bool VisitUnaryImag(const UnaryOperator *E);
7481   bool VisitUnaryPreInc(const UnaryOperator *UO) {
7482     return VisitUnaryPreIncDec(UO);
7483   }
7484   bool VisitUnaryPreDec(const UnaryOperator *UO) {
7485     return VisitUnaryPreIncDec(UO);
7486   }
7487   bool VisitBinAssign(const BinaryOperator *BO);
7488   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
7489 
7490   bool VisitCastExpr(const CastExpr *E) {
7491     switch (E->getCastKind()) {
7492     default:
7493       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
7494 
7495     case CK_LValueBitCast:
7496       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7497       if (!Visit(E->getSubExpr()))
7498         return false;
7499       Result.Designator.setInvalid();
7500       return true;
7501 
7502     case CK_BaseToDerived:
7503       if (!Visit(E->getSubExpr()))
7504         return false;
7505       return HandleBaseToDerivedCast(Info, E, Result);
7506 
7507     case CK_Dynamic:
7508       if (!Visit(E->getSubExpr()))
7509         return false;
7510       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
7511     }
7512   }
7513 };
7514 } // end anonymous namespace
7515 
7516 /// Evaluate an expression as an lvalue. This can be legitimately called on
7517 /// expressions which are not glvalues, in three cases:
7518 ///  * function designators in C, and
7519 ///  * "extern void" objects
7520 ///  * @selector() expressions in Objective-C
7521 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
7522                            bool InvalidBaseOK) {
7523   assert(E->isGLValue() || E->getType()->isFunctionType() ||
7524          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
7525   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
7526 }
7527 
7528 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
7529   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
7530     return Success(FD);
7531   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
7532     return VisitVarDecl(E, VD);
7533   if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
7534     return Visit(BD->getBinding());
7535   return Error(E);
7536 }
7537 
7538 
7539 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
7540 
7541   // If we are within a lambda's call operator, check whether the 'VD' referred
7542   // to within 'E' actually represents a lambda-capture that maps to a
7543   // data-member/field within the closure object, and if so, evaluate to the
7544   // field or what the field refers to.
7545   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
7546       isa<DeclRefExpr>(E) &&
7547       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
7548     // We don't always have a complete capture-map when checking or inferring if
7549     // the function call operator meets the requirements of a constexpr function
7550     // - but we don't need to evaluate the captures to determine constexprness
7551     // (dcl.constexpr C++17).
7552     if (Info.checkingPotentialConstantExpression())
7553       return false;
7554 
7555     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
7556       // Start with 'Result' referring to the complete closure object...
7557       Result = *Info.CurrentCall->This;
7558       // ... then update it to refer to the field of the closure object
7559       // that represents the capture.
7560       if (!HandleLValueMember(Info, E, Result, FD))
7561         return false;
7562       // And if the field is of reference type, update 'Result' to refer to what
7563       // the field refers to.
7564       if (FD->getType()->isReferenceType()) {
7565         APValue RVal;
7566         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
7567                                             RVal))
7568           return false;
7569         Result.setFrom(Info.Ctx, RVal);
7570       }
7571       return true;
7572     }
7573   }
7574   CallStackFrame *Frame = nullptr;
7575   if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
7576     // Only if a local variable was declared in the function currently being
7577     // evaluated, do we expect to be able to find its value in the current
7578     // frame. (Otherwise it was likely declared in an enclosing context and
7579     // could either have a valid evaluatable value (for e.g. a constexpr
7580     // variable) or be ill-formed (and trigger an appropriate evaluation
7581     // diagnostic)).
7582     if (Info.CurrentCall->Callee &&
7583         Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
7584       Frame = Info.CurrentCall;
7585     }
7586   }
7587 
7588   if (!VD->getType()->isReferenceType()) {
7589     if (Frame) {
7590       Result.set({VD, Frame->Index,
7591                   Info.CurrentCall->getCurrentTemporaryVersion(VD)});
7592       return true;
7593     }
7594     return Success(VD);
7595   }
7596 
7597   APValue *V;
7598   if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
7599     return false;
7600   if (!V->hasValue()) {
7601     // FIXME: Is it possible for V to be indeterminate here? If so, we should
7602     // adjust the diagnostic to say that.
7603     if (!Info.checkingPotentialConstantExpression())
7604       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
7605     return false;
7606   }
7607   return Success(*V, E);
7608 }
7609 
7610 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
7611     const MaterializeTemporaryExpr *E) {
7612   // Walk through the expression to find the materialized temporary itself.
7613   SmallVector<const Expr *, 2> CommaLHSs;
7614   SmallVector<SubobjectAdjustment, 2> Adjustments;
7615   const Expr *Inner =
7616       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
7617 
7618   // If we passed any comma operators, evaluate their LHSs.
7619   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
7620     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
7621       return false;
7622 
7623   // A materialized temporary with static storage duration can appear within the
7624   // result of a constant expression evaluation, so we need to preserve its
7625   // value for use outside this evaluation.
7626   APValue *Value;
7627   if (E->getStorageDuration() == SD_Static) {
7628     Value = E->getOrCreateValue(true);
7629     *Value = APValue();
7630     Result.set(E);
7631   } else {
7632     Value = &Info.CurrentCall->createTemporary(
7633         E, E->getType(), E->getStorageDuration() == SD_Automatic, Result);
7634   }
7635 
7636   QualType Type = Inner->getType();
7637 
7638   // Materialize the temporary itself.
7639   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
7640     *Value = APValue();
7641     return false;
7642   }
7643 
7644   // Adjust our lvalue to refer to the desired subobject.
7645   for (unsigned I = Adjustments.size(); I != 0; /**/) {
7646     --I;
7647     switch (Adjustments[I].Kind) {
7648     case SubobjectAdjustment::DerivedToBaseAdjustment:
7649       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
7650                                 Type, Result))
7651         return false;
7652       Type = Adjustments[I].DerivedToBase.BasePath->getType();
7653       break;
7654 
7655     case SubobjectAdjustment::FieldAdjustment:
7656       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
7657         return false;
7658       Type = Adjustments[I].Field->getType();
7659       break;
7660 
7661     case SubobjectAdjustment::MemberPointerAdjustment:
7662       if (!HandleMemberPointerAccess(this->Info, Type, Result,
7663                                      Adjustments[I].Ptr.RHS))
7664         return false;
7665       Type = Adjustments[I].Ptr.MPT->getPointeeType();
7666       break;
7667     }
7668   }
7669 
7670   return true;
7671 }
7672 
7673 bool
7674 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7675   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
7676          "lvalue compound literal in c++?");
7677   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
7678   // only see this when folding in C, so there's no standard to follow here.
7679   return Success(E);
7680 }
7681 
7682 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
7683   TypeInfoLValue TypeInfo;
7684 
7685   if (!E->isPotentiallyEvaluated()) {
7686     if (E->isTypeOperand())
7687       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
7688     else
7689       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
7690   } else {
7691     if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
7692       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
7693         << E->getExprOperand()->getType()
7694         << E->getExprOperand()->getSourceRange();
7695     }
7696 
7697     if (!Visit(E->getExprOperand()))
7698       return false;
7699 
7700     Optional<DynamicType> DynType =
7701         ComputeDynamicType(Info, E, Result, AK_TypeId);
7702     if (!DynType)
7703       return false;
7704 
7705     TypeInfo =
7706         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
7707   }
7708 
7709   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
7710 }
7711 
7712 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
7713   return Success(E);
7714 }
7715 
7716 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
7717   // Handle static data members.
7718   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
7719     VisitIgnoredBaseExpression(E->getBase());
7720     return VisitVarDecl(E, VD);
7721   }
7722 
7723   // Handle static member functions.
7724   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
7725     if (MD->isStatic()) {
7726       VisitIgnoredBaseExpression(E->getBase());
7727       return Success(MD);
7728     }
7729   }
7730 
7731   // Handle non-static data members.
7732   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
7733 }
7734 
7735 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
7736   // FIXME: Deal with vectors as array subscript bases.
7737   if (E->getBase()->getType()->isVectorType())
7738     return Error(E);
7739 
7740   bool Success = true;
7741   if (!evaluatePointer(E->getBase(), Result)) {
7742     if (!Info.noteFailure())
7743       return false;
7744     Success = false;
7745   }
7746 
7747   APSInt Index;
7748   if (!EvaluateInteger(E->getIdx(), Index, Info))
7749     return false;
7750 
7751   return Success &&
7752          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
7753 }
7754 
7755 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
7756   return evaluatePointer(E->getSubExpr(), Result);
7757 }
7758 
7759 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7760   if (!Visit(E->getSubExpr()))
7761     return false;
7762   // __real is a no-op on scalar lvalues.
7763   if (E->getSubExpr()->getType()->isAnyComplexType())
7764     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
7765   return true;
7766 }
7767 
7768 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7769   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
7770          "lvalue __imag__ on scalar?");
7771   if (!Visit(E->getSubExpr()))
7772     return false;
7773   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
7774   return true;
7775 }
7776 
7777 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
7778   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7779     return Error(UO);
7780 
7781   if (!this->Visit(UO->getSubExpr()))
7782     return false;
7783 
7784   return handleIncDec(
7785       this->Info, UO, Result, UO->getSubExpr()->getType(),
7786       UO->isIncrementOp(), nullptr);
7787 }
7788 
7789 bool LValueExprEvaluator::VisitCompoundAssignOperator(
7790     const CompoundAssignOperator *CAO) {
7791   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7792     return Error(CAO);
7793 
7794   APValue RHS;
7795 
7796   // The overall lvalue result is the result of evaluating the LHS.
7797   if (!this->Visit(CAO->getLHS())) {
7798     if (Info.noteFailure())
7799       Evaluate(RHS, this->Info, CAO->getRHS());
7800     return false;
7801   }
7802 
7803   if (!Evaluate(RHS, this->Info, CAO->getRHS()))
7804     return false;
7805 
7806   return handleCompoundAssignment(
7807       this->Info, CAO,
7808       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
7809       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
7810 }
7811 
7812 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
7813   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7814     return Error(E);
7815 
7816   APValue NewVal;
7817 
7818   if (!this->Visit(E->getLHS())) {
7819     if (Info.noteFailure())
7820       Evaluate(NewVal, this->Info, E->getRHS());
7821     return false;
7822   }
7823 
7824   if (!Evaluate(NewVal, this->Info, E->getRHS()))
7825     return false;
7826 
7827   if (Info.getLangOpts().CPlusPlus2a &&
7828       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
7829     return false;
7830 
7831   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
7832                           NewVal);
7833 }
7834 
7835 //===----------------------------------------------------------------------===//
7836 // Pointer Evaluation
7837 //===----------------------------------------------------------------------===//
7838 
7839 /// Attempts to compute the number of bytes available at the pointer
7840 /// returned by a function with the alloc_size attribute. Returns true if we
7841 /// were successful. Places an unsigned number into `Result`.
7842 ///
7843 /// This expects the given CallExpr to be a call to a function with an
7844 /// alloc_size attribute.
7845 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
7846                                             const CallExpr *Call,
7847                                             llvm::APInt &Result) {
7848   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
7849 
7850   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
7851   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
7852   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
7853   if (Call->getNumArgs() <= SizeArgNo)
7854     return false;
7855 
7856   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
7857     Expr::EvalResult ExprResult;
7858     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
7859       return false;
7860     Into = ExprResult.Val.getInt();
7861     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
7862       return false;
7863     Into = Into.zextOrSelf(BitsInSizeT);
7864     return true;
7865   };
7866 
7867   APSInt SizeOfElem;
7868   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
7869     return false;
7870 
7871   if (!AllocSize->getNumElemsParam().isValid()) {
7872     Result = std::move(SizeOfElem);
7873     return true;
7874   }
7875 
7876   APSInt NumberOfElems;
7877   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
7878   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
7879     return false;
7880 
7881   bool Overflow;
7882   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
7883   if (Overflow)
7884     return false;
7885 
7886   Result = std::move(BytesAvailable);
7887   return true;
7888 }
7889 
7890 /// Convenience function. LVal's base must be a call to an alloc_size
7891 /// function.
7892 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
7893                                             const LValue &LVal,
7894                                             llvm::APInt &Result) {
7895   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7896          "Can't get the size of a non alloc_size function");
7897   const auto *Base = LVal.getLValueBase().get<const Expr *>();
7898   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
7899   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
7900 }
7901 
7902 /// Attempts to evaluate the given LValueBase as the result of a call to
7903 /// a function with the alloc_size attribute. If it was possible to do so, this
7904 /// function will return true, make Result's Base point to said function call,
7905 /// and mark Result's Base as invalid.
7906 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
7907                                       LValue &Result) {
7908   if (Base.isNull())
7909     return false;
7910 
7911   // Because we do no form of static analysis, we only support const variables.
7912   //
7913   // Additionally, we can't support parameters, nor can we support static
7914   // variables (in the latter case, use-before-assign isn't UB; in the former,
7915   // we have no clue what they'll be assigned to).
7916   const auto *VD =
7917       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
7918   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
7919     return false;
7920 
7921   const Expr *Init = VD->getAnyInitializer();
7922   if (!Init)
7923     return false;
7924 
7925   const Expr *E = Init->IgnoreParens();
7926   if (!tryUnwrapAllocSizeCall(E))
7927     return false;
7928 
7929   // Store E instead of E unwrapped so that the type of the LValue's base is
7930   // what the user wanted.
7931   Result.setInvalid(E);
7932 
7933   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
7934   Result.addUnsizedArray(Info, E, Pointee);
7935   return true;
7936 }
7937 
7938 namespace {
7939 class PointerExprEvaluator
7940   : public ExprEvaluatorBase<PointerExprEvaluator> {
7941   LValue &Result;
7942   bool InvalidBaseOK;
7943 
7944   bool Success(const Expr *E) {
7945     Result.set(E);
7946     return true;
7947   }
7948 
7949   bool evaluateLValue(const Expr *E, LValue &Result) {
7950     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
7951   }
7952 
7953   bool evaluatePointer(const Expr *E, LValue &Result) {
7954     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
7955   }
7956 
7957   bool visitNonBuiltinCallExpr(const CallExpr *E);
7958 public:
7959 
7960   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
7961       : ExprEvaluatorBaseTy(info), Result(Result),
7962         InvalidBaseOK(InvalidBaseOK) {}
7963 
7964   bool Success(const APValue &V, const Expr *E) {
7965     Result.setFrom(Info.Ctx, V);
7966     return true;
7967   }
7968   bool ZeroInitialization(const Expr *E) {
7969     Result.setNull(Info.Ctx, E->getType());
7970     return true;
7971   }
7972 
7973   bool VisitBinaryOperator(const BinaryOperator *E);
7974   bool VisitCastExpr(const CastExpr* E);
7975   bool VisitUnaryAddrOf(const UnaryOperator *E);
7976   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
7977       { return Success(E); }
7978   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
7979     if (E->isExpressibleAsConstantInitializer())
7980       return Success(E);
7981     if (Info.noteFailure())
7982       EvaluateIgnoredValue(Info, E->getSubExpr());
7983     return Error(E);
7984   }
7985   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
7986       { return Success(E); }
7987   bool VisitCallExpr(const CallExpr *E);
7988   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
7989   bool VisitBlockExpr(const BlockExpr *E) {
7990     if (!E->getBlockDecl()->hasCaptures())
7991       return Success(E);
7992     return Error(E);
7993   }
7994   bool VisitCXXThisExpr(const CXXThisExpr *E) {
7995     // Can't look at 'this' when checking a potential constant expression.
7996     if (Info.checkingPotentialConstantExpression())
7997       return false;
7998     if (!Info.CurrentCall->This) {
7999       if (Info.getLangOpts().CPlusPlus11)
8000         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8001       else
8002         Info.FFDiag(E);
8003       return false;
8004     }
8005     Result = *Info.CurrentCall->This;
8006     // If we are inside a lambda's call operator, the 'this' expression refers
8007     // to the enclosing '*this' object (either by value or reference) which is
8008     // either copied into the closure object's field that represents the '*this'
8009     // or refers to '*this'.
8010     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8011       // Ensure we actually have captured 'this'. (an error will have
8012       // been previously reported if not).
8013       if (!Info.CurrentCall->LambdaThisCaptureField)
8014         return false;
8015 
8016       // Update 'Result' to refer to the data member/field of the closure object
8017       // that represents the '*this' capture.
8018       if (!HandleLValueMember(Info, E, Result,
8019                              Info.CurrentCall->LambdaThisCaptureField))
8020         return false;
8021       // If we captured '*this' by reference, replace the field with its referent.
8022       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8023               ->isPointerType()) {
8024         APValue RVal;
8025         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8026                                             RVal))
8027           return false;
8028 
8029         Result.setFrom(Info.Ctx, RVal);
8030       }
8031     }
8032     return true;
8033   }
8034 
8035   bool VisitCXXNewExpr(const CXXNewExpr *E);
8036 
8037   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8038     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
8039     APValue LValResult = E->EvaluateInContext(
8040         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8041     Result.setFrom(Info.Ctx, LValResult);
8042     return true;
8043   }
8044 
8045   // FIXME: Missing: @protocol, @selector
8046 };
8047 } // end anonymous namespace
8048 
8049 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8050                             bool InvalidBaseOK) {
8051   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
8052   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8053 }
8054 
8055 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8056   if (E->getOpcode() != BO_Add &&
8057       E->getOpcode() != BO_Sub)
8058     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8059 
8060   const Expr *PExp = E->getLHS();
8061   const Expr *IExp = E->getRHS();
8062   if (IExp->getType()->isPointerType())
8063     std::swap(PExp, IExp);
8064 
8065   bool EvalPtrOK = evaluatePointer(PExp, Result);
8066   if (!EvalPtrOK && !Info.noteFailure())
8067     return false;
8068 
8069   llvm::APSInt Offset;
8070   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8071     return false;
8072 
8073   if (E->getOpcode() == BO_Sub)
8074     negateAsSigned(Offset);
8075 
8076   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8077   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8078 }
8079 
8080 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8081   return evaluateLValue(E->getSubExpr(), Result);
8082 }
8083 
8084 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8085   const Expr *SubExpr = E->getSubExpr();
8086 
8087   switch (E->getCastKind()) {
8088   default:
8089     break;
8090   case CK_BitCast:
8091   case CK_CPointerToObjCPointerCast:
8092   case CK_BlockPointerToObjCPointerCast:
8093   case CK_AnyPointerToBlockPointerCast:
8094   case CK_AddressSpaceConversion:
8095     if (!Visit(SubExpr))
8096       return false;
8097     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8098     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8099     // also static_casts, but we disallow them as a resolution to DR1312.
8100     if (!E->getType()->isVoidPointerType()) {
8101       if (!Result.InvalidBase && !Result.Designator.Invalid &&
8102           !Result.IsNullPtr &&
8103           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8104                                           E->getType()->getPointeeType()) &&
8105           Info.getStdAllocatorCaller("allocate")) {
8106         // Inside a call to std::allocator::allocate and friends, we permit
8107         // casting from void* back to cv1 T* for a pointer that points to a
8108         // cv2 T.
8109       } else {
8110         Result.Designator.setInvalid();
8111         if (SubExpr->getType()->isVoidPointerType())
8112           CCEDiag(E, diag::note_constexpr_invalid_cast)
8113             << 3 << SubExpr->getType();
8114         else
8115           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8116       }
8117     }
8118     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8119       ZeroInitialization(E);
8120     return true;
8121 
8122   case CK_DerivedToBase:
8123   case CK_UncheckedDerivedToBase:
8124     if (!evaluatePointer(E->getSubExpr(), Result))
8125       return false;
8126     if (!Result.Base && Result.Offset.isZero())
8127       return true;
8128 
8129     // Now figure out the necessary offset to add to the base LV to get from
8130     // the derived class to the base class.
8131     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8132                                   castAs<PointerType>()->getPointeeType(),
8133                                 Result);
8134 
8135   case CK_BaseToDerived:
8136     if (!Visit(E->getSubExpr()))
8137       return false;
8138     if (!Result.Base && Result.Offset.isZero())
8139       return true;
8140     return HandleBaseToDerivedCast(Info, E, Result);
8141 
8142   case CK_Dynamic:
8143     if (!Visit(E->getSubExpr()))
8144       return false;
8145     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8146 
8147   case CK_NullToPointer:
8148     VisitIgnoredValue(E->getSubExpr());
8149     return ZeroInitialization(E);
8150 
8151   case CK_IntegralToPointer: {
8152     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8153 
8154     APValue Value;
8155     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8156       break;
8157 
8158     if (Value.isInt()) {
8159       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8160       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8161       Result.Base = (Expr*)nullptr;
8162       Result.InvalidBase = false;
8163       Result.Offset = CharUnits::fromQuantity(N);
8164       Result.Designator.setInvalid();
8165       Result.IsNullPtr = false;
8166       return true;
8167     } else {
8168       // Cast is of an lvalue, no need to change value.
8169       Result.setFrom(Info.Ctx, Value);
8170       return true;
8171     }
8172   }
8173 
8174   case CK_ArrayToPointerDecay: {
8175     if (SubExpr->isGLValue()) {
8176       if (!evaluateLValue(SubExpr, Result))
8177         return false;
8178     } else {
8179       APValue &Value = Info.CurrentCall->createTemporary(
8180           SubExpr, SubExpr->getType(), false, Result);
8181       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8182         return false;
8183     }
8184     // The result is a pointer to the first element of the array.
8185     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8186     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8187       Result.addArray(Info, E, CAT);
8188     else
8189       Result.addUnsizedArray(Info, E, AT->getElementType());
8190     return true;
8191   }
8192 
8193   case CK_FunctionToPointerDecay:
8194     return evaluateLValue(SubExpr, Result);
8195 
8196   case CK_LValueToRValue: {
8197     LValue LVal;
8198     if (!evaluateLValue(E->getSubExpr(), LVal))
8199       return false;
8200 
8201     APValue RVal;
8202     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8203     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8204                                         LVal, RVal))
8205       return InvalidBaseOK &&
8206              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8207     return Success(RVal, E);
8208   }
8209   }
8210 
8211   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8212 }
8213 
8214 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8215                                 UnaryExprOrTypeTrait ExprKind) {
8216   // C++ [expr.alignof]p3:
8217   //     When alignof is applied to a reference type, the result is the
8218   //     alignment of the referenced type.
8219   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8220     T = Ref->getPointeeType();
8221 
8222   if (T.getQualifiers().hasUnaligned())
8223     return CharUnits::One();
8224 
8225   const bool AlignOfReturnsPreferred =
8226       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8227 
8228   // __alignof is defined to return the preferred alignment.
8229   // Before 8, clang returned the preferred alignment for alignof and _Alignof
8230   // as well.
8231   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8232     return Info.Ctx.toCharUnitsFromBits(
8233       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8234   // alignof and _Alignof are defined to return the ABI alignment.
8235   else if (ExprKind == UETT_AlignOf)
8236     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8237   else
8238     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8239 }
8240 
8241 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8242                                 UnaryExprOrTypeTrait ExprKind) {
8243   E = E->IgnoreParens();
8244 
8245   // The kinds of expressions that we have special-case logic here for
8246   // should be kept up to date with the special checks for those
8247   // expressions in Sema.
8248 
8249   // alignof decl is always accepted, even if it doesn't make sense: we default
8250   // to 1 in those cases.
8251   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8252     return Info.Ctx.getDeclAlign(DRE->getDecl(),
8253                                  /*RefAsPointee*/true);
8254 
8255   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8256     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8257                                  /*RefAsPointee*/true);
8258 
8259   return GetAlignOfType(Info, E->getType(), ExprKind);
8260 }
8261 
8262 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
8263   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
8264     return Info.Ctx.getDeclAlign(VD);
8265   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
8266     return GetAlignOfExpr(Info, E, UETT_AlignOf);
8267   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
8268 }
8269 
8270 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
8271 /// __builtin_is_aligned and __builtin_assume_aligned.
8272 static bool getAlignmentArgument(const Expr *E, QualType ForType,
8273                                  EvalInfo &Info, APSInt &Alignment) {
8274   if (!EvaluateInteger(E, Alignment, Info))
8275     return false;
8276   if (Alignment < 0 || !Alignment.isPowerOf2()) {
8277     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
8278     return false;
8279   }
8280   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
8281   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
8282   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
8283     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
8284         << MaxValue << ForType << Alignment;
8285     return false;
8286   }
8287   // Ensure both alignment and source value have the same bit width so that we
8288   // don't assert when computing the resulting value.
8289   APSInt ExtAlignment =
8290       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
8291   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
8292          "Alignment should not be changed by ext/trunc");
8293   Alignment = ExtAlignment;
8294   assert(Alignment.getBitWidth() == SrcWidth);
8295   return true;
8296 }
8297 
8298 // To be clear: this happily visits unsupported builtins. Better name welcomed.
8299 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8300   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8301     return true;
8302 
8303   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
8304     return false;
8305 
8306   Result.setInvalid(E);
8307   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
8308   Result.addUnsizedArray(Info, E, PointeeTy);
8309   return true;
8310 }
8311 
8312 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
8313   if (IsStringLiteralCall(E))
8314     return Success(E);
8315 
8316   if (unsigned BuiltinOp = E->getBuiltinCallee())
8317     return VisitBuiltinCallExpr(E, BuiltinOp);
8318 
8319   return visitNonBuiltinCallExpr(E);
8320 }
8321 
8322 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8323                                                 unsigned BuiltinOp) {
8324   switch (BuiltinOp) {
8325   case Builtin::BI__builtin_addressof:
8326     return evaluateLValue(E->getArg(0), Result);
8327   case Builtin::BI__builtin_assume_aligned: {
8328     // We need to be very careful here because: if the pointer does not have the
8329     // asserted alignment, then the behavior is undefined, and undefined
8330     // behavior is non-constant.
8331     if (!evaluatePointer(E->getArg(0), Result))
8332       return false;
8333 
8334     LValue OffsetResult(Result);
8335     APSInt Alignment;
8336     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8337                               Alignment))
8338       return false;
8339     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
8340 
8341     if (E->getNumArgs() > 2) {
8342       APSInt Offset;
8343       if (!EvaluateInteger(E->getArg(2), Offset, Info))
8344         return false;
8345 
8346       int64_t AdditionalOffset = -Offset.getZExtValue();
8347       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
8348     }
8349 
8350     // If there is a base object, then it must have the correct alignment.
8351     if (OffsetResult.Base) {
8352       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
8353 
8354       if (BaseAlignment < Align) {
8355         Result.Designator.setInvalid();
8356         // FIXME: Add support to Diagnostic for long / long long.
8357         CCEDiag(E->getArg(0),
8358                 diag::note_constexpr_baa_insufficient_alignment) << 0
8359           << (unsigned)BaseAlignment.getQuantity()
8360           << (unsigned)Align.getQuantity();
8361         return false;
8362       }
8363     }
8364 
8365     // The offset must also have the correct alignment.
8366     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
8367       Result.Designator.setInvalid();
8368 
8369       (OffsetResult.Base
8370            ? CCEDiag(E->getArg(0),
8371                      diag::note_constexpr_baa_insufficient_alignment) << 1
8372            : CCEDiag(E->getArg(0),
8373                      diag::note_constexpr_baa_value_insufficient_alignment))
8374         << (int)OffsetResult.Offset.getQuantity()
8375         << (unsigned)Align.getQuantity();
8376       return false;
8377     }
8378 
8379     return true;
8380   }
8381   case Builtin::BI__builtin_align_up:
8382   case Builtin::BI__builtin_align_down: {
8383     if (!evaluatePointer(E->getArg(0), Result))
8384       return false;
8385     APSInt Alignment;
8386     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8387                               Alignment))
8388       return false;
8389     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
8390     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
8391     // For align_up/align_down, we can return the same value if the alignment
8392     // is known to be greater or equal to the requested value.
8393     if (PtrAlign.getQuantity() >= Alignment)
8394       return true;
8395 
8396     // The alignment could be greater than the minimum at run-time, so we cannot
8397     // infer much about the resulting pointer value. One case is possible:
8398     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
8399     // can infer the correct index if the requested alignment is smaller than
8400     // the base alignment so we can perform the computation on the offset.
8401     if (BaseAlignment.getQuantity() >= Alignment) {
8402       assert(Alignment.getBitWidth() <= 64 &&
8403              "Cannot handle > 64-bit address-space");
8404       uint64_t Alignment64 = Alignment.getZExtValue();
8405       CharUnits NewOffset = CharUnits::fromQuantity(
8406           BuiltinOp == Builtin::BI__builtin_align_down
8407               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
8408               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
8409       Result.adjustOffset(NewOffset - Result.Offset);
8410       // TODO: diagnose out-of-bounds values/only allow for arrays?
8411       return true;
8412     }
8413     // Otherwise, we cannot constant-evaluate the result.
8414     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
8415         << Alignment;
8416     return false;
8417   }
8418   case Builtin::BI__builtin_operator_new:
8419     return HandleOperatorNewCall(Info, E, Result);
8420   case Builtin::BI__builtin_launder:
8421     return evaluatePointer(E->getArg(0), Result);
8422   case Builtin::BIstrchr:
8423   case Builtin::BIwcschr:
8424   case Builtin::BImemchr:
8425   case Builtin::BIwmemchr:
8426     if (Info.getLangOpts().CPlusPlus11)
8427       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8428         << /*isConstexpr*/0 << /*isConstructor*/0
8429         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8430     else
8431       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8432     LLVM_FALLTHROUGH;
8433   case Builtin::BI__builtin_strchr:
8434   case Builtin::BI__builtin_wcschr:
8435   case Builtin::BI__builtin_memchr:
8436   case Builtin::BI__builtin_char_memchr:
8437   case Builtin::BI__builtin_wmemchr: {
8438     if (!Visit(E->getArg(0)))
8439       return false;
8440     APSInt Desired;
8441     if (!EvaluateInteger(E->getArg(1), Desired, Info))
8442       return false;
8443     uint64_t MaxLength = uint64_t(-1);
8444     if (BuiltinOp != Builtin::BIstrchr &&
8445         BuiltinOp != Builtin::BIwcschr &&
8446         BuiltinOp != Builtin::BI__builtin_strchr &&
8447         BuiltinOp != Builtin::BI__builtin_wcschr) {
8448       APSInt N;
8449       if (!EvaluateInteger(E->getArg(2), N, Info))
8450         return false;
8451       MaxLength = N.getExtValue();
8452     }
8453     // We cannot find the value if there are no candidates to match against.
8454     if (MaxLength == 0u)
8455       return ZeroInitialization(E);
8456     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
8457         Result.Designator.Invalid)
8458       return false;
8459     QualType CharTy = Result.Designator.getType(Info.Ctx);
8460     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
8461                      BuiltinOp == Builtin::BI__builtin_memchr;
8462     assert(IsRawByte ||
8463            Info.Ctx.hasSameUnqualifiedType(
8464                CharTy, E->getArg(0)->getType()->getPointeeType()));
8465     // Pointers to const void may point to objects of incomplete type.
8466     if (IsRawByte && CharTy->isIncompleteType()) {
8467       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
8468       return false;
8469     }
8470     // Give up on byte-oriented matching against multibyte elements.
8471     // FIXME: We can compare the bytes in the correct order.
8472     if (IsRawByte && !CharTy->isCharType()) {
8473       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
8474           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
8475           << CharTy;
8476       return false;
8477     }
8478     // Figure out what value we're actually looking for (after converting to
8479     // the corresponding unsigned type if necessary).
8480     uint64_t DesiredVal;
8481     bool StopAtNull = false;
8482     switch (BuiltinOp) {
8483     case Builtin::BIstrchr:
8484     case Builtin::BI__builtin_strchr:
8485       // strchr compares directly to the passed integer, and therefore
8486       // always fails if given an int that is not a char.
8487       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
8488                                                   E->getArg(1)->getType(),
8489                                                   Desired),
8490                                Desired))
8491         return ZeroInitialization(E);
8492       StopAtNull = true;
8493       LLVM_FALLTHROUGH;
8494     case Builtin::BImemchr:
8495     case Builtin::BI__builtin_memchr:
8496     case Builtin::BI__builtin_char_memchr:
8497       // memchr compares by converting both sides to unsigned char. That's also
8498       // correct for strchr if we get this far (to cope with plain char being
8499       // unsigned in the strchr case).
8500       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
8501       break;
8502 
8503     case Builtin::BIwcschr:
8504     case Builtin::BI__builtin_wcschr:
8505       StopAtNull = true;
8506       LLVM_FALLTHROUGH;
8507     case Builtin::BIwmemchr:
8508     case Builtin::BI__builtin_wmemchr:
8509       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
8510       DesiredVal = Desired.getZExtValue();
8511       break;
8512     }
8513 
8514     for (; MaxLength; --MaxLength) {
8515       APValue Char;
8516       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
8517           !Char.isInt())
8518         return false;
8519       if (Char.getInt().getZExtValue() == DesiredVal)
8520         return true;
8521       if (StopAtNull && !Char.getInt())
8522         break;
8523       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
8524         return false;
8525     }
8526     // Not found: return nullptr.
8527     return ZeroInitialization(E);
8528   }
8529 
8530   case Builtin::BImemcpy:
8531   case Builtin::BImemmove:
8532   case Builtin::BIwmemcpy:
8533   case Builtin::BIwmemmove:
8534     if (Info.getLangOpts().CPlusPlus11)
8535       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8536         << /*isConstexpr*/0 << /*isConstructor*/0
8537         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8538     else
8539       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8540     LLVM_FALLTHROUGH;
8541   case Builtin::BI__builtin_memcpy:
8542   case Builtin::BI__builtin_memmove:
8543   case Builtin::BI__builtin_wmemcpy:
8544   case Builtin::BI__builtin_wmemmove: {
8545     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
8546                  BuiltinOp == Builtin::BIwmemmove ||
8547                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
8548                  BuiltinOp == Builtin::BI__builtin_wmemmove;
8549     bool Move = BuiltinOp == Builtin::BImemmove ||
8550                 BuiltinOp == Builtin::BIwmemmove ||
8551                 BuiltinOp == Builtin::BI__builtin_memmove ||
8552                 BuiltinOp == Builtin::BI__builtin_wmemmove;
8553 
8554     // The result of mem* is the first argument.
8555     if (!Visit(E->getArg(0)))
8556       return false;
8557     LValue Dest = Result;
8558 
8559     LValue Src;
8560     if (!EvaluatePointer(E->getArg(1), Src, Info))
8561       return false;
8562 
8563     APSInt N;
8564     if (!EvaluateInteger(E->getArg(2), N, Info))
8565       return false;
8566     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
8567 
8568     // If the size is zero, we treat this as always being a valid no-op.
8569     // (Even if one of the src and dest pointers is null.)
8570     if (!N)
8571       return true;
8572 
8573     // Otherwise, if either of the operands is null, we can't proceed. Don't
8574     // try to determine the type of the copied objects, because there aren't
8575     // any.
8576     if (!Src.Base || !Dest.Base) {
8577       APValue Val;
8578       (!Src.Base ? Src : Dest).moveInto(Val);
8579       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
8580           << Move << WChar << !!Src.Base
8581           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
8582       return false;
8583     }
8584     if (Src.Designator.Invalid || Dest.Designator.Invalid)
8585       return false;
8586 
8587     // We require that Src and Dest are both pointers to arrays of
8588     // trivially-copyable type. (For the wide version, the designator will be
8589     // invalid if the designated object is not a wchar_t.)
8590     QualType T = Dest.Designator.getType(Info.Ctx);
8591     QualType SrcT = Src.Designator.getType(Info.Ctx);
8592     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
8593       // FIXME: Consider using our bit_cast implementation to support this.
8594       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
8595       return false;
8596     }
8597     if (T->isIncompleteType()) {
8598       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
8599       return false;
8600     }
8601     if (!T.isTriviallyCopyableType(Info.Ctx)) {
8602       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
8603       return false;
8604     }
8605 
8606     // Figure out how many T's we're copying.
8607     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
8608     if (!WChar) {
8609       uint64_t Remainder;
8610       llvm::APInt OrigN = N;
8611       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
8612       if (Remainder) {
8613         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8614             << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
8615             << (unsigned)TSize;
8616         return false;
8617       }
8618     }
8619 
8620     // Check that the copying will remain within the arrays, just so that we
8621     // can give a more meaningful diagnostic. This implicitly also checks that
8622     // N fits into 64 bits.
8623     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
8624     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
8625     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
8626       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
8627           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
8628           << N.toString(10, /*Signed*/false);
8629       return false;
8630     }
8631     uint64_t NElems = N.getZExtValue();
8632     uint64_t NBytes = NElems * TSize;
8633 
8634     // Check for overlap.
8635     int Direction = 1;
8636     if (HasSameBase(Src, Dest)) {
8637       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
8638       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
8639       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
8640         // Dest is inside the source region.
8641         if (!Move) {
8642           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8643           return false;
8644         }
8645         // For memmove and friends, copy backwards.
8646         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
8647             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
8648           return false;
8649         Direction = -1;
8650       } else if (!Move && SrcOffset >= DestOffset &&
8651                  SrcOffset - DestOffset < NBytes) {
8652         // Src is inside the destination region for memcpy: invalid.
8653         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
8654         return false;
8655       }
8656     }
8657 
8658     while (true) {
8659       APValue Val;
8660       // FIXME: Set WantObjectRepresentation to true if we're copying a
8661       // char-like type?
8662       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
8663           !handleAssignment(Info, E, Dest, T, Val))
8664         return false;
8665       // Do not iterate past the last element; if we're copying backwards, that
8666       // might take us off the start of the array.
8667       if (--NElems == 0)
8668         return true;
8669       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
8670           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
8671         return false;
8672     }
8673   }
8674 
8675   default:
8676     break;
8677   }
8678 
8679   return visitNonBuiltinCallExpr(E);
8680 }
8681 
8682 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
8683                                      APValue &Result, const InitListExpr *ILE,
8684                                      QualType AllocType);
8685 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
8686                                           APValue &Result,
8687                                           const CXXConstructExpr *CCE,
8688                                           QualType AllocType);
8689 
8690 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
8691   if (!Info.getLangOpts().CPlusPlus2a)
8692     Info.CCEDiag(E, diag::note_constexpr_new);
8693 
8694   // We cannot speculatively evaluate a delete expression.
8695   if (Info.SpeculativeEvaluationDepth)
8696     return false;
8697 
8698   FunctionDecl *OperatorNew = E->getOperatorNew();
8699 
8700   bool IsNothrow = false;
8701   bool IsPlacement = false;
8702   if (OperatorNew->isReservedGlobalPlacementOperator() &&
8703       Info.CurrentCall->isStdFunction() && !E->isArray()) {
8704     // FIXME Support array placement new.
8705     assert(E->getNumPlacementArgs() == 1);
8706     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
8707       return false;
8708     if (Result.Designator.Invalid)
8709       return false;
8710     IsPlacement = true;
8711   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
8712     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
8713         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
8714     return false;
8715   } else if (E->getNumPlacementArgs()) {
8716     // The only new-placement list we support is of the form (std::nothrow).
8717     //
8718     // FIXME: There is no restriction on this, but it's not clear that any
8719     // other form makes any sense. We get here for cases such as:
8720     //
8721     //   new (std::align_val_t{N}) X(int)
8722     //
8723     // (which should presumably be valid only if N is a multiple of
8724     // alignof(int), and in any case can't be deallocated unless N is
8725     // alignof(X) and X has new-extended alignment).
8726     if (E->getNumPlacementArgs() != 1 ||
8727         !E->getPlacementArg(0)->getType()->isNothrowT())
8728       return Error(E, diag::note_constexpr_new_placement);
8729 
8730     LValue Nothrow;
8731     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
8732       return false;
8733     IsNothrow = true;
8734   }
8735 
8736   const Expr *Init = E->getInitializer();
8737   const InitListExpr *ResizedArrayILE = nullptr;
8738   const CXXConstructExpr *ResizedArrayCCE = nullptr;
8739 
8740   QualType AllocType = E->getAllocatedType();
8741   if (Optional<const Expr*> ArraySize = E->getArraySize()) {
8742     const Expr *Stripped = *ArraySize;
8743     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
8744          Stripped = ICE->getSubExpr())
8745       if (ICE->getCastKind() != CK_NoOp &&
8746           ICE->getCastKind() != CK_IntegralCast)
8747         break;
8748 
8749     llvm::APSInt ArrayBound;
8750     if (!EvaluateInteger(Stripped, ArrayBound, Info))
8751       return false;
8752 
8753     // C++ [expr.new]p9:
8754     //   The expression is erroneous if:
8755     //   -- [...] its value before converting to size_t [or] applying the
8756     //      second standard conversion sequence is less than zero
8757     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
8758       if (IsNothrow)
8759         return ZeroInitialization(E);
8760 
8761       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
8762           << ArrayBound << (*ArraySize)->getSourceRange();
8763       return false;
8764     }
8765 
8766     //   -- its value is such that the size of the allocated object would
8767     //      exceed the implementation-defined limit
8768     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
8769                                                 ArrayBound) >
8770         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
8771       if (IsNothrow)
8772         return ZeroInitialization(E);
8773 
8774       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
8775         << ArrayBound << (*ArraySize)->getSourceRange();
8776       return false;
8777     }
8778 
8779     //   -- the new-initializer is a braced-init-list and the number of
8780     //      array elements for which initializers are provided [...]
8781     //      exceeds the number of elements to initialize
8782     if (Init && !isa<CXXConstructExpr>(Init)) {
8783       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
8784       assert(CAT && "unexpected type for array initializer");
8785 
8786       unsigned Bits =
8787           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
8788       llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
8789       llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
8790       if (InitBound.ugt(AllocBound)) {
8791         if (IsNothrow)
8792           return ZeroInitialization(E);
8793 
8794         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
8795             << AllocBound.toString(10, /*Signed=*/false)
8796             << InitBound.toString(10, /*Signed=*/false)
8797             << (*ArraySize)->getSourceRange();
8798         return false;
8799       }
8800 
8801       // If the sizes differ, we must have an initializer list, and we need
8802       // special handling for this case when we initialize.
8803       if (InitBound != AllocBound)
8804         ResizedArrayILE = cast<InitListExpr>(Init);
8805     } else if (Init) {
8806       ResizedArrayCCE = cast<CXXConstructExpr>(Init);
8807     }
8808 
8809     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
8810                                               ArrayType::Normal, 0);
8811   } else {
8812     assert(!AllocType->isArrayType() &&
8813            "array allocation with non-array new");
8814   }
8815 
8816   APValue *Val;
8817   if (IsPlacement) {
8818     AccessKinds AK = AK_Construct;
8819     struct FindObjectHandler {
8820       EvalInfo &Info;
8821       const Expr *E;
8822       QualType AllocType;
8823       const AccessKinds AccessKind;
8824       APValue *Value;
8825 
8826       typedef bool result_type;
8827       bool failed() { return false; }
8828       bool found(APValue &Subobj, QualType SubobjType) {
8829         // FIXME: Reject the cases where [basic.life]p8 would not permit the
8830         // old name of the object to be used to name the new object.
8831         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
8832           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
8833             SubobjType << AllocType;
8834           return false;
8835         }
8836         Value = &Subobj;
8837         return true;
8838       }
8839       bool found(APSInt &Value, QualType SubobjType) {
8840         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
8841         return false;
8842       }
8843       bool found(APFloat &Value, QualType SubobjType) {
8844         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
8845         return false;
8846       }
8847     } Handler = {Info, E, AllocType, AK, nullptr};
8848 
8849     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
8850     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
8851       return false;
8852 
8853     Val = Handler.Value;
8854 
8855     // [basic.life]p1:
8856     //   The lifetime of an object o of type T ends when [...] the storage
8857     //   which the object occupies is [...] reused by an object that is not
8858     //   nested within o (6.6.2).
8859     *Val = APValue();
8860   } else {
8861     // Perform the allocation and obtain a pointer to the resulting object.
8862     Val = Info.createHeapAlloc(E, AllocType, Result);
8863     if (!Val)
8864       return false;
8865   }
8866 
8867   if (ResizedArrayILE) {
8868     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
8869                                   AllocType))
8870       return false;
8871   } else if (ResizedArrayCCE) {
8872     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
8873                                        AllocType))
8874       return false;
8875   } else if (Init) {
8876     if (!EvaluateInPlace(*Val, Info, Result, Init))
8877       return false;
8878   } else {
8879     *Val = getDefaultInitValue(AllocType);
8880   }
8881 
8882   // Array new returns a pointer to the first element, not a pointer to the
8883   // array.
8884   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
8885     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
8886 
8887   return true;
8888 }
8889 //===----------------------------------------------------------------------===//
8890 // Member Pointer Evaluation
8891 //===----------------------------------------------------------------------===//
8892 
8893 namespace {
8894 class MemberPointerExprEvaluator
8895   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
8896   MemberPtr &Result;
8897 
8898   bool Success(const ValueDecl *D) {
8899     Result = MemberPtr(D);
8900     return true;
8901   }
8902 public:
8903 
8904   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
8905     : ExprEvaluatorBaseTy(Info), Result(Result) {}
8906 
8907   bool Success(const APValue &V, const Expr *E) {
8908     Result.setFrom(V);
8909     return true;
8910   }
8911   bool ZeroInitialization(const Expr *E) {
8912     return Success((const ValueDecl*)nullptr);
8913   }
8914 
8915   bool VisitCastExpr(const CastExpr *E);
8916   bool VisitUnaryAddrOf(const UnaryOperator *E);
8917 };
8918 } // end anonymous namespace
8919 
8920 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
8921                                   EvalInfo &Info) {
8922   assert(E->isRValue() && E->getType()->isMemberPointerType());
8923   return MemberPointerExprEvaluator(Info, Result).Visit(E);
8924 }
8925 
8926 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8927   switch (E->getCastKind()) {
8928   default:
8929     return ExprEvaluatorBaseTy::VisitCastExpr(E);
8930 
8931   case CK_NullToMemberPointer:
8932     VisitIgnoredValue(E->getSubExpr());
8933     return ZeroInitialization(E);
8934 
8935   case CK_BaseToDerivedMemberPointer: {
8936     if (!Visit(E->getSubExpr()))
8937       return false;
8938     if (E->path_empty())
8939       return true;
8940     // Base-to-derived member pointer casts store the path in derived-to-base
8941     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
8942     // the wrong end of the derived->base arc, so stagger the path by one class.
8943     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
8944     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
8945          PathI != PathE; ++PathI) {
8946       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
8947       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
8948       if (!Result.castToDerived(Derived))
8949         return Error(E);
8950     }
8951     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
8952     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
8953       return Error(E);
8954     return true;
8955   }
8956 
8957   case CK_DerivedToBaseMemberPointer:
8958     if (!Visit(E->getSubExpr()))
8959       return false;
8960     for (CastExpr::path_const_iterator PathI = E->path_begin(),
8961          PathE = E->path_end(); PathI != PathE; ++PathI) {
8962       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
8963       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
8964       if (!Result.castToBase(Base))
8965         return Error(E);
8966     }
8967     return true;
8968   }
8969 }
8970 
8971 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8972   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
8973   // member can be formed.
8974   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
8975 }
8976 
8977 //===----------------------------------------------------------------------===//
8978 // Record Evaluation
8979 //===----------------------------------------------------------------------===//
8980 
8981 namespace {
8982   class RecordExprEvaluator
8983   : public ExprEvaluatorBase<RecordExprEvaluator> {
8984     const LValue &This;
8985     APValue &Result;
8986   public:
8987 
8988     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
8989       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
8990 
8991     bool Success(const APValue &V, const Expr *E) {
8992       Result = V;
8993       return true;
8994     }
8995     bool ZeroInitialization(const Expr *E) {
8996       return ZeroInitialization(E, E->getType());
8997     }
8998     bool ZeroInitialization(const Expr *E, QualType T);
8999 
9000     bool VisitCallExpr(const CallExpr *E) {
9001       return handleCallExpr(E, Result, &This);
9002     }
9003     bool VisitCastExpr(const CastExpr *E);
9004     bool VisitInitListExpr(const InitListExpr *E);
9005     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9006       return VisitCXXConstructExpr(E, E->getType());
9007     }
9008     bool VisitLambdaExpr(const LambdaExpr *E);
9009     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9010     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9011     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9012     bool VisitBinCmp(const BinaryOperator *E);
9013   };
9014 }
9015 
9016 /// Perform zero-initialization on an object of non-union class type.
9017 /// C++11 [dcl.init]p5:
9018 ///  To zero-initialize an object or reference of type T means:
9019 ///    [...]
9020 ///    -- if T is a (possibly cv-qualified) non-union class type,
9021 ///       each non-static data member and each base-class subobject is
9022 ///       zero-initialized
9023 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9024                                           const RecordDecl *RD,
9025                                           const LValue &This, APValue &Result) {
9026   assert(!RD->isUnion() && "Expected non-union class type");
9027   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9028   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9029                    std::distance(RD->field_begin(), RD->field_end()));
9030 
9031   if (RD->isInvalidDecl()) return false;
9032   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9033 
9034   if (CD) {
9035     unsigned Index = 0;
9036     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9037            End = CD->bases_end(); I != End; ++I, ++Index) {
9038       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9039       LValue Subobject = This;
9040       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9041         return false;
9042       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9043                                          Result.getStructBase(Index)))
9044         return false;
9045     }
9046   }
9047 
9048   for (const auto *I : RD->fields()) {
9049     // -- if T is a reference type, no initialization is performed.
9050     if (I->getType()->isReferenceType())
9051       continue;
9052 
9053     LValue Subobject = This;
9054     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9055       return false;
9056 
9057     ImplicitValueInitExpr VIE(I->getType());
9058     if (!EvaluateInPlace(
9059           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9060       return false;
9061   }
9062 
9063   return true;
9064 }
9065 
9066 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9067   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9068   if (RD->isInvalidDecl()) return false;
9069   if (RD->isUnion()) {
9070     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9071     // object's first non-static named data member is zero-initialized
9072     RecordDecl::field_iterator I = RD->field_begin();
9073     if (I == RD->field_end()) {
9074       Result = APValue((const FieldDecl*)nullptr);
9075       return true;
9076     }
9077 
9078     LValue Subobject = This;
9079     if (!HandleLValueMember(Info, E, Subobject, *I))
9080       return false;
9081     Result = APValue(*I);
9082     ImplicitValueInitExpr VIE(I->getType());
9083     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9084   }
9085 
9086   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9087     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9088     return false;
9089   }
9090 
9091   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9092 }
9093 
9094 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9095   switch (E->getCastKind()) {
9096   default:
9097     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9098 
9099   case CK_ConstructorConversion:
9100     return Visit(E->getSubExpr());
9101 
9102   case CK_DerivedToBase:
9103   case CK_UncheckedDerivedToBase: {
9104     APValue DerivedObject;
9105     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9106       return false;
9107     if (!DerivedObject.isStruct())
9108       return Error(E->getSubExpr());
9109 
9110     // Derived-to-base rvalue conversion: just slice off the derived part.
9111     APValue *Value = &DerivedObject;
9112     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9113     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9114          PathE = E->path_end(); PathI != PathE; ++PathI) {
9115       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9116       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9117       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9118       RD = Base;
9119     }
9120     Result = *Value;
9121     return true;
9122   }
9123   }
9124 }
9125 
9126 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9127   if (E->isTransparent())
9128     return Visit(E->getInit(0));
9129 
9130   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9131   if (RD->isInvalidDecl()) return false;
9132   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9133   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9134 
9135   EvalInfo::EvaluatingConstructorRAII EvalObj(
9136       Info,
9137       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9138       CXXRD && CXXRD->getNumBases());
9139 
9140   if (RD->isUnion()) {
9141     const FieldDecl *Field = E->getInitializedFieldInUnion();
9142     Result = APValue(Field);
9143     if (!Field)
9144       return true;
9145 
9146     // If the initializer list for a union does not contain any elements, the
9147     // first element of the union is value-initialized.
9148     // FIXME: The element should be initialized from an initializer list.
9149     //        Is this difference ever observable for initializer lists which
9150     //        we don't build?
9151     ImplicitValueInitExpr VIE(Field->getType());
9152     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9153 
9154     LValue Subobject = This;
9155     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9156       return false;
9157 
9158     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9159     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9160                                   isa<CXXDefaultInitExpr>(InitExpr));
9161 
9162     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
9163   }
9164 
9165   if (!Result.hasValue())
9166     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9167                      std::distance(RD->field_begin(), RD->field_end()));
9168   unsigned ElementNo = 0;
9169   bool Success = true;
9170 
9171   // Initialize base classes.
9172   if (CXXRD && CXXRD->getNumBases()) {
9173     for (const auto &Base : CXXRD->bases()) {
9174       assert(ElementNo < E->getNumInits() && "missing init for base class");
9175       const Expr *Init = E->getInit(ElementNo);
9176 
9177       LValue Subobject = This;
9178       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9179         return false;
9180 
9181       APValue &FieldVal = Result.getStructBase(ElementNo);
9182       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9183         if (!Info.noteFailure())
9184           return false;
9185         Success = false;
9186       }
9187       ++ElementNo;
9188     }
9189 
9190     EvalObj.finishedConstructingBases();
9191   }
9192 
9193   // Initialize members.
9194   for (const auto *Field : RD->fields()) {
9195     // Anonymous bit-fields are not considered members of the class for
9196     // purposes of aggregate initialization.
9197     if (Field->isUnnamedBitfield())
9198       continue;
9199 
9200     LValue Subobject = This;
9201 
9202     bool HaveInit = ElementNo < E->getNumInits();
9203 
9204     // FIXME: Diagnostics here should point to the end of the initializer
9205     // list, not the start.
9206     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9207                             Subobject, Field, &Layout))
9208       return false;
9209 
9210     // Perform an implicit value-initialization for members beyond the end of
9211     // the initializer list.
9212     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9213     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9214 
9215     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9216     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9217                                   isa<CXXDefaultInitExpr>(Init));
9218 
9219     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9220     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9221         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9222                                                        FieldVal, Field))) {
9223       if (!Info.noteFailure())
9224         return false;
9225       Success = false;
9226     }
9227   }
9228 
9229   EvalObj.finishedConstructingFields();
9230 
9231   return Success;
9232 }
9233 
9234 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9235                                                 QualType T) {
9236   // Note that E's type is not necessarily the type of our class here; we might
9237   // be initializing an array element instead.
9238   const CXXConstructorDecl *FD = E->getConstructor();
9239   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9240 
9241   bool ZeroInit = E->requiresZeroInitialization();
9242   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
9243     // If we've already performed zero-initialization, we're already done.
9244     if (Result.hasValue())
9245       return true;
9246 
9247     if (ZeroInit)
9248       return ZeroInitialization(E, T);
9249 
9250     Result = getDefaultInitValue(T);
9251     return true;
9252   }
9253 
9254   const FunctionDecl *Definition = nullptr;
9255   auto Body = FD->getBody(Definition);
9256 
9257   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9258     return false;
9259 
9260   // Avoid materializing a temporary for an elidable copy/move constructor.
9261   if (E->isElidable() && !ZeroInit)
9262     if (const MaterializeTemporaryExpr *ME
9263           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
9264       return Visit(ME->getSubExpr());
9265 
9266   if (ZeroInit && !ZeroInitialization(E, T))
9267     return false;
9268 
9269   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
9270   return HandleConstructorCall(E, This, Args,
9271                                cast<CXXConstructorDecl>(Definition), Info,
9272                                Result);
9273 }
9274 
9275 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9276     const CXXInheritedCtorInitExpr *E) {
9277   if (!Info.CurrentCall) {
9278     assert(Info.checkingPotentialConstantExpression());
9279     return false;
9280   }
9281 
9282   const CXXConstructorDecl *FD = E->getConstructor();
9283   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9284     return false;
9285 
9286   const FunctionDecl *Definition = nullptr;
9287   auto Body = FD->getBody(Definition);
9288 
9289   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9290     return false;
9291 
9292   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
9293                                cast<CXXConstructorDecl>(Definition), Info,
9294                                Result);
9295 }
9296 
9297 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
9298     const CXXStdInitializerListExpr *E) {
9299   const ConstantArrayType *ArrayType =
9300       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
9301 
9302   LValue Array;
9303   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
9304     return false;
9305 
9306   // Get a pointer to the first element of the array.
9307   Array.addArray(Info, E, ArrayType);
9308 
9309   // FIXME: Perform the checks on the field types in SemaInit.
9310   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
9311   RecordDecl::field_iterator Field = Record->field_begin();
9312   if (Field == Record->field_end())
9313     return Error(E);
9314 
9315   // Start pointer.
9316   if (!Field->getType()->isPointerType() ||
9317       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9318                             ArrayType->getElementType()))
9319     return Error(E);
9320 
9321   // FIXME: What if the initializer_list type has base classes, etc?
9322   Result = APValue(APValue::UninitStruct(), 0, 2);
9323   Array.moveInto(Result.getStructField(0));
9324 
9325   if (++Field == Record->field_end())
9326     return Error(E);
9327 
9328   if (Field->getType()->isPointerType() &&
9329       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9330                            ArrayType->getElementType())) {
9331     // End pointer.
9332     if (!HandleLValueArrayAdjustment(Info, E, Array,
9333                                      ArrayType->getElementType(),
9334                                      ArrayType->getSize().getZExtValue()))
9335       return false;
9336     Array.moveInto(Result.getStructField(1));
9337   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
9338     // Length.
9339     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
9340   else
9341     return Error(E);
9342 
9343   if (++Field != Record->field_end())
9344     return Error(E);
9345 
9346   return true;
9347 }
9348 
9349 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
9350   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
9351   if (ClosureClass->isInvalidDecl())
9352     return false;
9353 
9354   const size_t NumFields =
9355       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
9356 
9357   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
9358                                             E->capture_init_end()) &&
9359          "The number of lambda capture initializers should equal the number of "
9360          "fields within the closure type");
9361 
9362   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
9363   // Iterate through all the lambda's closure object's fields and initialize
9364   // them.
9365   auto *CaptureInitIt = E->capture_init_begin();
9366   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
9367   bool Success = true;
9368   for (const auto *Field : ClosureClass->fields()) {
9369     assert(CaptureInitIt != E->capture_init_end());
9370     // Get the initializer for this field
9371     Expr *const CurFieldInit = *CaptureInitIt++;
9372 
9373     // If there is no initializer, either this is a VLA or an error has
9374     // occurred.
9375     if (!CurFieldInit)
9376       return Error(E);
9377 
9378     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9379     if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
9380       if (!Info.keepEvaluatingAfterFailure())
9381         return false;
9382       Success = false;
9383     }
9384     ++CaptureIt;
9385   }
9386   return Success;
9387 }
9388 
9389 static bool EvaluateRecord(const Expr *E, const LValue &This,
9390                            APValue &Result, EvalInfo &Info) {
9391   assert(E->isRValue() && E->getType()->isRecordType() &&
9392          "can't evaluate expression as a record rvalue");
9393   return RecordExprEvaluator(Info, This, Result).Visit(E);
9394 }
9395 
9396 //===----------------------------------------------------------------------===//
9397 // Temporary Evaluation
9398 //
9399 // Temporaries are represented in the AST as rvalues, but generally behave like
9400 // lvalues. The full-object of which the temporary is a subobject is implicitly
9401 // materialized so that a reference can bind to it.
9402 //===----------------------------------------------------------------------===//
9403 namespace {
9404 class TemporaryExprEvaluator
9405   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
9406 public:
9407   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
9408     LValueExprEvaluatorBaseTy(Info, Result, false) {}
9409 
9410   /// Visit an expression which constructs the value of this temporary.
9411   bool VisitConstructExpr(const Expr *E) {
9412     APValue &Value =
9413         Info.CurrentCall->createTemporary(E, E->getType(), false, Result);
9414     return EvaluateInPlace(Value, Info, Result, E);
9415   }
9416 
9417   bool VisitCastExpr(const CastExpr *E) {
9418     switch (E->getCastKind()) {
9419     default:
9420       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9421 
9422     case CK_ConstructorConversion:
9423       return VisitConstructExpr(E->getSubExpr());
9424     }
9425   }
9426   bool VisitInitListExpr(const InitListExpr *E) {
9427     return VisitConstructExpr(E);
9428   }
9429   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9430     return VisitConstructExpr(E);
9431   }
9432   bool VisitCallExpr(const CallExpr *E) {
9433     return VisitConstructExpr(E);
9434   }
9435   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
9436     return VisitConstructExpr(E);
9437   }
9438   bool VisitLambdaExpr(const LambdaExpr *E) {
9439     return VisitConstructExpr(E);
9440   }
9441 };
9442 } // end anonymous namespace
9443 
9444 /// Evaluate an expression of record type as a temporary.
9445 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
9446   assert(E->isRValue() && E->getType()->isRecordType());
9447   return TemporaryExprEvaluator(Info, Result).Visit(E);
9448 }
9449 
9450 //===----------------------------------------------------------------------===//
9451 // Vector Evaluation
9452 //===----------------------------------------------------------------------===//
9453 
9454 namespace {
9455   class VectorExprEvaluator
9456   : public ExprEvaluatorBase<VectorExprEvaluator> {
9457     APValue &Result;
9458   public:
9459 
9460     VectorExprEvaluator(EvalInfo &info, APValue &Result)
9461       : ExprEvaluatorBaseTy(info), Result(Result) {}
9462 
9463     bool Success(ArrayRef<APValue> V, const Expr *E) {
9464       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
9465       // FIXME: remove this APValue copy.
9466       Result = APValue(V.data(), V.size());
9467       return true;
9468     }
9469     bool Success(const APValue &V, const Expr *E) {
9470       assert(V.isVector());
9471       Result = V;
9472       return true;
9473     }
9474     bool ZeroInitialization(const Expr *E);
9475 
9476     bool VisitUnaryReal(const UnaryOperator *E)
9477       { return Visit(E->getSubExpr()); }
9478     bool VisitCastExpr(const CastExpr* E);
9479     bool VisitInitListExpr(const InitListExpr *E);
9480     bool VisitUnaryImag(const UnaryOperator *E);
9481     // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
9482     //                 binary comparisons, binary and/or/xor,
9483     //                 conditional operator (for GNU conditional select),
9484     //                 shufflevector, ExtVectorElementExpr
9485   };
9486 } // end anonymous namespace
9487 
9488 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
9489   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
9490   return VectorExprEvaluator(Info, Result).Visit(E);
9491 }
9492 
9493 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
9494   const VectorType *VTy = E->getType()->castAs<VectorType>();
9495   unsigned NElts = VTy->getNumElements();
9496 
9497   const Expr *SE = E->getSubExpr();
9498   QualType SETy = SE->getType();
9499 
9500   switch (E->getCastKind()) {
9501   case CK_VectorSplat: {
9502     APValue Val = APValue();
9503     if (SETy->isIntegerType()) {
9504       APSInt IntResult;
9505       if (!EvaluateInteger(SE, IntResult, Info))
9506         return false;
9507       Val = APValue(std::move(IntResult));
9508     } else if (SETy->isRealFloatingType()) {
9509       APFloat FloatResult(0.0);
9510       if (!EvaluateFloat(SE, FloatResult, Info))
9511         return false;
9512       Val = APValue(std::move(FloatResult));
9513     } else {
9514       return Error(E);
9515     }
9516 
9517     // Splat and create vector APValue.
9518     SmallVector<APValue, 4> Elts(NElts, Val);
9519     return Success(Elts, E);
9520   }
9521   case CK_BitCast: {
9522     // Evaluate the operand into an APInt we can extract from.
9523     llvm::APInt SValInt;
9524     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
9525       return false;
9526     // Extract the elements
9527     QualType EltTy = VTy->getElementType();
9528     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
9529     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
9530     SmallVector<APValue, 4> Elts;
9531     if (EltTy->isRealFloatingType()) {
9532       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
9533       unsigned FloatEltSize = EltSize;
9534       if (&Sem == &APFloat::x87DoubleExtended())
9535         FloatEltSize = 80;
9536       for (unsigned i = 0; i < NElts; i++) {
9537         llvm::APInt Elt;
9538         if (BigEndian)
9539           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
9540         else
9541           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
9542         Elts.push_back(APValue(APFloat(Sem, Elt)));
9543       }
9544     } else if (EltTy->isIntegerType()) {
9545       for (unsigned i = 0; i < NElts; i++) {
9546         llvm::APInt Elt;
9547         if (BigEndian)
9548           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
9549         else
9550           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
9551         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
9552       }
9553     } else {
9554       return Error(E);
9555     }
9556     return Success(Elts, E);
9557   }
9558   default:
9559     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9560   }
9561 }
9562 
9563 bool
9564 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9565   const VectorType *VT = E->getType()->castAs<VectorType>();
9566   unsigned NumInits = E->getNumInits();
9567   unsigned NumElements = VT->getNumElements();
9568 
9569   QualType EltTy = VT->getElementType();
9570   SmallVector<APValue, 4> Elements;
9571 
9572   // The number of initializers can be less than the number of
9573   // vector elements. For OpenCL, this can be due to nested vector
9574   // initialization. For GCC compatibility, missing trailing elements
9575   // should be initialized with zeroes.
9576   unsigned CountInits = 0, CountElts = 0;
9577   while (CountElts < NumElements) {
9578     // Handle nested vector initialization.
9579     if (CountInits < NumInits
9580         && E->getInit(CountInits)->getType()->isVectorType()) {
9581       APValue v;
9582       if (!EvaluateVector(E->getInit(CountInits), v, Info))
9583         return Error(E);
9584       unsigned vlen = v.getVectorLength();
9585       for (unsigned j = 0; j < vlen; j++)
9586         Elements.push_back(v.getVectorElt(j));
9587       CountElts += vlen;
9588     } else if (EltTy->isIntegerType()) {
9589       llvm::APSInt sInt(32);
9590       if (CountInits < NumInits) {
9591         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
9592           return false;
9593       } else // trailing integer zero.
9594         sInt = Info.Ctx.MakeIntValue(0, EltTy);
9595       Elements.push_back(APValue(sInt));
9596       CountElts++;
9597     } else {
9598       llvm::APFloat f(0.0);
9599       if (CountInits < NumInits) {
9600         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
9601           return false;
9602       } else // trailing float zero.
9603         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
9604       Elements.push_back(APValue(f));
9605       CountElts++;
9606     }
9607     CountInits++;
9608   }
9609   return Success(Elements, E);
9610 }
9611 
9612 bool
9613 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
9614   const auto *VT = E->getType()->castAs<VectorType>();
9615   QualType EltTy = VT->getElementType();
9616   APValue ZeroElement;
9617   if (EltTy->isIntegerType())
9618     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
9619   else
9620     ZeroElement =
9621         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
9622 
9623   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
9624   return Success(Elements, E);
9625 }
9626 
9627 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9628   VisitIgnoredValue(E->getSubExpr());
9629   return ZeroInitialization(E);
9630 }
9631 
9632 //===----------------------------------------------------------------------===//
9633 // Array Evaluation
9634 //===----------------------------------------------------------------------===//
9635 
9636 namespace {
9637   class ArrayExprEvaluator
9638   : public ExprEvaluatorBase<ArrayExprEvaluator> {
9639     const LValue &This;
9640     APValue &Result;
9641   public:
9642 
9643     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
9644       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
9645 
9646     bool Success(const APValue &V, const Expr *E) {
9647       assert(V.isArray() && "expected array");
9648       Result = V;
9649       return true;
9650     }
9651 
9652     bool ZeroInitialization(const Expr *E) {
9653       const ConstantArrayType *CAT =
9654           Info.Ctx.getAsConstantArrayType(E->getType());
9655       if (!CAT)
9656         return Error(E);
9657 
9658       Result = APValue(APValue::UninitArray(), 0,
9659                        CAT->getSize().getZExtValue());
9660       if (!Result.hasArrayFiller()) return true;
9661 
9662       // Zero-initialize all elements.
9663       LValue Subobject = This;
9664       Subobject.addArray(Info, E, CAT);
9665       ImplicitValueInitExpr VIE(CAT->getElementType());
9666       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
9667     }
9668 
9669     bool VisitCallExpr(const CallExpr *E) {
9670       return handleCallExpr(E, Result, &This);
9671     }
9672     bool VisitInitListExpr(const InitListExpr *E,
9673                            QualType AllocType = QualType());
9674     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
9675     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
9676     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
9677                                const LValue &Subobject,
9678                                APValue *Value, QualType Type);
9679     bool VisitStringLiteral(const StringLiteral *E,
9680                             QualType AllocType = QualType()) {
9681       expandStringLiteral(Info, E, Result, AllocType);
9682       return true;
9683     }
9684   };
9685 } // end anonymous namespace
9686 
9687 static bool EvaluateArray(const Expr *E, const LValue &This,
9688                           APValue &Result, EvalInfo &Info) {
9689   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
9690   return ArrayExprEvaluator(Info, This, Result).Visit(E);
9691 }
9692 
9693 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9694                                      APValue &Result, const InitListExpr *ILE,
9695                                      QualType AllocType) {
9696   assert(ILE->isRValue() && ILE->getType()->isArrayType() &&
9697          "not an array rvalue");
9698   return ArrayExprEvaluator(Info, This, Result)
9699       .VisitInitListExpr(ILE, AllocType);
9700 }
9701 
9702 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9703                                           APValue &Result,
9704                                           const CXXConstructExpr *CCE,
9705                                           QualType AllocType) {
9706   assert(CCE->isRValue() && CCE->getType()->isArrayType() &&
9707          "not an array rvalue");
9708   return ArrayExprEvaluator(Info, This, Result)
9709       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
9710 }
9711 
9712 // Return true iff the given array filler may depend on the element index.
9713 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
9714   // For now, just whitelist non-class value-initialization and initialization
9715   // lists comprised of them.
9716   if (isa<ImplicitValueInitExpr>(FillerExpr))
9717     return false;
9718   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
9719     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
9720       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
9721         return true;
9722     }
9723     return false;
9724   }
9725   return true;
9726 }
9727 
9728 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
9729                                            QualType AllocType) {
9730   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
9731       AllocType.isNull() ? E->getType() : AllocType);
9732   if (!CAT)
9733     return Error(E);
9734 
9735   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
9736   // an appropriately-typed string literal enclosed in braces.
9737   if (E->isStringLiteralInit()) {
9738     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
9739     // FIXME: Support ObjCEncodeExpr here once we support it in
9740     // ArrayExprEvaluator generally.
9741     if (!SL)
9742       return Error(E);
9743     return VisitStringLiteral(SL, AllocType);
9744   }
9745 
9746   bool Success = true;
9747 
9748   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
9749          "zero-initialized array shouldn't have any initialized elts");
9750   APValue Filler;
9751   if (Result.isArray() && Result.hasArrayFiller())
9752     Filler = Result.getArrayFiller();
9753 
9754   unsigned NumEltsToInit = E->getNumInits();
9755   unsigned NumElts = CAT->getSize().getZExtValue();
9756   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
9757 
9758   // If the initializer might depend on the array index, run it for each
9759   // array element.
9760   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
9761     NumEltsToInit = NumElts;
9762 
9763   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
9764                           << NumEltsToInit << ".\n");
9765 
9766   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
9767 
9768   // If the array was previously zero-initialized, preserve the
9769   // zero-initialized values.
9770   if (Filler.hasValue()) {
9771     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
9772       Result.getArrayInitializedElt(I) = Filler;
9773     if (Result.hasArrayFiller())
9774       Result.getArrayFiller() = Filler;
9775   }
9776 
9777   LValue Subobject = This;
9778   Subobject.addArray(Info, E, CAT);
9779   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
9780     const Expr *Init =
9781         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
9782     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
9783                          Info, Subobject, Init) ||
9784         !HandleLValueArrayAdjustment(Info, Init, Subobject,
9785                                      CAT->getElementType(), 1)) {
9786       if (!Info.noteFailure())
9787         return false;
9788       Success = false;
9789     }
9790   }
9791 
9792   if (!Result.hasArrayFiller())
9793     return Success;
9794 
9795   // If we get here, we have a trivial filler, which we can just evaluate
9796   // once and splat over the rest of the array elements.
9797   assert(FillerExpr && "no array filler for incomplete init list");
9798   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
9799                          FillerExpr) && Success;
9800 }
9801 
9802 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
9803   LValue CommonLV;
9804   if (E->getCommonExpr() &&
9805       !Evaluate(Info.CurrentCall->createTemporary(
9806                     E->getCommonExpr(),
9807                     getStorageType(Info.Ctx, E->getCommonExpr()), false,
9808                     CommonLV),
9809                 Info, E->getCommonExpr()->getSourceExpr()))
9810     return false;
9811 
9812   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
9813 
9814   uint64_t Elements = CAT->getSize().getZExtValue();
9815   Result = APValue(APValue::UninitArray(), Elements, Elements);
9816 
9817   LValue Subobject = This;
9818   Subobject.addArray(Info, E, CAT);
9819 
9820   bool Success = true;
9821   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
9822     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
9823                          Info, Subobject, E->getSubExpr()) ||
9824         !HandleLValueArrayAdjustment(Info, E, Subobject,
9825                                      CAT->getElementType(), 1)) {
9826       if (!Info.noteFailure())
9827         return false;
9828       Success = false;
9829     }
9830   }
9831 
9832   return Success;
9833 }
9834 
9835 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
9836   return VisitCXXConstructExpr(E, This, &Result, E->getType());
9837 }
9838 
9839 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9840                                                const LValue &Subobject,
9841                                                APValue *Value,
9842                                                QualType Type) {
9843   bool HadZeroInit = Value->hasValue();
9844 
9845   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
9846     unsigned N = CAT->getSize().getZExtValue();
9847 
9848     // Preserve the array filler if we had prior zero-initialization.
9849     APValue Filler =
9850       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
9851                                              : APValue();
9852 
9853     *Value = APValue(APValue::UninitArray(), N, N);
9854 
9855     if (HadZeroInit)
9856       for (unsigned I = 0; I != N; ++I)
9857         Value->getArrayInitializedElt(I) = Filler;
9858 
9859     // Initialize the elements.
9860     LValue ArrayElt = Subobject;
9861     ArrayElt.addArray(Info, E, CAT);
9862     for (unsigned I = 0; I != N; ++I)
9863       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
9864                                  CAT->getElementType()) ||
9865           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
9866                                        CAT->getElementType(), 1))
9867         return false;
9868 
9869     return true;
9870   }
9871 
9872   if (!Type->isRecordType())
9873     return Error(E);
9874 
9875   return RecordExprEvaluator(Info, Subobject, *Value)
9876              .VisitCXXConstructExpr(E, Type);
9877 }
9878 
9879 //===----------------------------------------------------------------------===//
9880 // Integer Evaluation
9881 //
9882 // As a GNU extension, we support casting pointers to sufficiently-wide integer
9883 // types and back in constant folding. Integer values are thus represented
9884 // either as an integer-valued APValue, or as an lvalue-valued APValue.
9885 //===----------------------------------------------------------------------===//
9886 
9887 namespace {
9888 class IntExprEvaluator
9889         : public ExprEvaluatorBase<IntExprEvaluator> {
9890   APValue &Result;
9891 public:
9892   IntExprEvaluator(EvalInfo &info, APValue &result)
9893       : ExprEvaluatorBaseTy(info), Result(result) {}
9894 
9895   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
9896     assert(E->getType()->isIntegralOrEnumerationType() &&
9897            "Invalid evaluation result.");
9898     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
9899            "Invalid evaluation result.");
9900     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
9901            "Invalid evaluation result.");
9902     Result = APValue(SI);
9903     return true;
9904   }
9905   bool Success(const llvm::APSInt &SI, const Expr *E) {
9906     return Success(SI, E, Result);
9907   }
9908 
9909   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
9910     assert(E->getType()->isIntegralOrEnumerationType() &&
9911            "Invalid evaluation result.");
9912     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
9913            "Invalid evaluation result.");
9914     Result = APValue(APSInt(I));
9915     Result.getInt().setIsUnsigned(
9916                             E->getType()->isUnsignedIntegerOrEnumerationType());
9917     return true;
9918   }
9919   bool Success(const llvm::APInt &I, const Expr *E) {
9920     return Success(I, E, Result);
9921   }
9922 
9923   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
9924     assert(E->getType()->isIntegralOrEnumerationType() &&
9925            "Invalid evaluation result.");
9926     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
9927     return true;
9928   }
9929   bool Success(uint64_t Value, const Expr *E) {
9930     return Success(Value, E, Result);
9931   }
9932 
9933   bool Success(CharUnits Size, const Expr *E) {
9934     return Success(Size.getQuantity(), E);
9935   }
9936 
9937   bool Success(const APValue &V, const Expr *E) {
9938     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
9939       Result = V;
9940       return true;
9941     }
9942     return Success(V.getInt(), E);
9943   }
9944 
9945   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
9946 
9947   //===--------------------------------------------------------------------===//
9948   //                            Visitor Methods
9949   //===--------------------------------------------------------------------===//
9950 
9951   bool VisitConstantExpr(const ConstantExpr *E);
9952 
9953   bool VisitIntegerLiteral(const IntegerLiteral *E) {
9954     return Success(E->getValue(), E);
9955   }
9956   bool VisitCharacterLiteral(const CharacterLiteral *E) {
9957     return Success(E->getValue(), E);
9958   }
9959 
9960   bool CheckReferencedDecl(const Expr *E, const Decl *D);
9961   bool VisitDeclRefExpr(const DeclRefExpr *E) {
9962     if (CheckReferencedDecl(E, E->getDecl()))
9963       return true;
9964 
9965     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
9966   }
9967   bool VisitMemberExpr(const MemberExpr *E) {
9968     if (CheckReferencedDecl(E, E->getMemberDecl())) {
9969       VisitIgnoredBaseExpression(E->getBase());
9970       return true;
9971     }
9972 
9973     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
9974   }
9975 
9976   bool VisitCallExpr(const CallExpr *E);
9977   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
9978   bool VisitBinaryOperator(const BinaryOperator *E);
9979   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
9980   bool VisitUnaryOperator(const UnaryOperator *E);
9981 
9982   bool VisitCastExpr(const CastExpr* E);
9983   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
9984 
9985   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
9986     return Success(E->getValue(), E);
9987   }
9988 
9989   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
9990     return Success(E->getValue(), E);
9991   }
9992 
9993   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
9994     if (Info.ArrayInitIndex == uint64_t(-1)) {
9995       // We were asked to evaluate this subexpression independent of the
9996       // enclosing ArrayInitLoopExpr. We can't do that.
9997       Info.FFDiag(E);
9998       return false;
9999     }
10000     return Success(Info.ArrayInitIndex, E);
10001   }
10002 
10003   // Note, GNU defines __null as an integer, not a pointer.
10004   bool VisitGNUNullExpr(const GNUNullExpr *E) {
10005     return ZeroInitialization(E);
10006   }
10007 
10008   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
10009     return Success(E->getValue(), E);
10010   }
10011 
10012   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
10013     return Success(E->getValue(), E);
10014   }
10015 
10016   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
10017     return Success(E->getValue(), E);
10018   }
10019 
10020   bool VisitUnaryReal(const UnaryOperator *E);
10021   bool VisitUnaryImag(const UnaryOperator *E);
10022 
10023   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
10024   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
10025   bool VisitSourceLocExpr(const SourceLocExpr *E);
10026   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
10027   bool VisitRequiresExpr(const RequiresExpr *E);
10028   // FIXME: Missing: array subscript of vector, member of vector
10029 };
10030 
10031 class FixedPointExprEvaluator
10032     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
10033   APValue &Result;
10034 
10035  public:
10036   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
10037       : ExprEvaluatorBaseTy(info), Result(result) {}
10038 
10039   bool Success(const llvm::APInt &I, const Expr *E) {
10040     return Success(
10041         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10042   }
10043 
10044   bool Success(uint64_t Value, const Expr *E) {
10045     return Success(
10046         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10047   }
10048 
10049   bool Success(const APValue &V, const Expr *E) {
10050     return Success(V.getFixedPoint(), E);
10051   }
10052 
10053   bool Success(const APFixedPoint &V, const Expr *E) {
10054     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
10055     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10056            "Invalid evaluation result.");
10057     Result = APValue(V);
10058     return true;
10059   }
10060 
10061   //===--------------------------------------------------------------------===//
10062   //                            Visitor Methods
10063   //===--------------------------------------------------------------------===//
10064 
10065   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
10066     return Success(E->getValue(), E);
10067   }
10068 
10069   bool VisitCastExpr(const CastExpr *E);
10070   bool VisitUnaryOperator(const UnaryOperator *E);
10071   bool VisitBinaryOperator(const BinaryOperator *E);
10072 };
10073 } // end anonymous namespace
10074 
10075 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
10076 /// produce either the integer value or a pointer.
10077 ///
10078 /// GCC has a heinous extension which folds casts between pointer types and
10079 /// pointer-sized integral types. We support this by allowing the evaluation of
10080 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
10081 /// Some simple arithmetic on such values is supported (they are treated much
10082 /// like char*).
10083 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
10084                                     EvalInfo &Info) {
10085   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
10086   return IntExprEvaluator(Info, Result).Visit(E);
10087 }
10088 
10089 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
10090   APValue Val;
10091   if (!EvaluateIntegerOrLValue(E, Val, Info))
10092     return false;
10093   if (!Val.isInt()) {
10094     // FIXME: It would be better to produce the diagnostic for casting
10095     //        a pointer to an integer.
10096     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10097     return false;
10098   }
10099   Result = Val.getInt();
10100   return true;
10101 }
10102 
10103 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
10104   APValue Evaluated = E->EvaluateInContext(
10105       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10106   return Success(Evaluated, E);
10107 }
10108 
10109 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
10110                                EvalInfo &Info) {
10111   if (E->getType()->isFixedPointType()) {
10112     APValue Val;
10113     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
10114       return false;
10115     if (!Val.isFixedPoint())
10116       return false;
10117 
10118     Result = Val.getFixedPoint();
10119     return true;
10120   }
10121   return false;
10122 }
10123 
10124 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
10125                                         EvalInfo &Info) {
10126   if (E->getType()->isIntegerType()) {
10127     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
10128     APSInt Val;
10129     if (!EvaluateInteger(E, Val, Info))
10130       return false;
10131     Result = APFixedPoint(Val, FXSema);
10132     return true;
10133   } else if (E->getType()->isFixedPointType()) {
10134     return EvaluateFixedPoint(E, Result, Info);
10135   }
10136   return false;
10137 }
10138 
10139 /// Check whether the given declaration can be directly converted to an integral
10140 /// rvalue. If not, no diagnostic is produced; there are other things we can
10141 /// try.
10142 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
10143   // Enums are integer constant exprs.
10144   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
10145     // Check for signedness/width mismatches between E type and ECD value.
10146     bool SameSign = (ECD->getInitVal().isSigned()
10147                      == E->getType()->isSignedIntegerOrEnumerationType());
10148     bool SameWidth = (ECD->getInitVal().getBitWidth()
10149                       == Info.Ctx.getIntWidth(E->getType()));
10150     if (SameSign && SameWidth)
10151       return Success(ECD->getInitVal(), E);
10152     else {
10153       // Get rid of mismatch (otherwise Success assertions will fail)
10154       // by computing a new value matching the type of E.
10155       llvm::APSInt Val = ECD->getInitVal();
10156       if (!SameSign)
10157         Val.setIsSigned(!ECD->getInitVal().isSigned());
10158       if (!SameWidth)
10159         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
10160       return Success(Val, E);
10161     }
10162   }
10163   return false;
10164 }
10165 
10166 /// Values returned by __builtin_classify_type, chosen to match the values
10167 /// produced by GCC's builtin.
10168 enum class GCCTypeClass {
10169   None = -1,
10170   Void = 0,
10171   Integer = 1,
10172   // GCC reserves 2 for character types, but instead classifies them as
10173   // integers.
10174   Enum = 3,
10175   Bool = 4,
10176   Pointer = 5,
10177   // GCC reserves 6 for references, but appears to never use it (because
10178   // expressions never have reference type, presumably).
10179   PointerToDataMember = 7,
10180   RealFloat = 8,
10181   Complex = 9,
10182   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
10183   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
10184   // GCC claims to reserve 11 for pointers to member functions, but *actually*
10185   // uses 12 for that purpose, same as for a class or struct. Maybe it
10186   // internally implements a pointer to member as a struct?  Who knows.
10187   PointerToMemberFunction = 12, // Not a bug, see above.
10188   ClassOrStruct = 12,
10189   Union = 13,
10190   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
10191   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
10192   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
10193   // literals.
10194 };
10195 
10196 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10197 /// as GCC.
10198 static GCCTypeClass
10199 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
10200   assert(!T->isDependentType() && "unexpected dependent type");
10201 
10202   QualType CanTy = T.getCanonicalType();
10203   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
10204 
10205   switch (CanTy->getTypeClass()) {
10206 #define TYPE(ID, BASE)
10207 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
10208 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
10209 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
10210 #include "clang/AST/TypeNodes.inc"
10211   case Type::Auto:
10212   case Type::DeducedTemplateSpecialization:
10213       llvm_unreachable("unexpected non-canonical or dependent type");
10214 
10215   case Type::Builtin:
10216     switch (BT->getKind()) {
10217 #define BUILTIN_TYPE(ID, SINGLETON_ID)
10218 #define SIGNED_TYPE(ID, SINGLETON_ID) \
10219     case BuiltinType::ID: return GCCTypeClass::Integer;
10220 #define FLOATING_TYPE(ID, SINGLETON_ID) \
10221     case BuiltinType::ID: return GCCTypeClass::RealFloat;
10222 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
10223     case BuiltinType::ID: break;
10224 #include "clang/AST/BuiltinTypes.def"
10225     case BuiltinType::Void:
10226       return GCCTypeClass::Void;
10227 
10228     case BuiltinType::Bool:
10229       return GCCTypeClass::Bool;
10230 
10231     case BuiltinType::Char_U:
10232     case BuiltinType::UChar:
10233     case BuiltinType::WChar_U:
10234     case BuiltinType::Char8:
10235     case BuiltinType::Char16:
10236     case BuiltinType::Char32:
10237     case BuiltinType::UShort:
10238     case BuiltinType::UInt:
10239     case BuiltinType::ULong:
10240     case BuiltinType::ULongLong:
10241     case BuiltinType::UInt128:
10242       return GCCTypeClass::Integer;
10243 
10244     case BuiltinType::UShortAccum:
10245     case BuiltinType::UAccum:
10246     case BuiltinType::ULongAccum:
10247     case BuiltinType::UShortFract:
10248     case BuiltinType::UFract:
10249     case BuiltinType::ULongFract:
10250     case BuiltinType::SatUShortAccum:
10251     case BuiltinType::SatUAccum:
10252     case BuiltinType::SatULongAccum:
10253     case BuiltinType::SatUShortFract:
10254     case BuiltinType::SatUFract:
10255     case BuiltinType::SatULongFract:
10256       return GCCTypeClass::None;
10257 
10258     case BuiltinType::NullPtr:
10259 
10260     case BuiltinType::ObjCId:
10261     case BuiltinType::ObjCClass:
10262     case BuiltinType::ObjCSel:
10263 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
10264     case BuiltinType::Id:
10265 #include "clang/Basic/OpenCLImageTypes.def"
10266 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
10267     case BuiltinType::Id:
10268 #include "clang/Basic/OpenCLExtensionTypes.def"
10269     case BuiltinType::OCLSampler:
10270     case BuiltinType::OCLEvent:
10271     case BuiltinType::OCLClkEvent:
10272     case BuiltinType::OCLQueue:
10273     case BuiltinType::OCLReserveID:
10274 #define SVE_TYPE(Name, Id, SingletonId) \
10275     case BuiltinType::Id:
10276 #include "clang/Basic/AArch64SVEACLETypes.def"
10277       return GCCTypeClass::None;
10278 
10279     case BuiltinType::Dependent:
10280       llvm_unreachable("unexpected dependent type");
10281     };
10282     llvm_unreachable("unexpected placeholder type");
10283 
10284   case Type::Enum:
10285     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
10286 
10287   case Type::Pointer:
10288   case Type::ConstantArray:
10289   case Type::VariableArray:
10290   case Type::IncompleteArray:
10291   case Type::FunctionNoProto:
10292   case Type::FunctionProto:
10293     return GCCTypeClass::Pointer;
10294 
10295   case Type::MemberPointer:
10296     return CanTy->isMemberDataPointerType()
10297                ? GCCTypeClass::PointerToDataMember
10298                : GCCTypeClass::PointerToMemberFunction;
10299 
10300   case Type::Complex:
10301     return GCCTypeClass::Complex;
10302 
10303   case Type::Record:
10304     return CanTy->isUnionType() ? GCCTypeClass::Union
10305                                 : GCCTypeClass::ClassOrStruct;
10306 
10307   case Type::Atomic:
10308     // GCC classifies _Atomic T the same as T.
10309     return EvaluateBuiltinClassifyType(
10310         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
10311 
10312   case Type::BlockPointer:
10313   case Type::Vector:
10314   case Type::ExtVector:
10315   case Type::ObjCObject:
10316   case Type::ObjCInterface:
10317   case Type::ObjCObjectPointer:
10318   case Type::Pipe:
10319     // GCC classifies vectors as None. We follow its lead and classify all
10320     // other types that don't fit into the regular classification the same way.
10321     return GCCTypeClass::None;
10322 
10323   case Type::LValueReference:
10324   case Type::RValueReference:
10325     llvm_unreachable("invalid type for expression");
10326   }
10327 
10328   llvm_unreachable("unexpected type class");
10329 }
10330 
10331 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10332 /// as GCC.
10333 static GCCTypeClass
10334 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
10335   // If no argument was supplied, default to None. This isn't
10336   // ideal, however it is what gcc does.
10337   if (E->getNumArgs() == 0)
10338     return GCCTypeClass::None;
10339 
10340   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
10341   // being an ICE, but still folds it to a constant using the type of the first
10342   // argument.
10343   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
10344 }
10345 
10346 /// EvaluateBuiltinConstantPForLValue - Determine the result of
10347 /// __builtin_constant_p when applied to the given pointer.
10348 ///
10349 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
10350 /// or it points to the first character of a string literal.
10351 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
10352   APValue::LValueBase Base = LV.getLValueBase();
10353   if (Base.isNull()) {
10354     // A null base is acceptable.
10355     return true;
10356   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
10357     if (!isa<StringLiteral>(E))
10358       return false;
10359     return LV.getLValueOffset().isZero();
10360   } else if (Base.is<TypeInfoLValue>()) {
10361     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
10362     // evaluate to true.
10363     return true;
10364   } else {
10365     // Any other base is not constant enough for GCC.
10366     return false;
10367   }
10368 }
10369 
10370 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
10371 /// GCC as we can manage.
10372 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
10373   // This evaluation is not permitted to have side-effects, so evaluate it in
10374   // a speculative evaluation context.
10375   SpeculativeEvaluationRAII SpeculativeEval(Info);
10376 
10377   // Constant-folding is always enabled for the operand of __builtin_constant_p
10378   // (even when the enclosing evaluation context otherwise requires a strict
10379   // language-specific constant expression).
10380   FoldConstant Fold(Info, true);
10381 
10382   QualType ArgType = Arg->getType();
10383 
10384   // __builtin_constant_p always has one operand. The rules which gcc follows
10385   // are not precisely documented, but are as follows:
10386   //
10387   //  - If the operand is of integral, floating, complex or enumeration type,
10388   //    and can be folded to a known value of that type, it returns 1.
10389   //  - If the operand can be folded to a pointer to the first character
10390   //    of a string literal (or such a pointer cast to an integral type)
10391   //    or to a null pointer or an integer cast to a pointer, it returns 1.
10392   //
10393   // Otherwise, it returns 0.
10394   //
10395   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
10396   // its support for this did not work prior to GCC 9 and is not yet well
10397   // understood.
10398   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
10399       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
10400       ArgType->isNullPtrType()) {
10401     APValue V;
10402     if (!::EvaluateAsRValue(Info, Arg, V)) {
10403       Fold.keepDiagnostics();
10404       return false;
10405     }
10406 
10407     // For a pointer (possibly cast to integer), there are special rules.
10408     if (V.getKind() == APValue::LValue)
10409       return EvaluateBuiltinConstantPForLValue(V);
10410 
10411     // Otherwise, any constant value is good enough.
10412     return V.hasValue();
10413   }
10414 
10415   // Anything else isn't considered to be sufficiently constant.
10416   return false;
10417 }
10418 
10419 /// Retrieves the "underlying object type" of the given expression,
10420 /// as used by __builtin_object_size.
10421 static QualType getObjectType(APValue::LValueBase B) {
10422   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
10423     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
10424       return VD->getType();
10425   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
10426     if (isa<CompoundLiteralExpr>(E))
10427       return E->getType();
10428   } else if (B.is<TypeInfoLValue>()) {
10429     return B.getTypeInfoType();
10430   } else if (B.is<DynamicAllocLValue>()) {
10431     return B.getDynamicAllocType();
10432   }
10433 
10434   return QualType();
10435 }
10436 
10437 /// A more selective version of E->IgnoreParenCasts for
10438 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
10439 /// to change the type of E.
10440 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
10441 ///
10442 /// Always returns an RValue with a pointer representation.
10443 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
10444   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
10445 
10446   auto *NoParens = E->IgnoreParens();
10447   auto *Cast = dyn_cast<CastExpr>(NoParens);
10448   if (Cast == nullptr)
10449     return NoParens;
10450 
10451   // We only conservatively allow a few kinds of casts, because this code is
10452   // inherently a simple solution that seeks to support the common case.
10453   auto CastKind = Cast->getCastKind();
10454   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
10455       CastKind != CK_AddressSpaceConversion)
10456     return NoParens;
10457 
10458   auto *SubExpr = Cast->getSubExpr();
10459   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
10460     return NoParens;
10461   return ignorePointerCastsAndParens(SubExpr);
10462 }
10463 
10464 /// Checks to see if the given LValue's Designator is at the end of the LValue's
10465 /// record layout. e.g.
10466 ///   struct { struct { int a, b; } fst, snd; } obj;
10467 ///   obj.fst   // no
10468 ///   obj.snd   // yes
10469 ///   obj.fst.a // no
10470 ///   obj.fst.b // no
10471 ///   obj.snd.a // no
10472 ///   obj.snd.b // yes
10473 ///
10474 /// Please note: this function is specialized for how __builtin_object_size
10475 /// views "objects".
10476 ///
10477 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
10478 /// correct result, it will always return true.
10479 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
10480   assert(!LVal.Designator.Invalid);
10481 
10482   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
10483     const RecordDecl *Parent = FD->getParent();
10484     Invalid = Parent->isInvalidDecl();
10485     if (Invalid || Parent->isUnion())
10486       return true;
10487     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
10488     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
10489   };
10490 
10491   auto &Base = LVal.getLValueBase();
10492   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
10493     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
10494       bool Invalid;
10495       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10496         return Invalid;
10497     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
10498       for (auto *FD : IFD->chain()) {
10499         bool Invalid;
10500         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
10501           return Invalid;
10502       }
10503     }
10504   }
10505 
10506   unsigned I = 0;
10507   QualType BaseType = getType(Base);
10508   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
10509     // If we don't know the array bound, conservatively assume we're looking at
10510     // the final array element.
10511     ++I;
10512     if (BaseType->isIncompleteArrayType())
10513       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
10514     else
10515       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
10516   }
10517 
10518   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
10519     const auto &Entry = LVal.Designator.Entries[I];
10520     if (BaseType->isArrayType()) {
10521       // Because __builtin_object_size treats arrays as objects, we can ignore
10522       // the index iff this is the last array in the Designator.
10523       if (I + 1 == E)
10524         return true;
10525       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
10526       uint64_t Index = Entry.getAsArrayIndex();
10527       if (Index + 1 != CAT->getSize())
10528         return false;
10529       BaseType = CAT->getElementType();
10530     } else if (BaseType->isAnyComplexType()) {
10531       const auto *CT = BaseType->castAs<ComplexType>();
10532       uint64_t Index = Entry.getAsArrayIndex();
10533       if (Index != 1)
10534         return false;
10535       BaseType = CT->getElementType();
10536     } else if (auto *FD = getAsField(Entry)) {
10537       bool Invalid;
10538       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
10539         return Invalid;
10540       BaseType = FD->getType();
10541     } else {
10542       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
10543       return false;
10544     }
10545   }
10546   return true;
10547 }
10548 
10549 /// Tests to see if the LValue has a user-specified designator (that isn't
10550 /// necessarily valid). Note that this always returns 'true' if the LValue has
10551 /// an unsized array as its first designator entry, because there's currently no
10552 /// way to tell if the user typed *foo or foo[0].
10553 static bool refersToCompleteObject(const LValue &LVal) {
10554   if (LVal.Designator.Invalid)
10555     return false;
10556 
10557   if (!LVal.Designator.Entries.empty())
10558     return LVal.Designator.isMostDerivedAnUnsizedArray();
10559 
10560   if (!LVal.InvalidBase)
10561     return true;
10562 
10563   // If `E` is a MemberExpr, then the first part of the designator is hiding in
10564   // the LValueBase.
10565   const auto *E = LVal.Base.dyn_cast<const Expr *>();
10566   return !E || !isa<MemberExpr>(E);
10567 }
10568 
10569 /// Attempts to detect a user writing into a piece of memory that's impossible
10570 /// to figure out the size of by just using types.
10571 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
10572   const SubobjectDesignator &Designator = LVal.Designator;
10573   // Notes:
10574   // - Users can only write off of the end when we have an invalid base. Invalid
10575   //   bases imply we don't know where the memory came from.
10576   // - We used to be a bit more aggressive here; we'd only be conservative if
10577   //   the array at the end was flexible, or if it had 0 or 1 elements. This
10578   //   broke some common standard library extensions (PR30346), but was
10579   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
10580   //   with some sort of whitelist. OTOH, it seems that GCC is always
10581   //   conservative with the last element in structs (if it's an array), so our
10582   //   current behavior is more compatible than a whitelisting approach would
10583   //   be.
10584   return LVal.InvalidBase &&
10585          Designator.Entries.size() == Designator.MostDerivedPathLength &&
10586          Designator.MostDerivedIsArrayElement &&
10587          isDesignatorAtObjectEnd(Ctx, LVal);
10588 }
10589 
10590 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
10591 /// Fails if the conversion would cause loss of precision.
10592 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
10593                                             CharUnits &Result) {
10594   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
10595   if (Int.ugt(CharUnitsMax))
10596     return false;
10597   Result = CharUnits::fromQuantity(Int.getZExtValue());
10598   return true;
10599 }
10600 
10601 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
10602 /// determine how many bytes exist from the beginning of the object to either
10603 /// the end of the current subobject, or the end of the object itself, depending
10604 /// on what the LValue looks like + the value of Type.
10605 ///
10606 /// If this returns false, the value of Result is undefined.
10607 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
10608                                unsigned Type, const LValue &LVal,
10609                                CharUnits &EndOffset) {
10610   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
10611 
10612   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
10613     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
10614       return false;
10615     return HandleSizeof(Info, ExprLoc, Ty, Result);
10616   };
10617 
10618   // We want to evaluate the size of the entire object. This is a valid fallback
10619   // for when Type=1 and the designator is invalid, because we're asked for an
10620   // upper-bound.
10621   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
10622     // Type=3 wants a lower bound, so we can't fall back to this.
10623     if (Type == 3 && !DetermineForCompleteObject)
10624       return false;
10625 
10626     llvm::APInt APEndOffset;
10627     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10628         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10629       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10630 
10631     if (LVal.InvalidBase)
10632       return false;
10633 
10634     QualType BaseTy = getObjectType(LVal.getLValueBase());
10635     return CheckedHandleSizeof(BaseTy, EndOffset);
10636   }
10637 
10638   // We want to evaluate the size of a subobject.
10639   const SubobjectDesignator &Designator = LVal.Designator;
10640 
10641   // The following is a moderately common idiom in C:
10642   //
10643   // struct Foo { int a; char c[1]; };
10644   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
10645   // strcpy(&F->c[0], Bar);
10646   //
10647   // In order to not break too much legacy code, we need to support it.
10648   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
10649     // If we can resolve this to an alloc_size call, we can hand that back,
10650     // because we know for certain how many bytes there are to write to.
10651     llvm::APInt APEndOffset;
10652     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
10653         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
10654       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
10655 
10656     // If we cannot determine the size of the initial allocation, then we can't
10657     // given an accurate upper-bound. However, we are still able to give
10658     // conservative lower-bounds for Type=3.
10659     if (Type == 1)
10660       return false;
10661   }
10662 
10663   CharUnits BytesPerElem;
10664   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
10665     return false;
10666 
10667   // According to the GCC documentation, we want the size of the subobject
10668   // denoted by the pointer. But that's not quite right -- what we actually
10669   // want is the size of the immediately-enclosing array, if there is one.
10670   int64_t ElemsRemaining;
10671   if (Designator.MostDerivedIsArrayElement &&
10672       Designator.Entries.size() == Designator.MostDerivedPathLength) {
10673     uint64_t ArraySize = Designator.getMostDerivedArraySize();
10674     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
10675     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
10676   } else {
10677     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
10678   }
10679 
10680   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
10681   return true;
10682 }
10683 
10684 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
10685 /// returns true and stores the result in @p Size.
10686 ///
10687 /// If @p WasError is non-null, this will report whether the failure to evaluate
10688 /// is to be treated as an Error in IntExprEvaluator.
10689 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
10690                                          EvalInfo &Info, uint64_t &Size) {
10691   // Determine the denoted object.
10692   LValue LVal;
10693   {
10694     // The operand of __builtin_object_size is never evaluated for side-effects.
10695     // If there are any, but we can determine the pointed-to object anyway, then
10696     // ignore the side-effects.
10697     SpeculativeEvaluationRAII SpeculativeEval(Info);
10698     IgnoreSideEffectsRAII Fold(Info);
10699 
10700     if (E->isGLValue()) {
10701       // It's possible for us to be given GLValues if we're called via
10702       // Expr::tryEvaluateObjectSize.
10703       APValue RVal;
10704       if (!EvaluateAsRValue(Info, E, RVal))
10705         return false;
10706       LVal.setFrom(Info.Ctx, RVal);
10707     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
10708                                 /*InvalidBaseOK=*/true))
10709       return false;
10710   }
10711 
10712   // If we point to before the start of the object, there are no accessible
10713   // bytes.
10714   if (LVal.getLValueOffset().isNegative()) {
10715     Size = 0;
10716     return true;
10717   }
10718 
10719   CharUnits EndOffset;
10720   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
10721     return false;
10722 
10723   // If we've fallen outside of the end offset, just pretend there's nothing to
10724   // write to/read from.
10725   if (EndOffset <= LVal.getLValueOffset())
10726     Size = 0;
10727   else
10728     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
10729   return true;
10730 }
10731 
10732 bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
10733   llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
10734   if (E->getResultAPValueKind() != APValue::None)
10735     return Success(E->getAPValueResult(), E);
10736   return ExprEvaluatorBaseTy::VisitConstantExpr(E);
10737 }
10738 
10739 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
10740   if (unsigned BuiltinOp = E->getBuiltinCallee())
10741     return VisitBuiltinCallExpr(E, BuiltinOp);
10742 
10743   return ExprEvaluatorBaseTy::VisitCallExpr(E);
10744 }
10745 
10746 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
10747                                      APValue &Val, APSInt &Alignment) {
10748   QualType SrcTy = E->getArg(0)->getType();
10749   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
10750     return false;
10751   // Even though we are evaluating integer expressions we could get a pointer
10752   // argument for the __builtin_is_aligned() case.
10753   if (SrcTy->isPointerType()) {
10754     LValue Ptr;
10755     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
10756       return false;
10757     Ptr.moveInto(Val);
10758   } else if (!SrcTy->isIntegralOrEnumerationType()) {
10759     Info.FFDiag(E->getArg(0));
10760     return false;
10761   } else {
10762     APSInt SrcInt;
10763     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
10764       return false;
10765     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
10766            "Bit widths must be the same");
10767     Val = APValue(SrcInt);
10768   }
10769   assert(Val.hasValue());
10770   return true;
10771 }
10772 
10773 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
10774                                             unsigned BuiltinOp) {
10775   switch (BuiltinOp) {
10776   default:
10777     return ExprEvaluatorBaseTy::VisitCallExpr(E);
10778 
10779   case Builtin::BI__builtin_dynamic_object_size:
10780   case Builtin::BI__builtin_object_size: {
10781     // The type was checked when we built the expression.
10782     unsigned Type =
10783         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
10784     assert(Type <= 3 && "unexpected type");
10785 
10786     uint64_t Size;
10787     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
10788       return Success(Size, E);
10789 
10790     if (E->getArg(0)->HasSideEffects(Info.Ctx))
10791       return Success((Type & 2) ? 0 : -1, E);
10792 
10793     // Expression had no side effects, but we couldn't statically determine the
10794     // size of the referenced object.
10795     switch (Info.EvalMode) {
10796     case EvalInfo::EM_ConstantExpression:
10797     case EvalInfo::EM_ConstantFold:
10798     case EvalInfo::EM_IgnoreSideEffects:
10799       // Leave it to IR generation.
10800       return Error(E);
10801     case EvalInfo::EM_ConstantExpressionUnevaluated:
10802       // Reduce it to a constant now.
10803       return Success((Type & 2) ? 0 : -1, E);
10804     }
10805 
10806     llvm_unreachable("unexpected EvalMode");
10807   }
10808 
10809   case Builtin::BI__builtin_os_log_format_buffer_size: {
10810     analyze_os_log::OSLogBufferLayout Layout;
10811     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
10812     return Success(Layout.size().getQuantity(), E);
10813   }
10814 
10815   case Builtin::BI__builtin_is_aligned: {
10816     APValue Src;
10817     APSInt Alignment;
10818     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
10819       return false;
10820     if (Src.isLValue()) {
10821       // If we evaluated a pointer, check the minimum known alignment.
10822       LValue Ptr;
10823       Ptr.setFrom(Info.Ctx, Src);
10824       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
10825       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
10826       // We can return true if the known alignment at the computed offset is
10827       // greater than the requested alignment.
10828       assert(PtrAlign.isPowerOfTwo());
10829       assert(Alignment.isPowerOf2());
10830       if (PtrAlign.getQuantity() >= Alignment)
10831         return Success(1, E);
10832       // If the alignment is not known to be sufficient, some cases could still
10833       // be aligned at run time. However, if the requested alignment is less or
10834       // equal to the base alignment and the offset is not aligned, we know that
10835       // the run-time value can never be aligned.
10836       if (BaseAlignment.getQuantity() >= Alignment &&
10837           PtrAlign.getQuantity() < Alignment)
10838         return Success(0, E);
10839       // Otherwise we can't infer whether the value is sufficiently aligned.
10840       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
10841       //  in cases where we can't fully evaluate the pointer.
10842       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
10843           << Alignment;
10844       return false;
10845     }
10846     assert(Src.isInt());
10847     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
10848   }
10849   case Builtin::BI__builtin_align_up: {
10850     APValue Src;
10851     APSInt Alignment;
10852     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
10853       return false;
10854     if (!Src.isInt())
10855       return Error(E);
10856     APSInt AlignedVal =
10857         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
10858                Src.getInt().isUnsigned());
10859     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
10860     return Success(AlignedVal, E);
10861   }
10862   case Builtin::BI__builtin_align_down: {
10863     APValue Src;
10864     APSInt Alignment;
10865     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
10866       return false;
10867     if (!Src.isInt())
10868       return Error(E);
10869     APSInt AlignedVal =
10870         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
10871     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
10872     return Success(AlignedVal, E);
10873   }
10874 
10875   case Builtin::BI__builtin_bswap16:
10876   case Builtin::BI__builtin_bswap32:
10877   case Builtin::BI__builtin_bswap64: {
10878     APSInt Val;
10879     if (!EvaluateInteger(E->getArg(0), Val, Info))
10880       return false;
10881 
10882     return Success(Val.byteSwap(), E);
10883   }
10884 
10885   case Builtin::BI__builtin_classify_type:
10886     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
10887 
10888   case Builtin::BI__builtin_clrsb:
10889   case Builtin::BI__builtin_clrsbl:
10890   case Builtin::BI__builtin_clrsbll: {
10891     APSInt Val;
10892     if (!EvaluateInteger(E->getArg(0), Val, Info))
10893       return false;
10894 
10895     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
10896   }
10897 
10898   case Builtin::BI__builtin_clz:
10899   case Builtin::BI__builtin_clzl:
10900   case Builtin::BI__builtin_clzll:
10901   case Builtin::BI__builtin_clzs: {
10902     APSInt Val;
10903     if (!EvaluateInteger(E->getArg(0), Val, Info))
10904       return false;
10905     if (!Val)
10906       return Error(E);
10907 
10908     return Success(Val.countLeadingZeros(), E);
10909   }
10910 
10911   case Builtin::BI__builtin_constant_p: {
10912     const Expr *Arg = E->getArg(0);
10913     if (EvaluateBuiltinConstantP(Info, Arg))
10914       return Success(true, E);
10915     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
10916       // Outside a constant context, eagerly evaluate to false in the presence
10917       // of side-effects in order to avoid -Wunsequenced false-positives in
10918       // a branch on __builtin_constant_p(expr).
10919       return Success(false, E);
10920     }
10921     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10922     return false;
10923   }
10924 
10925   case Builtin::BI__builtin_is_constant_evaluated: {
10926     const auto *Callee = Info.CurrentCall->getCallee();
10927     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
10928         (Info.CallStackDepth == 1 ||
10929          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
10930           Callee->getIdentifier() &&
10931           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
10932       // FIXME: Find a better way to avoid duplicated diagnostics.
10933       if (Info.EvalStatus.Diag)
10934         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
10935                                                : Info.CurrentCall->CallLoc,
10936                     diag::warn_is_constant_evaluated_always_true_constexpr)
10937             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
10938                                          : "std::is_constant_evaluated");
10939     }
10940 
10941     return Success(Info.InConstantContext, E);
10942   }
10943 
10944   case Builtin::BI__builtin_ctz:
10945   case Builtin::BI__builtin_ctzl:
10946   case Builtin::BI__builtin_ctzll:
10947   case Builtin::BI__builtin_ctzs: {
10948     APSInt Val;
10949     if (!EvaluateInteger(E->getArg(0), Val, Info))
10950       return false;
10951     if (!Val)
10952       return Error(E);
10953 
10954     return Success(Val.countTrailingZeros(), E);
10955   }
10956 
10957   case Builtin::BI__builtin_eh_return_data_regno: {
10958     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
10959     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
10960     return Success(Operand, E);
10961   }
10962 
10963   case Builtin::BI__builtin_expect:
10964     return Visit(E->getArg(0));
10965 
10966   case Builtin::BI__builtin_ffs:
10967   case Builtin::BI__builtin_ffsl:
10968   case Builtin::BI__builtin_ffsll: {
10969     APSInt Val;
10970     if (!EvaluateInteger(E->getArg(0), Val, Info))
10971       return false;
10972 
10973     unsigned N = Val.countTrailingZeros();
10974     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
10975   }
10976 
10977   case Builtin::BI__builtin_fpclassify: {
10978     APFloat Val(0.0);
10979     if (!EvaluateFloat(E->getArg(5), Val, Info))
10980       return false;
10981     unsigned Arg;
10982     switch (Val.getCategory()) {
10983     case APFloat::fcNaN: Arg = 0; break;
10984     case APFloat::fcInfinity: Arg = 1; break;
10985     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
10986     case APFloat::fcZero: Arg = 4; break;
10987     }
10988     return Visit(E->getArg(Arg));
10989   }
10990 
10991   case Builtin::BI__builtin_isinf_sign: {
10992     APFloat Val(0.0);
10993     return EvaluateFloat(E->getArg(0), Val, Info) &&
10994            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
10995   }
10996 
10997   case Builtin::BI__builtin_isinf: {
10998     APFloat Val(0.0);
10999     return EvaluateFloat(E->getArg(0), Val, Info) &&
11000            Success(Val.isInfinity() ? 1 : 0, E);
11001   }
11002 
11003   case Builtin::BI__builtin_isfinite: {
11004     APFloat Val(0.0);
11005     return EvaluateFloat(E->getArg(0), Val, Info) &&
11006            Success(Val.isFinite() ? 1 : 0, E);
11007   }
11008 
11009   case Builtin::BI__builtin_isnan: {
11010     APFloat Val(0.0);
11011     return EvaluateFloat(E->getArg(0), Val, Info) &&
11012            Success(Val.isNaN() ? 1 : 0, E);
11013   }
11014 
11015   case Builtin::BI__builtin_isnormal: {
11016     APFloat Val(0.0);
11017     return EvaluateFloat(E->getArg(0), Val, Info) &&
11018            Success(Val.isNormal() ? 1 : 0, E);
11019   }
11020 
11021   case Builtin::BI__builtin_parity:
11022   case Builtin::BI__builtin_parityl:
11023   case Builtin::BI__builtin_parityll: {
11024     APSInt Val;
11025     if (!EvaluateInteger(E->getArg(0), Val, Info))
11026       return false;
11027 
11028     return Success(Val.countPopulation() % 2, E);
11029   }
11030 
11031   case Builtin::BI__builtin_popcount:
11032   case Builtin::BI__builtin_popcountl:
11033   case Builtin::BI__builtin_popcountll: {
11034     APSInt Val;
11035     if (!EvaluateInteger(E->getArg(0), Val, Info))
11036       return false;
11037 
11038     return Success(Val.countPopulation(), E);
11039   }
11040 
11041   case Builtin::BIstrlen:
11042   case Builtin::BIwcslen:
11043     // A call to strlen is not a constant expression.
11044     if (Info.getLangOpts().CPlusPlus11)
11045       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11046         << /*isConstexpr*/0 << /*isConstructor*/0
11047         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11048     else
11049       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11050     LLVM_FALLTHROUGH;
11051   case Builtin::BI__builtin_strlen:
11052   case Builtin::BI__builtin_wcslen: {
11053     // As an extension, we support __builtin_strlen() as a constant expression,
11054     // and support folding strlen() to a constant.
11055     LValue String;
11056     if (!EvaluatePointer(E->getArg(0), String, Info))
11057       return false;
11058 
11059     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
11060 
11061     // Fast path: if it's a string literal, search the string value.
11062     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
11063             String.getLValueBase().dyn_cast<const Expr *>())) {
11064       // The string literal may have embedded null characters. Find the first
11065       // one and truncate there.
11066       StringRef Str = S->getBytes();
11067       int64_t Off = String.Offset.getQuantity();
11068       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
11069           S->getCharByteWidth() == 1 &&
11070           // FIXME: Add fast-path for wchar_t too.
11071           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
11072         Str = Str.substr(Off);
11073 
11074         StringRef::size_type Pos = Str.find(0);
11075         if (Pos != StringRef::npos)
11076           Str = Str.substr(0, Pos);
11077 
11078         return Success(Str.size(), E);
11079       }
11080 
11081       // Fall through to slow path to issue appropriate diagnostic.
11082     }
11083 
11084     // Slow path: scan the bytes of the string looking for the terminating 0.
11085     for (uint64_t Strlen = 0; /**/; ++Strlen) {
11086       APValue Char;
11087       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
11088           !Char.isInt())
11089         return false;
11090       if (!Char.getInt())
11091         return Success(Strlen, E);
11092       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
11093         return false;
11094     }
11095   }
11096 
11097   case Builtin::BIstrcmp:
11098   case Builtin::BIwcscmp:
11099   case Builtin::BIstrncmp:
11100   case Builtin::BIwcsncmp:
11101   case Builtin::BImemcmp:
11102   case Builtin::BIbcmp:
11103   case Builtin::BIwmemcmp:
11104     // A call to strlen is not a constant expression.
11105     if (Info.getLangOpts().CPlusPlus11)
11106       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11107         << /*isConstexpr*/0 << /*isConstructor*/0
11108         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11109     else
11110       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11111     LLVM_FALLTHROUGH;
11112   case Builtin::BI__builtin_strcmp:
11113   case Builtin::BI__builtin_wcscmp:
11114   case Builtin::BI__builtin_strncmp:
11115   case Builtin::BI__builtin_wcsncmp:
11116   case Builtin::BI__builtin_memcmp:
11117   case Builtin::BI__builtin_bcmp:
11118   case Builtin::BI__builtin_wmemcmp: {
11119     LValue String1, String2;
11120     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
11121         !EvaluatePointer(E->getArg(1), String2, Info))
11122       return false;
11123 
11124     uint64_t MaxLength = uint64_t(-1);
11125     if (BuiltinOp != Builtin::BIstrcmp &&
11126         BuiltinOp != Builtin::BIwcscmp &&
11127         BuiltinOp != Builtin::BI__builtin_strcmp &&
11128         BuiltinOp != Builtin::BI__builtin_wcscmp) {
11129       APSInt N;
11130       if (!EvaluateInteger(E->getArg(2), N, Info))
11131         return false;
11132       MaxLength = N.getExtValue();
11133     }
11134 
11135     // Empty substrings compare equal by definition.
11136     if (MaxLength == 0u)
11137       return Success(0, E);
11138 
11139     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11140         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11141         String1.Designator.Invalid || String2.Designator.Invalid)
11142       return false;
11143 
11144     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
11145     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
11146 
11147     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
11148                      BuiltinOp == Builtin::BIbcmp ||
11149                      BuiltinOp == Builtin::BI__builtin_memcmp ||
11150                      BuiltinOp == Builtin::BI__builtin_bcmp;
11151 
11152     assert(IsRawByte ||
11153            (Info.Ctx.hasSameUnqualifiedType(
11154                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
11155             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
11156 
11157     // For memcmp, allow comparing any arrays of '[[un]signed] char',
11158     // but no other types.
11159     if (IsRawByte && !(CharTy1->isCharType() && CharTy2->isCharType())) {
11160       // FIXME: Consider using our bit_cast implementation to support this.
11161       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
11162           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
11163           << CharTy1 << CharTy2;
11164       return false;
11165     }
11166 
11167     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
11168       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
11169              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
11170              Char1.isInt() && Char2.isInt();
11171     };
11172     const auto &AdvanceElems = [&] {
11173       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
11174              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
11175     };
11176 
11177     bool StopAtNull =
11178         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
11179          BuiltinOp != Builtin::BIwmemcmp &&
11180          BuiltinOp != Builtin::BI__builtin_memcmp &&
11181          BuiltinOp != Builtin::BI__builtin_bcmp &&
11182          BuiltinOp != Builtin::BI__builtin_wmemcmp);
11183     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
11184                   BuiltinOp == Builtin::BIwcsncmp ||
11185                   BuiltinOp == Builtin::BIwmemcmp ||
11186                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
11187                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
11188                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
11189 
11190     for (; MaxLength; --MaxLength) {
11191       APValue Char1, Char2;
11192       if (!ReadCurElems(Char1, Char2))
11193         return false;
11194       if (Char1.getInt().ne(Char2.getInt())) {
11195         if (IsWide) // wmemcmp compares with wchar_t signedness.
11196           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
11197         // memcmp always compares unsigned chars.
11198         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
11199       }
11200       if (StopAtNull && !Char1.getInt())
11201         return Success(0, E);
11202       assert(!(StopAtNull && !Char2.getInt()));
11203       if (!AdvanceElems())
11204         return false;
11205     }
11206     // We hit the strncmp / memcmp limit.
11207     return Success(0, E);
11208   }
11209 
11210   case Builtin::BI__atomic_always_lock_free:
11211   case Builtin::BI__atomic_is_lock_free:
11212   case Builtin::BI__c11_atomic_is_lock_free: {
11213     APSInt SizeVal;
11214     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
11215       return false;
11216 
11217     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
11218     // of two less than the maximum inline atomic width, we know it is
11219     // lock-free.  If the size isn't a power of two, or greater than the
11220     // maximum alignment where we promote atomics, we know it is not lock-free
11221     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
11222     // the answer can only be determined at runtime; for example, 16-byte
11223     // atomics have lock-free implementations on some, but not all,
11224     // x86-64 processors.
11225 
11226     // Check power-of-two.
11227     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
11228     if (Size.isPowerOfTwo()) {
11229       // Check against inlining width.
11230       unsigned InlineWidthBits =
11231           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
11232       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
11233         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
11234             Size == CharUnits::One() ||
11235             E->getArg(1)->isNullPointerConstant(Info.Ctx,
11236                                                 Expr::NPC_NeverValueDependent))
11237           // OK, we will inline appropriately-aligned operations of this size,
11238           // and _Atomic(T) is appropriately-aligned.
11239           return Success(1, E);
11240 
11241         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
11242           castAs<PointerType>()->getPointeeType();
11243         if (!PointeeType->isIncompleteType() &&
11244             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
11245           // OK, we will inline operations on this object.
11246           return Success(1, E);
11247         }
11248       }
11249     }
11250 
11251     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
11252         Success(0, E) : Error(E);
11253   }
11254   case Builtin::BIomp_is_initial_device:
11255     // We can decide statically which value the runtime would return if called.
11256     return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
11257   case Builtin::BI__builtin_add_overflow:
11258   case Builtin::BI__builtin_sub_overflow:
11259   case Builtin::BI__builtin_mul_overflow:
11260   case Builtin::BI__builtin_sadd_overflow:
11261   case Builtin::BI__builtin_uadd_overflow:
11262   case Builtin::BI__builtin_uaddl_overflow:
11263   case Builtin::BI__builtin_uaddll_overflow:
11264   case Builtin::BI__builtin_usub_overflow:
11265   case Builtin::BI__builtin_usubl_overflow:
11266   case Builtin::BI__builtin_usubll_overflow:
11267   case Builtin::BI__builtin_umul_overflow:
11268   case Builtin::BI__builtin_umull_overflow:
11269   case Builtin::BI__builtin_umulll_overflow:
11270   case Builtin::BI__builtin_saddl_overflow:
11271   case Builtin::BI__builtin_saddll_overflow:
11272   case Builtin::BI__builtin_ssub_overflow:
11273   case Builtin::BI__builtin_ssubl_overflow:
11274   case Builtin::BI__builtin_ssubll_overflow:
11275   case Builtin::BI__builtin_smul_overflow:
11276   case Builtin::BI__builtin_smull_overflow:
11277   case Builtin::BI__builtin_smulll_overflow: {
11278     LValue ResultLValue;
11279     APSInt LHS, RHS;
11280 
11281     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
11282     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
11283         !EvaluateInteger(E->getArg(1), RHS, Info) ||
11284         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
11285       return false;
11286 
11287     APSInt Result;
11288     bool DidOverflow = false;
11289 
11290     // If the types don't have to match, enlarge all 3 to the largest of them.
11291     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11292         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11293         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11294       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
11295                       ResultType->isSignedIntegerOrEnumerationType();
11296       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
11297                       ResultType->isSignedIntegerOrEnumerationType();
11298       uint64_t LHSSize = LHS.getBitWidth();
11299       uint64_t RHSSize = RHS.getBitWidth();
11300       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
11301       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
11302 
11303       // Add an additional bit if the signedness isn't uniformly agreed to. We
11304       // could do this ONLY if there is a signed and an unsigned that both have
11305       // MaxBits, but the code to check that is pretty nasty.  The issue will be
11306       // caught in the shrink-to-result later anyway.
11307       if (IsSigned && !AllSigned)
11308         ++MaxBits;
11309 
11310       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
11311       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
11312       Result = APSInt(MaxBits, !IsSigned);
11313     }
11314 
11315     // Find largest int.
11316     switch (BuiltinOp) {
11317     default:
11318       llvm_unreachable("Invalid value for BuiltinOp");
11319     case Builtin::BI__builtin_add_overflow:
11320     case Builtin::BI__builtin_sadd_overflow:
11321     case Builtin::BI__builtin_saddl_overflow:
11322     case Builtin::BI__builtin_saddll_overflow:
11323     case Builtin::BI__builtin_uadd_overflow:
11324     case Builtin::BI__builtin_uaddl_overflow:
11325     case Builtin::BI__builtin_uaddll_overflow:
11326       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
11327                               : LHS.uadd_ov(RHS, DidOverflow);
11328       break;
11329     case Builtin::BI__builtin_sub_overflow:
11330     case Builtin::BI__builtin_ssub_overflow:
11331     case Builtin::BI__builtin_ssubl_overflow:
11332     case Builtin::BI__builtin_ssubll_overflow:
11333     case Builtin::BI__builtin_usub_overflow:
11334     case Builtin::BI__builtin_usubl_overflow:
11335     case Builtin::BI__builtin_usubll_overflow:
11336       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
11337                               : LHS.usub_ov(RHS, DidOverflow);
11338       break;
11339     case Builtin::BI__builtin_mul_overflow:
11340     case Builtin::BI__builtin_smul_overflow:
11341     case Builtin::BI__builtin_smull_overflow:
11342     case Builtin::BI__builtin_smulll_overflow:
11343     case Builtin::BI__builtin_umul_overflow:
11344     case Builtin::BI__builtin_umull_overflow:
11345     case Builtin::BI__builtin_umulll_overflow:
11346       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
11347                               : LHS.umul_ov(RHS, DidOverflow);
11348       break;
11349     }
11350 
11351     // In the case where multiple sizes are allowed, truncate and see if
11352     // the values are the same.
11353     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11354         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11355         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11356       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
11357       // since it will give us the behavior of a TruncOrSelf in the case where
11358       // its parameter <= its size.  We previously set Result to be at least the
11359       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
11360       // will work exactly like TruncOrSelf.
11361       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
11362       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
11363 
11364       if (!APSInt::isSameValue(Temp, Result))
11365         DidOverflow = true;
11366       Result = Temp;
11367     }
11368 
11369     APValue APV{Result};
11370     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
11371       return false;
11372     return Success(DidOverflow, E);
11373   }
11374   }
11375 }
11376 
11377 /// Determine whether this is a pointer past the end of the complete
11378 /// object referred to by the lvalue.
11379 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
11380                                             const LValue &LV) {
11381   // A null pointer can be viewed as being "past the end" but we don't
11382   // choose to look at it that way here.
11383   if (!LV.getLValueBase())
11384     return false;
11385 
11386   // If the designator is valid and refers to a subobject, we're not pointing
11387   // past the end.
11388   if (!LV.getLValueDesignator().Invalid &&
11389       !LV.getLValueDesignator().isOnePastTheEnd())
11390     return false;
11391 
11392   // A pointer to an incomplete type might be past-the-end if the type's size is
11393   // zero.  We cannot tell because the type is incomplete.
11394   QualType Ty = getType(LV.getLValueBase());
11395   if (Ty->isIncompleteType())
11396     return true;
11397 
11398   // We're a past-the-end pointer if we point to the byte after the object,
11399   // no matter what our type or path is.
11400   auto Size = Ctx.getTypeSizeInChars(Ty);
11401   return LV.getLValueOffset() == Size;
11402 }
11403 
11404 namespace {
11405 
11406 /// Data recursive integer evaluator of certain binary operators.
11407 ///
11408 /// We use a data recursive algorithm for binary operators so that we are able
11409 /// to handle extreme cases of chained binary operators without causing stack
11410 /// overflow.
11411 class DataRecursiveIntBinOpEvaluator {
11412   struct EvalResult {
11413     APValue Val;
11414     bool Failed;
11415 
11416     EvalResult() : Failed(false) { }
11417 
11418     void swap(EvalResult &RHS) {
11419       Val.swap(RHS.Val);
11420       Failed = RHS.Failed;
11421       RHS.Failed = false;
11422     }
11423   };
11424 
11425   struct Job {
11426     const Expr *E;
11427     EvalResult LHSResult; // meaningful only for binary operator expression.
11428     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
11429 
11430     Job() = default;
11431     Job(Job &&) = default;
11432 
11433     void startSpeculativeEval(EvalInfo &Info) {
11434       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
11435     }
11436 
11437   private:
11438     SpeculativeEvaluationRAII SpecEvalRAII;
11439   };
11440 
11441   SmallVector<Job, 16> Queue;
11442 
11443   IntExprEvaluator &IntEval;
11444   EvalInfo &Info;
11445   APValue &FinalResult;
11446 
11447 public:
11448   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
11449     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
11450 
11451   /// True if \param E is a binary operator that we are going to handle
11452   /// data recursively.
11453   /// We handle binary operators that are comma, logical, or that have operands
11454   /// with integral or enumeration type.
11455   static bool shouldEnqueue(const BinaryOperator *E) {
11456     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
11457            (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
11458             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11459             E->getRHS()->getType()->isIntegralOrEnumerationType());
11460   }
11461 
11462   bool Traverse(const BinaryOperator *E) {
11463     enqueue(E);
11464     EvalResult PrevResult;
11465     while (!Queue.empty())
11466       process(PrevResult);
11467 
11468     if (PrevResult.Failed) return false;
11469 
11470     FinalResult.swap(PrevResult.Val);
11471     return true;
11472   }
11473 
11474 private:
11475   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
11476     return IntEval.Success(Value, E, Result);
11477   }
11478   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
11479     return IntEval.Success(Value, E, Result);
11480   }
11481   bool Error(const Expr *E) {
11482     return IntEval.Error(E);
11483   }
11484   bool Error(const Expr *E, diag::kind D) {
11485     return IntEval.Error(E, D);
11486   }
11487 
11488   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
11489     return Info.CCEDiag(E, D);
11490   }
11491 
11492   // Returns true if visiting the RHS is necessary, false otherwise.
11493   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
11494                          bool &SuppressRHSDiags);
11495 
11496   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
11497                   const BinaryOperator *E, APValue &Result);
11498 
11499   void EvaluateExpr(const Expr *E, EvalResult &Result) {
11500     Result.Failed = !Evaluate(Result.Val, Info, E);
11501     if (Result.Failed)
11502       Result.Val = APValue();
11503   }
11504 
11505   void process(EvalResult &Result);
11506 
11507   void enqueue(const Expr *E) {
11508     E = E->IgnoreParens();
11509     Queue.resize(Queue.size()+1);
11510     Queue.back().E = E;
11511     Queue.back().Kind = Job::AnyExprKind;
11512   }
11513 };
11514 
11515 }
11516 
11517 bool DataRecursiveIntBinOpEvaluator::
11518        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
11519                          bool &SuppressRHSDiags) {
11520   if (E->getOpcode() == BO_Comma) {
11521     // Ignore LHS but note if we could not evaluate it.
11522     if (LHSResult.Failed)
11523       return Info.noteSideEffect();
11524     return true;
11525   }
11526 
11527   if (E->isLogicalOp()) {
11528     bool LHSAsBool;
11529     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
11530       // We were able to evaluate the LHS, see if we can get away with not
11531       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
11532       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
11533         Success(LHSAsBool, E, LHSResult.Val);
11534         return false; // Ignore RHS
11535       }
11536     } else {
11537       LHSResult.Failed = true;
11538 
11539       // Since we weren't able to evaluate the left hand side, it
11540       // might have had side effects.
11541       if (!Info.noteSideEffect())
11542         return false;
11543 
11544       // We can't evaluate the LHS; however, sometimes the result
11545       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
11546       // Don't ignore RHS and suppress diagnostics from this arm.
11547       SuppressRHSDiags = true;
11548     }
11549 
11550     return true;
11551   }
11552 
11553   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11554          E->getRHS()->getType()->isIntegralOrEnumerationType());
11555 
11556   if (LHSResult.Failed && !Info.noteFailure())
11557     return false; // Ignore RHS;
11558 
11559   return true;
11560 }
11561 
11562 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
11563                                     bool IsSub) {
11564   // Compute the new offset in the appropriate width, wrapping at 64 bits.
11565   // FIXME: When compiling for a 32-bit target, we should use 32-bit
11566   // offsets.
11567   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
11568   CharUnits &Offset = LVal.getLValueOffset();
11569   uint64_t Offset64 = Offset.getQuantity();
11570   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
11571   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
11572                                          : Offset64 + Index64);
11573 }
11574 
11575 bool DataRecursiveIntBinOpEvaluator::
11576        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
11577                   const BinaryOperator *E, APValue &Result) {
11578   if (E->getOpcode() == BO_Comma) {
11579     if (RHSResult.Failed)
11580       return false;
11581     Result = RHSResult.Val;
11582     return true;
11583   }
11584 
11585   if (E->isLogicalOp()) {
11586     bool lhsResult, rhsResult;
11587     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
11588     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
11589 
11590     if (LHSIsOK) {
11591       if (RHSIsOK) {
11592         if (E->getOpcode() == BO_LOr)
11593           return Success(lhsResult || rhsResult, E, Result);
11594         else
11595           return Success(lhsResult && rhsResult, E, Result);
11596       }
11597     } else {
11598       if (RHSIsOK) {
11599         // We can't evaluate the LHS; however, sometimes the result
11600         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
11601         if (rhsResult == (E->getOpcode() == BO_LOr))
11602           return Success(rhsResult, E, Result);
11603       }
11604     }
11605 
11606     return false;
11607   }
11608 
11609   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
11610          E->getRHS()->getType()->isIntegralOrEnumerationType());
11611 
11612   if (LHSResult.Failed || RHSResult.Failed)
11613     return false;
11614 
11615   const APValue &LHSVal = LHSResult.Val;
11616   const APValue &RHSVal = RHSResult.Val;
11617 
11618   // Handle cases like (unsigned long)&a + 4.
11619   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
11620     Result = LHSVal;
11621     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
11622     return true;
11623   }
11624 
11625   // Handle cases like 4 + (unsigned long)&a
11626   if (E->getOpcode() == BO_Add &&
11627       RHSVal.isLValue() && LHSVal.isInt()) {
11628     Result = RHSVal;
11629     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
11630     return true;
11631   }
11632 
11633   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
11634     // Handle (intptr_t)&&A - (intptr_t)&&B.
11635     if (!LHSVal.getLValueOffset().isZero() ||
11636         !RHSVal.getLValueOffset().isZero())
11637       return false;
11638     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
11639     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
11640     if (!LHSExpr || !RHSExpr)
11641       return false;
11642     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
11643     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
11644     if (!LHSAddrExpr || !RHSAddrExpr)
11645       return false;
11646     // Make sure both labels come from the same function.
11647     if (LHSAddrExpr->getLabel()->getDeclContext() !=
11648         RHSAddrExpr->getLabel()->getDeclContext())
11649       return false;
11650     Result = APValue(LHSAddrExpr, RHSAddrExpr);
11651     return true;
11652   }
11653 
11654   // All the remaining cases expect both operands to be an integer
11655   if (!LHSVal.isInt() || !RHSVal.isInt())
11656     return Error(E);
11657 
11658   // Set up the width and signedness manually, in case it can't be deduced
11659   // from the operation we're performing.
11660   // FIXME: Don't do this in the cases where we can deduce it.
11661   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
11662                E->getType()->isUnsignedIntegerOrEnumerationType());
11663   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
11664                          RHSVal.getInt(), Value))
11665     return false;
11666   return Success(Value, E, Result);
11667 }
11668 
11669 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
11670   Job &job = Queue.back();
11671 
11672   switch (job.Kind) {
11673     case Job::AnyExprKind: {
11674       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
11675         if (shouldEnqueue(Bop)) {
11676           job.Kind = Job::BinOpKind;
11677           enqueue(Bop->getLHS());
11678           return;
11679         }
11680       }
11681 
11682       EvaluateExpr(job.E, Result);
11683       Queue.pop_back();
11684       return;
11685     }
11686 
11687     case Job::BinOpKind: {
11688       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
11689       bool SuppressRHSDiags = false;
11690       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
11691         Queue.pop_back();
11692         return;
11693       }
11694       if (SuppressRHSDiags)
11695         job.startSpeculativeEval(Info);
11696       job.LHSResult.swap(Result);
11697       job.Kind = Job::BinOpVisitedLHSKind;
11698       enqueue(Bop->getRHS());
11699       return;
11700     }
11701 
11702     case Job::BinOpVisitedLHSKind: {
11703       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
11704       EvalResult RHS;
11705       RHS.swap(Result);
11706       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
11707       Queue.pop_back();
11708       return;
11709     }
11710   }
11711 
11712   llvm_unreachable("Invalid Job::Kind!");
11713 }
11714 
11715 namespace {
11716 /// Used when we determine that we should fail, but can keep evaluating prior to
11717 /// noting that we had a failure.
11718 class DelayedNoteFailureRAII {
11719   EvalInfo &Info;
11720   bool NoteFailure;
11721 
11722 public:
11723   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
11724       : Info(Info), NoteFailure(NoteFailure) {}
11725   ~DelayedNoteFailureRAII() {
11726     if (NoteFailure) {
11727       bool ContinueAfterFailure = Info.noteFailure();
11728       (void)ContinueAfterFailure;
11729       assert(ContinueAfterFailure &&
11730              "Shouldn't have kept evaluating on failure.");
11731     }
11732   }
11733 };
11734 
11735 enum class CmpResult {
11736   Unequal,
11737   Less,
11738   Equal,
11739   Greater,
11740   Unordered,
11741 };
11742 }
11743 
11744 template <class SuccessCB, class AfterCB>
11745 static bool
11746 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
11747                                  SuccessCB &&Success, AfterCB &&DoAfter) {
11748   assert(E->isComparisonOp() && "expected comparison operator");
11749   assert((E->getOpcode() == BO_Cmp ||
11750           E->getType()->isIntegralOrEnumerationType()) &&
11751          "unsupported binary expression evaluation");
11752   auto Error = [&](const Expr *E) {
11753     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11754     return false;
11755   };
11756 
11757   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
11758   bool IsEquality = E->isEqualityOp();
11759 
11760   QualType LHSTy = E->getLHS()->getType();
11761   QualType RHSTy = E->getRHS()->getType();
11762 
11763   if (LHSTy->isIntegralOrEnumerationType() &&
11764       RHSTy->isIntegralOrEnumerationType()) {
11765     APSInt LHS, RHS;
11766     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
11767     if (!LHSOK && !Info.noteFailure())
11768       return false;
11769     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
11770       return false;
11771     if (LHS < RHS)
11772       return Success(CmpResult::Less, E);
11773     if (LHS > RHS)
11774       return Success(CmpResult::Greater, E);
11775     return Success(CmpResult::Equal, E);
11776   }
11777 
11778   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
11779     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
11780     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
11781 
11782     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
11783     if (!LHSOK && !Info.noteFailure())
11784       return false;
11785     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
11786       return false;
11787     if (LHSFX < RHSFX)
11788       return Success(CmpResult::Less, E);
11789     if (LHSFX > RHSFX)
11790       return Success(CmpResult::Greater, E);
11791     return Success(CmpResult::Equal, E);
11792   }
11793 
11794   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
11795     ComplexValue LHS, RHS;
11796     bool LHSOK;
11797     if (E->isAssignmentOp()) {
11798       LValue LV;
11799       EvaluateLValue(E->getLHS(), LV, Info);
11800       LHSOK = false;
11801     } else if (LHSTy->isRealFloatingType()) {
11802       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
11803       if (LHSOK) {
11804         LHS.makeComplexFloat();
11805         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
11806       }
11807     } else {
11808       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
11809     }
11810     if (!LHSOK && !Info.noteFailure())
11811       return false;
11812 
11813     if (E->getRHS()->getType()->isRealFloatingType()) {
11814       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
11815         return false;
11816       RHS.makeComplexFloat();
11817       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
11818     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
11819       return false;
11820 
11821     if (LHS.isComplexFloat()) {
11822       APFloat::cmpResult CR_r =
11823         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
11824       APFloat::cmpResult CR_i =
11825         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
11826       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
11827       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
11828     } else {
11829       assert(IsEquality && "invalid complex comparison");
11830       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
11831                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
11832       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
11833     }
11834   }
11835 
11836   if (LHSTy->isRealFloatingType() &&
11837       RHSTy->isRealFloatingType()) {
11838     APFloat RHS(0.0), LHS(0.0);
11839 
11840     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
11841     if (!LHSOK && !Info.noteFailure())
11842       return false;
11843 
11844     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
11845       return false;
11846 
11847     assert(E->isComparisonOp() && "Invalid binary operator!");
11848     auto GetCmpRes = [&]() {
11849       switch (LHS.compare(RHS)) {
11850       case APFloat::cmpEqual:
11851         return CmpResult::Equal;
11852       case APFloat::cmpLessThan:
11853         return CmpResult::Less;
11854       case APFloat::cmpGreaterThan:
11855         return CmpResult::Greater;
11856       case APFloat::cmpUnordered:
11857         return CmpResult::Unordered;
11858       }
11859       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
11860     };
11861     return Success(GetCmpRes(), E);
11862   }
11863 
11864   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
11865     LValue LHSValue, RHSValue;
11866 
11867     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
11868     if (!LHSOK && !Info.noteFailure())
11869       return false;
11870 
11871     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
11872       return false;
11873 
11874     // Reject differing bases from the normal codepath; we special-case
11875     // comparisons to null.
11876     if (!HasSameBase(LHSValue, RHSValue)) {
11877       // Inequalities and subtractions between unrelated pointers have
11878       // unspecified or undefined behavior.
11879       if (!IsEquality) {
11880         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
11881         return false;
11882       }
11883       // A constant address may compare equal to the address of a symbol.
11884       // The one exception is that address of an object cannot compare equal
11885       // to a null pointer constant.
11886       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
11887           (!RHSValue.Base && !RHSValue.Offset.isZero()))
11888         return Error(E);
11889       // It's implementation-defined whether distinct literals will have
11890       // distinct addresses. In clang, the result of such a comparison is
11891       // unspecified, so it is not a constant expression. However, we do know
11892       // that the address of a literal will be non-null.
11893       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
11894           LHSValue.Base && RHSValue.Base)
11895         return Error(E);
11896       // We can't tell whether weak symbols will end up pointing to the same
11897       // object.
11898       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
11899         return Error(E);
11900       // We can't compare the address of the start of one object with the
11901       // past-the-end address of another object, per C++ DR1652.
11902       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
11903            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
11904           (RHSValue.Base && RHSValue.Offset.isZero() &&
11905            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
11906         return Error(E);
11907       // We can't tell whether an object is at the same address as another
11908       // zero sized object.
11909       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
11910           (LHSValue.Base && isZeroSized(RHSValue)))
11911         return Error(E);
11912       return Success(CmpResult::Unequal, E);
11913     }
11914 
11915     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
11916     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
11917 
11918     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
11919     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
11920 
11921     // C++11 [expr.rel]p3:
11922     //   Pointers to void (after pointer conversions) can be compared, with a
11923     //   result defined as follows: If both pointers represent the same
11924     //   address or are both the null pointer value, the result is true if the
11925     //   operator is <= or >= and false otherwise; otherwise the result is
11926     //   unspecified.
11927     // We interpret this as applying to pointers to *cv* void.
11928     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
11929       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
11930 
11931     // C++11 [expr.rel]p2:
11932     // - If two pointers point to non-static data members of the same object,
11933     //   or to subobjects or array elements fo such members, recursively, the
11934     //   pointer to the later declared member compares greater provided the
11935     //   two members have the same access control and provided their class is
11936     //   not a union.
11937     //   [...]
11938     // - Otherwise pointer comparisons are unspecified.
11939     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
11940       bool WasArrayIndex;
11941       unsigned Mismatch = FindDesignatorMismatch(
11942           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
11943       // At the point where the designators diverge, the comparison has a
11944       // specified value if:
11945       //  - we are comparing array indices
11946       //  - we are comparing fields of a union, or fields with the same access
11947       // Otherwise, the result is unspecified and thus the comparison is not a
11948       // constant expression.
11949       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
11950           Mismatch < RHSDesignator.Entries.size()) {
11951         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
11952         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
11953         if (!LF && !RF)
11954           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
11955         else if (!LF)
11956           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
11957               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
11958               << RF->getParent() << RF;
11959         else if (!RF)
11960           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
11961               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
11962               << LF->getParent() << LF;
11963         else if (!LF->getParent()->isUnion() &&
11964                  LF->getAccess() != RF->getAccess())
11965           Info.CCEDiag(E,
11966                        diag::note_constexpr_pointer_comparison_differing_access)
11967               << LF << LF->getAccess() << RF << RF->getAccess()
11968               << LF->getParent();
11969       }
11970     }
11971 
11972     // The comparison here must be unsigned, and performed with the same
11973     // width as the pointer.
11974     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
11975     uint64_t CompareLHS = LHSOffset.getQuantity();
11976     uint64_t CompareRHS = RHSOffset.getQuantity();
11977     assert(PtrSize <= 64 && "Unexpected pointer width");
11978     uint64_t Mask = ~0ULL >> (64 - PtrSize);
11979     CompareLHS &= Mask;
11980     CompareRHS &= Mask;
11981 
11982     // If there is a base and this is a relational operator, we can only
11983     // compare pointers within the object in question; otherwise, the result
11984     // depends on where the object is located in memory.
11985     if (!LHSValue.Base.isNull() && IsRelational) {
11986       QualType BaseTy = getType(LHSValue.Base);
11987       if (BaseTy->isIncompleteType())
11988         return Error(E);
11989       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
11990       uint64_t OffsetLimit = Size.getQuantity();
11991       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
11992         return Error(E);
11993     }
11994 
11995     if (CompareLHS < CompareRHS)
11996       return Success(CmpResult::Less, E);
11997     if (CompareLHS > CompareRHS)
11998       return Success(CmpResult::Greater, E);
11999     return Success(CmpResult::Equal, E);
12000   }
12001 
12002   if (LHSTy->isMemberPointerType()) {
12003     assert(IsEquality && "unexpected member pointer operation");
12004     assert(RHSTy->isMemberPointerType() && "invalid comparison");
12005 
12006     MemberPtr LHSValue, RHSValue;
12007 
12008     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
12009     if (!LHSOK && !Info.noteFailure())
12010       return false;
12011 
12012     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12013       return false;
12014 
12015     // C++11 [expr.eq]p2:
12016     //   If both operands are null, they compare equal. Otherwise if only one is
12017     //   null, they compare unequal.
12018     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
12019       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
12020       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12021     }
12022 
12023     //   Otherwise if either is a pointer to a virtual member function, the
12024     //   result is unspecified.
12025     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
12026       if (MD->isVirtual())
12027         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12028     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
12029       if (MD->isVirtual())
12030         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12031 
12032     //   Otherwise they compare equal if and only if they would refer to the
12033     //   same member of the same most derived object or the same subobject if
12034     //   they were dereferenced with a hypothetical object of the associated
12035     //   class type.
12036     bool Equal = LHSValue == RHSValue;
12037     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12038   }
12039 
12040   if (LHSTy->isNullPtrType()) {
12041     assert(E->isComparisonOp() && "unexpected nullptr operation");
12042     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12043     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12044     // are compared, the result is true of the operator is <=, >= or ==, and
12045     // false otherwise.
12046     return Success(CmpResult::Equal, E);
12047   }
12048 
12049   return DoAfter();
12050 }
12051 
12052 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
12053   if (!CheckLiteralType(Info, E))
12054     return false;
12055 
12056   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12057     ComparisonCategoryResult CCR;
12058     switch (CR) {
12059     case CmpResult::Unequal:
12060       llvm_unreachable("should never produce Unequal for three-way comparison");
12061     case CmpResult::Less:
12062       CCR = ComparisonCategoryResult::Less;
12063       break;
12064     case CmpResult::Equal:
12065       CCR = ComparisonCategoryResult::Equal;
12066       break;
12067     case CmpResult::Greater:
12068       CCR = ComparisonCategoryResult::Greater;
12069       break;
12070     case CmpResult::Unordered:
12071       CCR = ComparisonCategoryResult::Unordered;
12072       break;
12073     }
12074     // Evaluation succeeded. Lookup the information for the comparison category
12075     // type and fetch the VarDecl for the result.
12076     const ComparisonCategoryInfo &CmpInfo =
12077         Info.Ctx.CompCategories.getInfoForType(E->getType());
12078     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
12079     // Check and evaluate the result as a constant expression.
12080     LValue LV;
12081     LV.set(VD);
12082     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12083       return false;
12084     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
12085   };
12086   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12087     return ExprEvaluatorBaseTy::VisitBinCmp(E);
12088   });
12089 }
12090 
12091 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12092   // We don't call noteFailure immediately because the assignment happens after
12093   // we evaluate LHS and RHS.
12094   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
12095     return Error(E);
12096 
12097   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
12098   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
12099     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
12100 
12101   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
12102           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
12103          "DataRecursiveIntBinOpEvaluator should have handled integral types");
12104 
12105   if (E->isComparisonOp()) {
12106     // Evaluate builtin binary comparisons by evaluating them as three-way
12107     // comparisons and then translating the result.
12108     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12109       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
12110              "should only produce Unequal for equality comparisons");
12111       bool IsEqual   = CR == CmpResult::Equal,
12112            IsLess    = CR == CmpResult::Less,
12113            IsGreater = CR == CmpResult::Greater;
12114       auto Op = E->getOpcode();
12115       switch (Op) {
12116       default:
12117         llvm_unreachable("unsupported binary operator");
12118       case BO_EQ:
12119       case BO_NE:
12120         return Success(IsEqual == (Op == BO_EQ), E);
12121       case BO_LT:
12122         return Success(IsLess, E);
12123       case BO_GT:
12124         return Success(IsGreater, E);
12125       case BO_LE:
12126         return Success(IsEqual || IsLess, E);
12127       case BO_GE:
12128         return Success(IsEqual || IsGreater, E);
12129       }
12130     };
12131     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12132       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12133     });
12134   }
12135 
12136   QualType LHSTy = E->getLHS()->getType();
12137   QualType RHSTy = E->getRHS()->getType();
12138 
12139   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
12140       E->getOpcode() == BO_Sub) {
12141     LValue LHSValue, RHSValue;
12142 
12143     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12144     if (!LHSOK && !Info.noteFailure())
12145       return false;
12146 
12147     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12148       return false;
12149 
12150     // Reject differing bases from the normal codepath; we special-case
12151     // comparisons to null.
12152     if (!HasSameBase(LHSValue, RHSValue)) {
12153       // Handle &&A - &&B.
12154       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
12155         return Error(E);
12156       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
12157       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
12158       if (!LHSExpr || !RHSExpr)
12159         return Error(E);
12160       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12161       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12162       if (!LHSAddrExpr || !RHSAddrExpr)
12163         return Error(E);
12164       // Make sure both labels come from the same function.
12165       if (LHSAddrExpr->getLabel()->getDeclContext() !=
12166           RHSAddrExpr->getLabel()->getDeclContext())
12167         return Error(E);
12168       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
12169     }
12170     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12171     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12172 
12173     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12174     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12175 
12176     // C++11 [expr.add]p6:
12177     //   Unless both pointers point to elements of the same array object, or
12178     //   one past the last element of the array object, the behavior is
12179     //   undefined.
12180     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
12181         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
12182                                 RHSDesignator))
12183       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
12184 
12185     QualType Type = E->getLHS()->getType();
12186     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
12187 
12188     CharUnits ElementSize;
12189     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
12190       return false;
12191 
12192     // As an extension, a type may have zero size (empty struct or union in
12193     // C, array of zero length). Pointer subtraction in such cases has
12194     // undefined behavior, so is not constant.
12195     if (ElementSize.isZero()) {
12196       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
12197           << ElementType;
12198       return false;
12199     }
12200 
12201     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
12202     // and produce incorrect results when it overflows. Such behavior
12203     // appears to be non-conforming, but is common, so perhaps we should
12204     // assume the standard intended for such cases to be undefined behavior
12205     // and check for them.
12206 
12207     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
12208     // overflow in the final conversion to ptrdiff_t.
12209     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
12210     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
12211     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
12212                     false);
12213     APSInt TrueResult = (LHS - RHS) / ElemSize;
12214     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
12215 
12216     if (Result.extend(65) != TrueResult &&
12217         !HandleOverflow(Info, E, TrueResult, E->getType()))
12218       return false;
12219     return Success(Result, E);
12220   }
12221 
12222   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12223 }
12224 
12225 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
12226 /// a result as the expression's type.
12227 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
12228                                     const UnaryExprOrTypeTraitExpr *E) {
12229   switch(E->getKind()) {
12230   case UETT_PreferredAlignOf:
12231   case UETT_AlignOf: {
12232     if (E->isArgumentType())
12233       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
12234                      E);
12235     else
12236       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
12237                      E);
12238   }
12239 
12240   case UETT_VecStep: {
12241     QualType Ty = E->getTypeOfArgument();
12242 
12243     if (Ty->isVectorType()) {
12244       unsigned n = Ty->castAs<VectorType>()->getNumElements();
12245 
12246       // The vec_step built-in functions that take a 3-component
12247       // vector return 4. (OpenCL 1.1 spec 6.11.12)
12248       if (n == 3)
12249         n = 4;
12250 
12251       return Success(n, E);
12252     } else
12253       return Success(1, E);
12254   }
12255 
12256   case UETT_SizeOf: {
12257     QualType SrcTy = E->getTypeOfArgument();
12258     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
12259     //   the result is the size of the referenced type."
12260     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
12261       SrcTy = Ref->getPointeeType();
12262 
12263     CharUnits Sizeof;
12264     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
12265       return false;
12266     return Success(Sizeof, E);
12267   }
12268   case UETT_OpenMPRequiredSimdAlign:
12269     assert(E->isArgumentType());
12270     return Success(
12271         Info.Ctx.toCharUnitsFromBits(
12272                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
12273             .getQuantity(),
12274         E);
12275   }
12276 
12277   llvm_unreachable("unknown expr/type trait");
12278 }
12279 
12280 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
12281   CharUnits Result;
12282   unsigned n = OOE->getNumComponents();
12283   if (n == 0)
12284     return Error(OOE);
12285   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
12286   for (unsigned i = 0; i != n; ++i) {
12287     OffsetOfNode ON = OOE->getComponent(i);
12288     switch (ON.getKind()) {
12289     case OffsetOfNode::Array: {
12290       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
12291       APSInt IdxResult;
12292       if (!EvaluateInteger(Idx, IdxResult, Info))
12293         return false;
12294       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
12295       if (!AT)
12296         return Error(OOE);
12297       CurrentType = AT->getElementType();
12298       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
12299       Result += IdxResult.getSExtValue() * ElementSize;
12300       break;
12301     }
12302 
12303     case OffsetOfNode::Field: {
12304       FieldDecl *MemberDecl = ON.getField();
12305       const RecordType *RT = CurrentType->getAs<RecordType>();
12306       if (!RT)
12307         return Error(OOE);
12308       RecordDecl *RD = RT->getDecl();
12309       if (RD->isInvalidDecl()) return false;
12310       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
12311       unsigned i = MemberDecl->getFieldIndex();
12312       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
12313       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
12314       CurrentType = MemberDecl->getType().getNonReferenceType();
12315       break;
12316     }
12317 
12318     case OffsetOfNode::Identifier:
12319       llvm_unreachable("dependent __builtin_offsetof");
12320 
12321     case OffsetOfNode::Base: {
12322       CXXBaseSpecifier *BaseSpec = ON.getBase();
12323       if (BaseSpec->isVirtual())
12324         return Error(OOE);
12325 
12326       // Find the layout of the class whose base we are looking into.
12327       const RecordType *RT = CurrentType->getAs<RecordType>();
12328       if (!RT)
12329         return Error(OOE);
12330       RecordDecl *RD = RT->getDecl();
12331       if (RD->isInvalidDecl()) return false;
12332       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
12333 
12334       // Find the base class itself.
12335       CurrentType = BaseSpec->getType();
12336       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
12337       if (!BaseRT)
12338         return Error(OOE);
12339 
12340       // Add the offset to the base.
12341       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
12342       break;
12343     }
12344     }
12345   }
12346   return Success(Result, OOE);
12347 }
12348 
12349 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12350   switch (E->getOpcode()) {
12351   default:
12352     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
12353     // See C99 6.6p3.
12354     return Error(E);
12355   case UO_Extension:
12356     // FIXME: Should extension allow i-c-e extension expressions in its scope?
12357     // If so, we could clear the diagnostic ID.
12358     return Visit(E->getSubExpr());
12359   case UO_Plus:
12360     // The result is just the value.
12361     return Visit(E->getSubExpr());
12362   case UO_Minus: {
12363     if (!Visit(E->getSubExpr()))
12364       return false;
12365     if (!Result.isInt()) return Error(E);
12366     const APSInt &Value = Result.getInt();
12367     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
12368         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
12369                         E->getType()))
12370       return false;
12371     return Success(-Value, E);
12372   }
12373   case UO_Not: {
12374     if (!Visit(E->getSubExpr()))
12375       return false;
12376     if (!Result.isInt()) return Error(E);
12377     return Success(~Result.getInt(), E);
12378   }
12379   case UO_LNot: {
12380     bool bres;
12381     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
12382       return false;
12383     return Success(!bres, E);
12384   }
12385   }
12386 }
12387 
12388 /// HandleCast - This is used to evaluate implicit or explicit casts where the
12389 /// result type is integer.
12390 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
12391   const Expr *SubExpr = E->getSubExpr();
12392   QualType DestType = E->getType();
12393   QualType SrcType = SubExpr->getType();
12394 
12395   switch (E->getCastKind()) {
12396   case CK_BaseToDerived:
12397   case CK_DerivedToBase:
12398   case CK_UncheckedDerivedToBase:
12399   case CK_Dynamic:
12400   case CK_ToUnion:
12401   case CK_ArrayToPointerDecay:
12402   case CK_FunctionToPointerDecay:
12403   case CK_NullToPointer:
12404   case CK_NullToMemberPointer:
12405   case CK_BaseToDerivedMemberPointer:
12406   case CK_DerivedToBaseMemberPointer:
12407   case CK_ReinterpretMemberPointer:
12408   case CK_ConstructorConversion:
12409   case CK_IntegralToPointer:
12410   case CK_ToVoid:
12411   case CK_VectorSplat:
12412   case CK_IntegralToFloating:
12413   case CK_FloatingCast:
12414   case CK_CPointerToObjCPointerCast:
12415   case CK_BlockPointerToObjCPointerCast:
12416   case CK_AnyPointerToBlockPointerCast:
12417   case CK_ObjCObjectLValueCast:
12418   case CK_FloatingRealToComplex:
12419   case CK_FloatingComplexToReal:
12420   case CK_FloatingComplexCast:
12421   case CK_FloatingComplexToIntegralComplex:
12422   case CK_IntegralRealToComplex:
12423   case CK_IntegralComplexCast:
12424   case CK_IntegralComplexToFloatingComplex:
12425   case CK_BuiltinFnToFnPtr:
12426   case CK_ZeroToOCLOpaqueType:
12427   case CK_NonAtomicToAtomic:
12428   case CK_AddressSpaceConversion:
12429   case CK_IntToOCLSampler:
12430   case CK_FixedPointCast:
12431   case CK_IntegralToFixedPoint:
12432     llvm_unreachable("invalid cast kind for integral value");
12433 
12434   case CK_BitCast:
12435   case CK_Dependent:
12436   case CK_LValueBitCast:
12437   case CK_ARCProduceObject:
12438   case CK_ARCConsumeObject:
12439   case CK_ARCReclaimReturnedObject:
12440   case CK_ARCExtendBlockObject:
12441   case CK_CopyAndAutoreleaseBlockObject:
12442     return Error(E);
12443 
12444   case CK_UserDefinedConversion:
12445   case CK_LValueToRValue:
12446   case CK_AtomicToNonAtomic:
12447   case CK_NoOp:
12448   case CK_LValueToRValueBitCast:
12449     return ExprEvaluatorBaseTy::VisitCastExpr(E);
12450 
12451   case CK_MemberPointerToBoolean:
12452   case CK_PointerToBoolean:
12453   case CK_IntegralToBoolean:
12454   case CK_FloatingToBoolean:
12455   case CK_BooleanToSignedIntegral:
12456   case CK_FloatingComplexToBoolean:
12457   case CK_IntegralComplexToBoolean: {
12458     bool BoolResult;
12459     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
12460       return false;
12461     uint64_t IntResult = BoolResult;
12462     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
12463       IntResult = (uint64_t)-1;
12464     return Success(IntResult, E);
12465   }
12466 
12467   case CK_FixedPointToIntegral: {
12468     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
12469     if (!EvaluateFixedPoint(SubExpr, Src, Info))
12470       return false;
12471     bool Overflowed;
12472     llvm::APSInt Result = Src.convertToInt(
12473         Info.Ctx.getIntWidth(DestType),
12474         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
12475     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
12476       return false;
12477     return Success(Result, E);
12478   }
12479 
12480   case CK_FixedPointToBoolean: {
12481     // Unsigned padding does not affect this.
12482     APValue Val;
12483     if (!Evaluate(Val, Info, SubExpr))
12484       return false;
12485     return Success(Val.getFixedPoint().getBoolValue(), E);
12486   }
12487 
12488   case CK_IntegralCast: {
12489     if (!Visit(SubExpr))
12490       return false;
12491 
12492     if (!Result.isInt()) {
12493       // Allow casts of address-of-label differences if they are no-ops
12494       // or narrowing.  (The narrowing case isn't actually guaranteed to
12495       // be constant-evaluatable except in some narrow cases which are hard
12496       // to detect here.  We let it through on the assumption the user knows
12497       // what they are doing.)
12498       if (Result.isAddrLabelDiff())
12499         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
12500       // Only allow casts of lvalues if they are lossless.
12501       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
12502     }
12503 
12504     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
12505                                       Result.getInt()), E);
12506   }
12507 
12508   case CK_PointerToIntegral: {
12509     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
12510 
12511     LValue LV;
12512     if (!EvaluatePointer(SubExpr, LV, Info))
12513       return false;
12514 
12515     if (LV.getLValueBase()) {
12516       // Only allow based lvalue casts if they are lossless.
12517       // FIXME: Allow a larger integer size than the pointer size, and allow
12518       // narrowing back down to pointer width in subsequent integral casts.
12519       // FIXME: Check integer type's active bits, not its type size.
12520       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
12521         return Error(E);
12522 
12523       LV.Designator.setInvalid();
12524       LV.moveInto(Result);
12525       return true;
12526     }
12527 
12528     APSInt AsInt;
12529     APValue V;
12530     LV.moveInto(V);
12531     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
12532       llvm_unreachable("Can't cast this!");
12533 
12534     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
12535   }
12536 
12537   case CK_IntegralComplexToReal: {
12538     ComplexValue C;
12539     if (!EvaluateComplex(SubExpr, C, Info))
12540       return false;
12541     return Success(C.getComplexIntReal(), E);
12542   }
12543 
12544   case CK_FloatingToIntegral: {
12545     APFloat F(0.0);
12546     if (!EvaluateFloat(SubExpr, F, Info))
12547       return false;
12548 
12549     APSInt Value;
12550     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
12551       return false;
12552     return Success(Value, E);
12553   }
12554   }
12555 
12556   llvm_unreachable("unknown cast resulting in integral value");
12557 }
12558 
12559 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
12560   if (E->getSubExpr()->getType()->isAnyComplexType()) {
12561     ComplexValue LV;
12562     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
12563       return false;
12564     if (!LV.isComplexInt())
12565       return Error(E);
12566     return Success(LV.getComplexIntReal(), E);
12567   }
12568 
12569   return Visit(E->getSubExpr());
12570 }
12571 
12572 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
12573   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
12574     ComplexValue LV;
12575     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
12576       return false;
12577     if (!LV.isComplexInt())
12578       return Error(E);
12579     return Success(LV.getComplexIntImag(), E);
12580   }
12581 
12582   VisitIgnoredValue(E->getSubExpr());
12583   return Success(0, E);
12584 }
12585 
12586 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
12587   return Success(E->getPackLength(), E);
12588 }
12589 
12590 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
12591   return Success(E->getValue(), E);
12592 }
12593 
12594 bool IntExprEvaluator::VisitConceptSpecializationExpr(
12595        const ConceptSpecializationExpr *E) {
12596   return Success(E->isSatisfied(), E);
12597 }
12598 
12599 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
12600   return Success(E->isSatisfied(), E);
12601 }
12602 
12603 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12604   switch (E->getOpcode()) {
12605     default:
12606       // Invalid unary operators
12607       return Error(E);
12608     case UO_Plus:
12609       // The result is just the value.
12610       return Visit(E->getSubExpr());
12611     case UO_Minus: {
12612       if (!Visit(E->getSubExpr())) return false;
12613       if (!Result.isFixedPoint())
12614         return Error(E);
12615       bool Overflowed;
12616       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
12617       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
12618         return false;
12619       return Success(Negated, E);
12620     }
12621     case UO_LNot: {
12622       bool bres;
12623       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
12624         return false;
12625       return Success(!bres, E);
12626     }
12627   }
12628 }
12629 
12630 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
12631   const Expr *SubExpr = E->getSubExpr();
12632   QualType DestType = E->getType();
12633   assert(DestType->isFixedPointType() &&
12634          "Expected destination type to be a fixed point type");
12635   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
12636 
12637   switch (E->getCastKind()) {
12638   case CK_FixedPointCast: {
12639     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
12640     if (!EvaluateFixedPoint(SubExpr, Src, Info))
12641       return false;
12642     bool Overflowed;
12643     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
12644     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
12645       return false;
12646     return Success(Result, E);
12647   }
12648   case CK_IntegralToFixedPoint: {
12649     APSInt Src;
12650     if (!EvaluateInteger(SubExpr, Src, Info))
12651       return false;
12652 
12653     bool Overflowed;
12654     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
12655         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
12656 
12657     if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
12658       return false;
12659 
12660     return Success(IntResult, E);
12661   }
12662   case CK_NoOp:
12663   case CK_LValueToRValue:
12664     return ExprEvaluatorBaseTy::VisitCastExpr(E);
12665   default:
12666     return Error(E);
12667   }
12668 }
12669 
12670 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12671   const Expr *LHS = E->getLHS();
12672   const Expr *RHS = E->getRHS();
12673   FixedPointSemantics ResultFXSema =
12674       Info.Ctx.getFixedPointSemantics(E->getType());
12675 
12676   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
12677   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
12678     return false;
12679   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
12680   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
12681     return false;
12682 
12683   switch (E->getOpcode()) {
12684   case BO_Add: {
12685     bool AddOverflow, ConversionOverflow;
12686     APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
12687                               .convert(ResultFXSema, &ConversionOverflow);
12688     if ((AddOverflow || ConversionOverflow) &&
12689         !HandleOverflow(Info, E, Result, E->getType()))
12690       return false;
12691     return Success(Result, E);
12692   }
12693   default:
12694     return false;
12695   }
12696   llvm_unreachable("Should've exited before this");
12697 }
12698 
12699 //===----------------------------------------------------------------------===//
12700 // Float Evaluation
12701 //===----------------------------------------------------------------------===//
12702 
12703 namespace {
12704 class FloatExprEvaluator
12705   : public ExprEvaluatorBase<FloatExprEvaluator> {
12706   APFloat &Result;
12707 public:
12708   FloatExprEvaluator(EvalInfo &info, APFloat &result)
12709     : ExprEvaluatorBaseTy(info), Result(result) {}
12710 
12711   bool Success(const APValue &V, const Expr *e) {
12712     Result = V.getFloat();
12713     return true;
12714   }
12715 
12716   bool ZeroInitialization(const Expr *E) {
12717     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
12718     return true;
12719   }
12720 
12721   bool VisitCallExpr(const CallExpr *E);
12722 
12723   bool VisitUnaryOperator(const UnaryOperator *E);
12724   bool VisitBinaryOperator(const BinaryOperator *E);
12725   bool VisitFloatingLiteral(const FloatingLiteral *E);
12726   bool VisitCastExpr(const CastExpr *E);
12727 
12728   bool VisitUnaryReal(const UnaryOperator *E);
12729   bool VisitUnaryImag(const UnaryOperator *E);
12730 
12731   // FIXME: Missing: array subscript of vector, member of vector
12732 };
12733 } // end anonymous namespace
12734 
12735 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
12736   assert(E->isRValue() && E->getType()->isRealFloatingType());
12737   return FloatExprEvaluator(Info, Result).Visit(E);
12738 }
12739 
12740 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
12741                                   QualType ResultTy,
12742                                   const Expr *Arg,
12743                                   bool SNaN,
12744                                   llvm::APFloat &Result) {
12745   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
12746   if (!S) return false;
12747 
12748   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
12749 
12750   llvm::APInt fill;
12751 
12752   // Treat empty strings as if they were zero.
12753   if (S->getString().empty())
12754     fill = llvm::APInt(32, 0);
12755   else if (S->getString().getAsInteger(0, fill))
12756     return false;
12757 
12758   if (Context.getTargetInfo().isNan2008()) {
12759     if (SNaN)
12760       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
12761     else
12762       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
12763   } else {
12764     // Prior to IEEE 754-2008, architectures were allowed to choose whether
12765     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
12766     // a different encoding to what became a standard in 2008, and for pre-
12767     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
12768     // sNaN. This is now known as "legacy NaN" encoding.
12769     if (SNaN)
12770       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
12771     else
12772       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
12773   }
12774 
12775   return true;
12776 }
12777 
12778 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
12779   switch (E->getBuiltinCallee()) {
12780   default:
12781     return ExprEvaluatorBaseTy::VisitCallExpr(E);
12782 
12783   case Builtin::BI__builtin_huge_val:
12784   case Builtin::BI__builtin_huge_valf:
12785   case Builtin::BI__builtin_huge_vall:
12786   case Builtin::BI__builtin_huge_valf128:
12787   case Builtin::BI__builtin_inf:
12788   case Builtin::BI__builtin_inff:
12789   case Builtin::BI__builtin_infl:
12790   case Builtin::BI__builtin_inff128: {
12791     const llvm::fltSemantics &Sem =
12792       Info.Ctx.getFloatTypeSemantics(E->getType());
12793     Result = llvm::APFloat::getInf(Sem);
12794     return true;
12795   }
12796 
12797   case Builtin::BI__builtin_nans:
12798   case Builtin::BI__builtin_nansf:
12799   case Builtin::BI__builtin_nansl:
12800   case Builtin::BI__builtin_nansf128:
12801     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
12802                                true, Result))
12803       return Error(E);
12804     return true;
12805 
12806   case Builtin::BI__builtin_nan:
12807   case Builtin::BI__builtin_nanf:
12808   case Builtin::BI__builtin_nanl:
12809   case Builtin::BI__builtin_nanf128:
12810     // If this is __builtin_nan() turn this into a nan, otherwise we
12811     // can't constant fold it.
12812     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
12813                                false, Result))
12814       return Error(E);
12815     return true;
12816 
12817   case Builtin::BI__builtin_fabs:
12818   case Builtin::BI__builtin_fabsf:
12819   case Builtin::BI__builtin_fabsl:
12820   case Builtin::BI__builtin_fabsf128:
12821     if (!EvaluateFloat(E->getArg(0), Result, Info))
12822       return false;
12823 
12824     if (Result.isNegative())
12825       Result.changeSign();
12826     return true;
12827 
12828   // FIXME: Builtin::BI__builtin_powi
12829   // FIXME: Builtin::BI__builtin_powif
12830   // FIXME: Builtin::BI__builtin_powil
12831 
12832   case Builtin::BI__builtin_copysign:
12833   case Builtin::BI__builtin_copysignf:
12834   case Builtin::BI__builtin_copysignl:
12835   case Builtin::BI__builtin_copysignf128: {
12836     APFloat RHS(0.);
12837     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
12838         !EvaluateFloat(E->getArg(1), RHS, Info))
12839       return false;
12840     Result.copySign(RHS);
12841     return true;
12842   }
12843   }
12844 }
12845 
12846 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
12847   if (E->getSubExpr()->getType()->isAnyComplexType()) {
12848     ComplexValue CV;
12849     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
12850       return false;
12851     Result = CV.FloatReal;
12852     return true;
12853   }
12854 
12855   return Visit(E->getSubExpr());
12856 }
12857 
12858 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
12859   if (E->getSubExpr()->getType()->isAnyComplexType()) {
12860     ComplexValue CV;
12861     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
12862       return false;
12863     Result = CV.FloatImag;
12864     return true;
12865   }
12866 
12867   VisitIgnoredValue(E->getSubExpr());
12868   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
12869   Result = llvm::APFloat::getZero(Sem);
12870   return true;
12871 }
12872 
12873 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12874   switch (E->getOpcode()) {
12875   default: return Error(E);
12876   case UO_Plus:
12877     return EvaluateFloat(E->getSubExpr(), Result, Info);
12878   case UO_Minus:
12879     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
12880       return false;
12881     Result.changeSign();
12882     return true;
12883   }
12884 }
12885 
12886 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12887   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
12888     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12889 
12890   APFloat RHS(0.0);
12891   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
12892   if (!LHSOK && !Info.noteFailure())
12893     return false;
12894   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
12895          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
12896 }
12897 
12898 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
12899   Result = E->getValue();
12900   return true;
12901 }
12902 
12903 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
12904   const Expr* SubExpr = E->getSubExpr();
12905 
12906   switch (E->getCastKind()) {
12907   default:
12908     return ExprEvaluatorBaseTy::VisitCastExpr(E);
12909 
12910   case CK_IntegralToFloating: {
12911     APSInt IntResult;
12912     return EvaluateInteger(SubExpr, IntResult, Info) &&
12913            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
12914                                 E->getType(), Result);
12915   }
12916 
12917   case CK_FloatingCast: {
12918     if (!Visit(SubExpr))
12919       return false;
12920     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
12921                                   Result);
12922   }
12923 
12924   case CK_FloatingComplexToReal: {
12925     ComplexValue V;
12926     if (!EvaluateComplex(SubExpr, V, Info))
12927       return false;
12928     Result = V.getComplexFloatReal();
12929     return true;
12930   }
12931   }
12932 }
12933 
12934 //===----------------------------------------------------------------------===//
12935 // Complex Evaluation (for float and integer)
12936 //===----------------------------------------------------------------------===//
12937 
12938 namespace {
12939 class ComplexExprEvaluator
12940   : public ExprEvaluatorBase<ComplexExprEvaluator> {
12941   ComplexValue &Result;
12942 
12943 public:
12944   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
12945     : ExprEvaluatorBaseTy(info), Result(Result) {}
12946 
12947   bool Success(const APValue &V, const Expr *e) {
12948     Result.setFrom(V);
12949     return true;
12950   }
12951 
12952   bool ZeroInitialization(const Expr *E);
12953 
12954   //===--------------------------------------------------------------------===//
12955   //                            Visitor Methods
12956   //===--------------------------------------------------------------------===//
12957 
12958   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
12959   bool VisitCastExpr(const CastExpr *E);
12960   bool VisitBinaryOperator(const BinaryOperator *E);
12961   bool VisitUnaryOperator(const UnaryOperator *E);
12962   bool VisitInitListExpr(const InitListExpr *E);
12963 };
12964 } // end anonymous namespace
12965 
12966 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
12967                             EvalInfo &Info) {
12968   assert(E->isRValue() && E->getType()->isAnyComplexType());
12969   return ComplexExprEvaluator(Info, Result).Visit(E);
12970 }
12971 
12972 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
12973   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
12974   if (ElemTy->isRealFloatingType()) {
12975     Result.makeComplexFloat();
12976     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
12977     Result.FloatReal = Zero;
12978     Result.FloatImag = Zero;
12979   } else {
12980     Result.makeComplexInt();
12981     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
12982     Result.IntReal = Zero;
12983     Result.IntImag = Zero;
12984   }
12985   return true;
12986 }
12987 
12988 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
12989   const Expr* SubExpr = E->getSubExpr();
12990 
12991   if (SubExpr->getType()->isRealFloatingType()) {
12992     Result.makeComplexFloat();
12993     APFloat &Imag = Result.FloatImag;
12994     if (!EvaluateFloat(SubExpr, Imag, Info))
12995       return false;
12996 
12997     Result.FloatReal = APFloat(Imag.getSemantics());
12998     return true;
12999   } else {
13000     assert(SubExpr->getType()->isIntegerType() &&
13001            "Unexpected imaginary literal.");
13002 
13003     Result.makeComplexInt();
13004     APSInt &Imag = Result.IntImag;
13005     if (!EvaluateInteger(SubExpr, Imag, Info))
13006       return false;
13007 
13008     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
13009     return true;
13010   }
13011 }
13012 
13013 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
13014 
13015   switch (E->getCastKind()) {
13016   case CK_BitCast:
13017   case CK_BaseToDerived:
13018   case CK_DerivedToBase:
13019   case CK_UncheckedDerivedToBase:
13020   case CK_Dynamic:
13021   case CK_ToUnion:
13022   case CK_ArrayToPointerDecay:
13023   case CK_FunctionToPointerDecay:
13024   case CK_NullToPointer:
13025   case CK_NullToMemberPointer:
13026   case CK_BaseToDerivedMemberPointer:
13027   case CK_DerivedToBaseMemberPointer:
13028   case CK_MemberPointerToBoolean:
13029   case CK_ReinterpretMemberPointer:
13030   case CK_ConstructorConversion:
13031   case CK_IntegralToPointer:
13032   case CK_PointerToIntegral:
13033   case CK_PointerToBoolean:
13034   case CK_ToVoid:
13035   case CK_VectorSplat:
13036   case CK_IntegralCast:
13037   case CK_BooleanToSignedIntegral:
13038   case CK_IntegralToBoolean:
13039   case CK_IntegralToFloating:
13040   case CK_FloatingToIntegral:
13041   case CK_FloatingToBoolean:
13042   case CK_FloatingCast:
13043   case CK_CPointerToObjCPointerCast:
13044   case CK_BlockPointerToObjCPointerCast:
13045   case CK_AnyPointerToBlockPointerCast:
13046   case CK_ObjCObjectLValueCast:
13047   case CK_FloatingComplexToReal:
13048   case CK_FloatingComplexToBoolean:
13049   case CK_IntegralComplexToReal:
13050   case CK_IntegralComplexToBoolean:
13051   case CK_ARCProduceObject:
13052   case CK_ARCConsumeObject:
13053   case CK_ARCReclaimReturnedObject:
13054   case CK_ARCExtendBlockObject:
13055   case CK_CopyAndAutoreleaseBlockObject:
13056   case CK_BuiltinFnToFnPtr:
13057   case CK_ZeroToOCLOpaqueType:
13058   case CK_NonAtomicToAtomic:
13059   case CK_AddressSpaceConversion:
13060   case CK_IntToOCLSampler:
13061   case CK_FixedPointCast:
13062   case CK_FixedPointToBoolean:
13063   case CK_FixedPointToIntegral:
13064   case CK_IntegralToFixedPoint:
13065     llvm_unreachable("invalid cast kind for complex value");
13066 
13067   case CK_LValueToRValue:
13068   case CK_AtomicToNonAtomic:
13069   case CK_NoOp:
13070   case CK_LValueToRValueBitCast:
13071     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13072 
13073   case CK_Dependent:
13074   case CK_LValueBitCast:
13075   case CK_UserDefinedConversion:
13076     return Error(E);
13077 
13078   case CK_FloatingRealToComplex: {
13079     APFloat &Real = Result.FloatReal;
13080     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
13081       return false;
13082 
13083     Result.makeComplexFloat();
13084     Result.FloatImag = APFloat(Real.getSemantics());
13085     return true;
13086   }
13087 
13088   case CK_FloatingComplexCast: {
13089     if (!Visit(E->getSubExpr()))
13090       return false;
13091 
13092     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13093     QualType From
13094       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13095 
13096     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
13097            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
13098   }
13099 
13100   case CK_FloatingComplexToIntegralComplex: {
13101     if (!Visit(E->getSubExpr()))
13102       return false;
13103 
13104     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13105     QualType From
13106       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13107     Result.makeComplexInt();
13108     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
13109                                 To, Result.IntReal) &&
13110            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
13111                                 To, Result.IntImag);
13112   }
13113 
13114   case CK_IntegralRealToComplex: {
13115     APSInt &Real = Result.IntReal;
13116     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
13117       return false;
13118 
13119     Result.makeComplexInt();
13120     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
13121     return true;
13122   }
13123 
13124   case CK_IntegralComplexCast: {
13125     if (!Visit(E->getSubExpr()))
13126       return false;
13127 
13128     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13129     QualType From
13130       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13131 
13132     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
13133     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
13134     return true;
13135   }
13136 
13137   case CK_IntegralComplexToFloatingComplex: {
13138     if (!Visit(E->getSubExpr()))
13139       return false;
13140 
13141     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13142     QualType From
13143       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13144     Result.makeComplexFloat();
13145     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
13146                                 To, Result.FloatReal) &&
13147            HandleIntToFloatCast(Info, E, From, Result.IntImag,
13148                                 To, Result.FloatImag);
13149   }
13150   }
13151 
13152   llvm_unreachable("unknown cast resulting in complex value");
13153 }
13154 
13155 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13156   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13157     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13158 
13159   // Track whether the LHS or RHS is real at the type system level. When this is
13160   // the case we can simplify our evaluation strategy.
13161   bool LHSReal = false, RHSReal = false;
13162 
13163   bool LHSOK;
13164   if (E->getLHS()->getType()->isRealFloatingType()) {
13165     LHSReal = true;
13166     APFloat &Real = Result.FloatReal;
13167     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
13168     if (LHSOK) {
13169       Result.makeComplexFloat();
13170       Result.FloatImag = APFloat(Real.getSemantics());
13171     }
13172   } else {
13173     LHSOK = Visit(E->getLHS());
13174   }
13175   if (!LHSOK && !Info.noteFailure())
13176     return false;
13177 
13178   ComplexValue RHS;
13179   if (E->getRHS()->getType()->isRealFloatingType()) {
13180     RHSReal = true;
13181     APFloat &Real = RHS.FloatReal;
13182     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
13183       return false;
13184     RHS.makeComplexFloat();
13185     RHS.FloatImag = APFloat(Real.getSemantics());
13186   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
13187     return false;
13188 
13189   assert(!(LHSReal && RHSReal) &&
13190          "Cannot have both operands of a complex operation be real.");
13191   switch (E->getOpcode()) {
13192   default: return Error(E);
13193   case BO_Add:
13194     if (Result.isComplexFloat()) {
13195       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
13196                                        APFloat::rmNearestTiesToEven);
13197       if (LHSReal)
13198         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
13199       else if (!RHSReal)
13200         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
13201                                          APFloat::rmNearestTiesToEven);
13202     } else {
13203       Result.getComplexIntReal() += RHS.getComplexIntReal();
13204       Result.getComplexIntImag() += RHS.getComplexIntImag();
13205     }
13206     break;
13207   case BO_Sub:
13208     if (Result.isComplexFloat()) {
13209       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
13210                                             APFloat::rmNearestTiesToEven);
13211       if (LHSReal) {
13212         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
13213         Result.getComplexFloatImag().changeSign();
13214       } else if (!RHSReal) {
13215         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
13216                                               APFloat::rmNearestTiesToEven);
13217       }
13218     } else {
13219       Result.getComplexIntReal() -= RHS.getComplexIntReal();
13220       Result.getComplexIntImag() -= RHS.getComplexIntImag();
13221     }
13222     break;
13223   case BO_Mul:
13224     if (Result.isComplexFloat()) {
13225       // This is an implementation of complex multiplication according to the
13226       // constraints laid out in C11 Annex G. The implementation uses the
13227       // following naming scheme:
13228       //   (a + ib) * (c + id)
13229       ComplexValue LHS = Result;
13230       APFloat &A = LHS.getComplexFloatReal();
13231       APFloat &B = LHS.getComplexFloatImag();
13232       APFloat &C = RHS.getComplexFloatReal();
13233       APFloat &D = RHS.getComplexFloatImag();
13234       APFloat &ResR = Result.getComplexFloatReal();
13235       APFloat &ResI = Result.getComplexFloatImag();
13236       if (LHSReal) {
13237         assert(!RHSReal && "Cannot have two real operands for a complex op!");
13238         ResR = A * C;
13239         ResI = A * D;
13240       } else if (RHSReal) {
13241         ResR = C * A;
13242         ResI = C * B;
13243       } else {
13244         // In the fully general case, we need to handle NaNs and infinities
13245         // robustly.
13246         APFloat AC = A * C;
13247         APFloat BD = B * D;
13248         APFloat AD = A * D;
13249         APFloat BC = B * C;
13250         ResR = AC - BD;
13251         ResI = AD + BC;
13252         if (ResR.isNaN() && ResI.isNaN()) {
13253           bool Recalc = false;
13254           if (A.isInfinity() || B.isInfinity()) {
13255             A = APFloat::copySign(
13256                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
13257             B = APFloat::copySign(
13258                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
13259             if (C.isNaN())
13260               C = APFloat::copySign(APFloat(C.getSemantics()), C);
13261             if (D.isNaN())
13262               D = APFloat::copySign(APFloat(D.getSemantics()), D);
13263             Recalc = true;
13264           }
13265           if (C.isInfinity() || D.isInfinity()) {
13266             C = APFloat::copySign(
13267                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
13268             D = APFloat::copySign(
13269                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
13270             if (A.isNaN())
13271               A = APFloat::copySign(APFloat(A.getSemantics()), A);
13272             if (B.isNaN())
13273               B = APFloat::copySign(APFloat(B.getSemantics()), B);
13274             Recalc = true;
13275           }
13276           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
13277                           AD.isInfinity() || BC.isInfinity())) {
13278             if (A.isNaN())
13279               A = APFloat::copySign(APFloat(A.getSemantics()), A);
13280             if (B.isNaN())
13281               B = APFloat::copySign(APFloat(B.getSemantics()), B);
13282             if (C.isNaN())
13283               C = APFloat::copySign(APFloat(C.getSemantics()), C);
13284             if (D.isNaN())
13285               D = APFloat::copySign(APFloat(D.getSemantics()), D);
13286             Recalc = true;
13287           }
13288           if (Recalc) {
13289             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
13290             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
13291           }
13292         }
13293       }
13294     } else {
13295       ComplexValue LHS = Result;
13296       Result.getComplexIntReal() =
13297         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
13298          LHS.getComplexIntImag() * RHS.getComplexIntImag());
13299       Result.getComplexIntImag() =
13300         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
13301          LHS.getComplexIntImag() * RHS.getComplexIntReal());
13302     }
13303     break;
13304   case BO_Div:
13305     if (Result.isComplexFloat()) {
13306       // This is an implementation of complex division according to the
13307       // constraints laid out in C11 Annex G. The implementation uses the
13308       // following naming scheme:
13309       //   (a + ib) / (c + id)
13310       ComplexValue LHS = Result;
13311       APFloat &A = LHS.getComplexFloatReal();
13312       APFloat &B = LHS.getComplexFloatImag();
13313       APFloat &C = RHS.getComplexFloatReal();
13314       APFloat &D = RHS.getComplexFloatImag();
13315       APFloat &ResR = Result.getComplexFloatReal();
13316       APFloat &ResI = Result.getComplexFloatImag();
13317       if (RHSReal) {
13318         ResR = A / C;
13319         ResI = B / C;
13320       } else {
13321         if (LHSReal) {
13322           // No real optimizations we can do here, stub out with zero.
13323           B = APFloat::getZero(A.getSemantics());
13324         }
13325         int DenomLogB = 0;
13326         APFloat MaxCD = maxnum(abs(C), abs(D));
13327         if (MaxCD.isFinite()) {
13328           DenomLogB = ilogb(MaxCD);
13329           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
13330           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
13331         }
13332         APFloat Denom = C * C + D * D;
13333         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
13334                       APFloat::rmNearestTiesToEven);
13335         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
13336                       APFloat::rmNearestTiesToEven);
13337         if (ResR.isNaN() && ResI.isNaN()) {
13338           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
13339             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
13340             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
13341           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
13342                      D.isFinite()) {
13343             A = APFloat::copySign(
13344                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
13345             B = APFloat::copySign(
13346                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
13347             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
13348             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
13349           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
13350             C = APFloat::copySign(
13351                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
13352             D = APFloat::copySign(
13353                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
13354             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
13355             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
13356           }
13357         }
13358       }
13359     } else {
13360       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
13361         return Error(E, diag::note_expr_divide_by_zero);
13362 
13363       ComplexValue LHS = Result;
13364       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
13365         RHS.getComplexIntImag() * RHS.getComplexIntImag();
13366       Result.getComplexIntReal() =
13367         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
13368          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
13369       Result.getComplexIntImag() =
13370         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
13371          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
13372     }
13373     break;
13374   }
13375 
13376   return true;
13377 }
13378 
13379 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13380   // Get the operand value into 'Result'.
13381   if (!Visit(E->getSubExpr()))
13382     return false;
13383 
13384   switch (E->getOpcode()) {
13385   default:
13386     return Error(E);
13387   case UO_Extension:
13388     return true;
13389   case UO_Plus:
13390     // The result is always just the subexpr.
13391     return true;
13392   case UO_Minus:
13393     if (Result.isComplexFloat()) {
13394       Result.getComplexFloatReal().changeSign();
13395       Result.getComplexFloatImag().changeSign();
13396     }
13397     else {
13398       Result.getComplexIntReal() = -Result.getComplexIntReal();
13399       Result.getComplexIntImag() = -Result.getComplexIntImag();
13400     }
13401     return true;
13402   case UO_Not:
13403     if (Result.isComplexFloat())
13404       Result.getComplexFloatImag().changeSign();
13405     else
13406       Result.getComplexIntImag() = -Result.getComplexIntImag();
13407     return true;
13408   }
13409 }
13410 
13411 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
13412   if (E->getNumInits() == 2) {
13413     if (E->getType()->isComplexType()) {
13414       Result.makeComplexFloat();
13415       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
13416         return false;
13417       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
13418         return false;
13419     } else {
13420       Result.makeComplexInt();
13421       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
13422         return false;
13423       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
13424         return false;
13425     }
13426     return true;
13427   }
13428   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
13429 }
13430 
13431 //===----------------------------------------------------------------------===//
13432 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
13433 // implicit conversion.
13434 //===----------------------------------------------------------------------===//
13435 
13436 namespace {
13437 class AtomicExprEvaluator :
13438     public ExprEvaluatorBase<AtomicExprEvaluator> {
13439   const LValue *This;
13440   APValue &Result;
13441 public:
13442   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
13443       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
13444 
13445   bool Success(const APValue &V, const Expr *E) {
13446     Result = V;
13447     return true;
13448   }
13449 
13450   bool ZeroInitialization(const Expr *E) {
13451     ImplicitValueInitExpr VIE(
13452         E->getType()->castAs<AtomicType>()->getValueType());
13453     // For atomic-qualified class (and array) types in C++, initialize the
13454     // _Atomic-wrapped subobject directly, in-place.
13455     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
13456                 : Evaluate(Result, Info, &VIE);
13457   }
13458 
13459   bool VisitCastExpr(const CastExpr *E) {
13460     switch (E->getCastKind()) {
13461     default:
13462       return ExprEvaluatorBaseTy::VisitCastExpr(E);
13463     case CK_NonAtomicToAtomic:
13464       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
13465                   : Evaluate(Result, Info, E->getSubExpr());
13466     }
13467   }
13468 };
13469 } // end anonymous namespace
13470 
13471 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
13472                            EvalInfo &Info) {
13473   assert(E->isRValue() && E->getType()->isAtomicType());
13474   return AtomicExprEvaluator(Info, This, Result).Visit(E);
13475 }
13476 
13477 //===----------------------------------------------------------------------===//
13478 // Void expression evaluation, primarily for a cast to void on the LHS of a
13479 // comma operator
13480 //===----------------------------------------------------------------------===//
13481 
13482 namespace {
13483 class VoidExprEvaluator
13484   : public ExprEvaluatorBase<VoidExprEvaluator> {
13485 public:
13486   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
13487 
13488   bool Success(const APValue &V, const Expr *e) { return true; }
13489 
13490   bool ZeroInitialization(const Expr *E) { return true; }
13491 
13492   bool VisitCastExpr(const CastExpr *E) {
13493     switch (E->getCastKind()) {
13494     default:
13495       return ExprEvaluatorBaseTy::VisitCastExpr(E);
13496     case CK_ToVoid:
13497       VisitIgnoredValue(E->getSubExpr());
13498       return true;
13499     }
13500   }
13501 
13502   bool VisitCallExpr(const CallExpr *E) {
13503     switch (E->getBuiltinCallee()) {
13504     case Builtin::BI__assume:
13505     case Builtin::BI__builtin_assume:
13506       // The argument is not evaluated!
13507       return true;
13508 
13509     case Builtin::BI__builtin_operator_delete:
13510       return HandleOperatorDeleteCall(Info, E);
13511 
13512     default:
13513       break;
13514     }
13515 
13516     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13517   }
13518 
13519   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
13520 };
13521 } // end anonymous namespace
13522 
13523 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
13524   // We cannot speculatively evaluate a delete expression.
13525   if (Info.SpeculativeEvaluationDepth)
13526     return false;
13527 
13528   FunctionDecl *OperatorDelete = E->getOperatorDelete();
13529   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
13530     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
13531         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
13532     return false;
13533   }
13534 
13535   const Expr *Arg = E->getArgument();
13536 
13537   LValue Pointer;
13538   if (!EvaluatePointer(Arg, Pointer, Info))
13539     return false;
13540   if (Pointer.Designator.Invalid)
13541     return false;
13542 
13543   // Deleting a null pointer has no effect.
13544   if (Pointer.isNullPointer()) {
13545     // This is the only case where we need to produce an extension warning:
13546     // the only other way we can succeed is if we find a dynamic allocation,
13547     // and we will have warned when we allocated it in that case.
13548     if (!Info.getLangOpts().CPlusPlus2a)
13549       Info.CCEDiag(E, diag::note_constexpr_new);
13550     return true;
13551   }
13552 
13553   Optional<DynAlloc *> Alloc = CheckDeleteKind(
13554       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
13555   if (!Alloc)
13556     return false;
13557   QualType AllocType = Pointer.Base.getDynamicAllocType();
13558 
13559   // For the non-array case, the designator must be empty if the static type
13560   // does not have a virtual destructor.
13561   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
13562       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
13563     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
13564         << Arg->getType()->getPointeeType() << AllocType;
13565     return false;
13566   }
13567 
13568   // For a class type with a virtual destructor, the selected operator delete
13569   // is the one looked up when building the destructor.
13570   if (!E->isArrayForm() && !E->isGlobalDelete()) {
13571     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
13572     if (VirtualDelete &&
13573         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
13574       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
13575           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
13576       return false;
13577     }
13578   }
13579 
13580   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
13581                          (*Alloc)->Value, AllocType))
13582     return false;
13583 
13584   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
13585     // The element was already erased. This means the destructor call also
13586     // deleted the object.
13587     // FIXME: This probably results in undefined behavior before we get this
13588     // far, and should be diagnosed elsewhere first.
13589     Info.FFDiag(E, diag::note_constexpr_double_delete);
13590     return false;
13591   }
13592 
13593   return true;
13594 }
13595 
13596 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
13597   assert(E->isRValue() && E->getType()->isVoidType());
13598   return VoidExprEvaluator(Info).Visit(E);
13599 }
13600 
13601 //===----------------------------------------------------------------------===//
13602 // Top level Expr::EvaluateAsRValue method.
13603 //===----------------------------------------------------------------------===//
13604 
13605 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
13606   // In C, function designators are not lvalues, but we evaluate them as if they
13607   // are.
13608   QualType T = E->getType();
13609   if (E->isGLValue() || T->isFunctionType()) {
13610     LValue LV;
13611     if (!EvaluateLValue(E, LV, Info))
13612       return false;
13613     LV.moveInto(Result);
13614   } else if (T->isVectorType()) {
13615     if (!EvaluateVector(E, Result, Info))
13616       return false;
13617   } else if (T->isIntegralOrEnumerationType()) {
13618     if (!IntExprEvaluator(Info, Result).Visit(E))
13619       return false;
13620   } else if (T->hasPointerRepresentation()) {
13621     LValue LV;
13622     if (!EvaluatePointer(E, LV, Info))
13623       return false;
13624     LV.moveInto(Result);
13625   } else if (T->isRealFloatingType()) {
13626     llvm::APFloat F(0.0);
13627     if (!EvaluateFloat(E, F, Info))
13628       return false;
13629     Result = APValue(F);
13630   } else if (T->isAnyComplexType()) {
13631     ComplexValue C;
13632     if (!EvaluateComplex(E, C, Info))
13633       return false;
13634     C.moveInto(Result);
13635   } else if (T->isFixedPointType()) {
13636     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
13637   } else if (T->isMemberPointerType()) {
13638     MemberPtr P;
13639     if (!EvaluateMemberPointer(E, P, Info))
13640       return false;
13641     P.moveInto(Result);
13642     return true;
13643   } else if (T->isArrayType()) {
13644     LValue LV;
13645     APValue &Value =
13646         Info.CurrentCall->createTemporary(E, T, false, LV);
13647     if (!EvaluateArray(E, LV, Value, Info))
13648       return false;
13649     Result = Value;
13650   } else if (T->isRecordType()) {
13651     LValue LV;
13652     APValue &Value = Info.CurrentCall->createTemporary(E, T, false, LV);
13653     if (!EvaluateRecord(E, LV, Value, Info))
13654       return false;
13655     Result = Value;
13656   } else if (T->isVoidType()) {
13657     if (!Info.getLangOpts().CPlusPlus11)
13658       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
13659         << E->getType();
13660     if (!EvaluateVoid(E, Info))
13661       return false;
13662   } else if (T->isAtomicType()) {
13663     QualType Unqual = T.getAtomicUnqualifiedType();
13664     if (Unqual->isArrayType() || Unqual->isRecordType()) {
13665       LValue LV;
13666       APValue &Value = Info.CurrentCall->createTemporary(E, Unqual, false, LV);
13667       if (!EvaluateAtomic(E, &LV, Value, Info))
13668         return false;
13669     } else {
13670       if (!EvaluateAtomic(E, nullptr, Result, Info))
13671         return false;
13672     }
13673   } else if (Info.getLangOpts().CPlusPlus11) {
13674     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
13675     return false;
13676   } else {
13677     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
13678     return false;
13679   }
13680 
13681   return true;
13682 }
13683 
13684 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
13685 /// cases, the in-place evaluation is essential, since later initializers for
13686 /// an object can indirectly refer to subobjects which were initialized earlier.
13687 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
13688                             const Expr *E, bool AllowNonLiteralTypes) {
13689   assert(!E->isValueDependent());
13690 
13691   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
13692     return false;
13693 
13694   if (E->isRValue()) {
13695     // Evaluate arrays and record types in-place, so that later initializers can
13696     // refer to earlier-initialized members of the object.
13697     QualType T = E->getType();
13698     if (T->isArrayType())
13699       return EvaluateArray(E, This, Result, Info);
13700     else if (T->isRecordType())
13701       return EvaluateRecord(E, This, Result, Info);
13702     else if (T->isAtomicType()) {
13703       QualType Unqual = T.getAtomicUnqualifiedType();
13704       if (Unqual->isArrayType() || Unqual->isRecordType())
13705         return EvaluateAtomic(E, &This, Result, Info);
13706     }
13707   }
13708 
13709   // For any other type, in-place evaluation is unimportant.
13710   return Evaluate(Result, Info, E);
13711 }
13712 
13713 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
13714 /// lvalue-to-rvalue cast if it is an lvalue.
13715 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
13716   if (Info.EnableNewConstInterp) {
13717     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
13718       return false;
13719   } else {
13720     if (E->getType().isNull())
13721       return false;
13722 
13723     if (!CheckLiteralType(Info, E))
13724       return false;
13725 
13726     if (!::Evaluate(Result, Info, E))
13727       return false;
13728 
13729     if (E->isGLValue()) {
13730       LValue LV;
13731       LV.setFrom(Info.Ctx, Result);
13732       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
13733         return false;
13734     }
13735   }
13736 
13737   // Check this core constant expression is a constant expression.
13738   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) &&
13739          CheckMemoryLeaks(Info);
13740 }
13741 
13742 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
13743                                  const ASTContext &Ctx, bool &IsConst) {
13744   // Fast-path evaluations of integer literals, since we sometimes see files
13745   // containing vast quantities of these.
13746   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
13747     Result.Val = APValue(APSInt(L->getValue(),
13748                                 L->getType()->isUnsignedIntegerType()));
13749     IsConst = true;
13750     return true;
13751   }
13752 
13753   // This case should be rare, but we need to check it before we check on
13754   // the type below.
13755   if (Exp->getType().isNull()) {
13756     IsConst = false;
13757     return true;
13758   }
13759 
13760   // FIXME: Evaluating values of large array and record types can cause
13761   // performance problems. Only do so in C++11 for now.
13762   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
13763                           Exp->getType()->isRecordType()) &&
13764       !Ctx.getLangOpts().CPlusPlus11) {
13765     IsConst = false;
13766     return true;
13767   }
13768   return false;
13769 }
13770 
13771 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
13772                                       Expr::SideEffectsKind SEK) {
13773   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
13774          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
13775 }
13776 
13777 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
13778                              const ASTContext &Ctx, EvalInfo &Info) {
13779   bool IsConst;
13780   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
13781     return IsConst;
13782 
13783   return EvaluateAsRValue(Info, E, Result.Val);
13784 }
13785 
13786 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
13787                           const ASTContext &Ctx,
13788                           Expr::SideEffectsKind AllowSideEffects,
13789                           EvalInfo &Info) {
13790   if (!E->getType()->isIntegralOrEnumerationType())
13791     return false;
13792 
13793   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
13794       !ExprResult.Val.isInt() ||
13795       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13796     return false;
13797 
13798   return true;
13799 }
13800 
13801 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
13802                                  const ASTContext &Ctx,
13803                                  Expr::SideEffectsKind AllowSideEffects,
13804                                  EvalInfo &Info) {
13805   if (!E->getType()->isFixedPointType())
13806     return false;
13807 
13808   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
13809     return false;
13810 
13811   if (!ExprResult.Val.isFixedPoint() ||
13812       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13813     return false;
13814 
13815   return true;
13816 }
13817 
13818 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
13819 /// any crazy technique (that has nothing to do with language standards) that
13820 /// we want to.  If this function returns true, it returns the folded constant
13821 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
13822 /// will be applied to the result.
13823 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
13824                             bool InConstantContext) const {
13825   assert(!isValueDependent() &&
13826          "Expression evaluator can't be called on a dependent expression.");
13827   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
13828   Info.InConstantContext = InConstantContext;
13829   return ::EvaluateAsRValue(this, Result, Ctx, Info);
13830 }
13831 
13832 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
13833                                       bool InConstantContext) const {
13834   assert(!isValueDependent() &&
13835          "Expression evaluator can't be called on a dependent expression.");
13836   EvalResult Scratch;
13837   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
13838          HandleConversionToBool(Scratch.Val, Result);
13839 }
13840 
13841 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
13842                          SideEffectsKind AllowSideEffects,
13843                          bool InConstantContext) const {
13844   assert(!isValueDependent() &&
13845          "Expression evaluator can't be called on a dependent expression.");
13846   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
13847   Info.InConstantContext = InConstantContext;
13848   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
13849 }
13850 
13851 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
13852                                 SideEffectsKind AllowSideEffects,
13853                                 bool InConstantContext) const {
13854   assert(!isValueDependent() &&
13855          "Expression evaluator can't be called on a dependent expression.");
13856   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
13857   Info.InConstantContext = InConstantContext;
13858   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
13859 }
13860 
13861 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
13862                            SideEffectsKind AllowSideEffects,
13863                            bool InConstantContext) const {
13864   assert(!isValueDependent() &&
13865          "Expression evaluator can't be called on a dependent expression.");
13866 
13867   if (!getType()->isRealFloatingType())
13868     return false;
13869 
13870   EvalResult ExprResult;
13871   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
13872       !ExprResult.Val.isFloat() ||
13873       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
13874     return false;
13875 
13876   Result = ExprResult.Val.getFloat();
13877   return true;
13878 }
13879 
13880 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
13881                             bool InConstantContext) const {
13882   assert(!isValueDependent() &&
13883          "Expression evaluator can't be called on a dependent expression.");
13884 
13885   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
13886   Info.InConstantContext = InConstantContext;
13887   LValue LV;
13888   CheckedTemporaries CheckedTemps;
13889   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
13890       Result.HasSideEffects ||
13891       !CheckLValueConstantExpression(Info, getExprLoc(),
13892                                      Ctx.getLValueReferenceType(getType()), LV,
13893                                      Expr::EvaluateForCodeGen, CheckedTemps))
13894     return false;
13895 
13896   LV.moveInto(Result.Val);
13897   return true;
13898 }
13899 
13900 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
13901                                   const ASTContext &Ctx, bool InPlace) const {
13902   assert(!isValueDependent() &&
13903          "Expression evaluator can't be called on a dependent expression.");
13904 
13905   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
13906   EvalInfo Info(Ctx, Result, EM);
13907   Info.InConstantContext = true;
13908 
13909   if (InPlace) {
13910     Info.setEvaluatingDecl(this, Result.Val);
13911     LValue LVal;
13912     LVal.set(this);
13913     if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
13914         Result.HasSideEffects)
13915       return false;
13916   } else if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects)
13917     return false;
13918 
13919   if (!Info.discardCleanups())
13920     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
13921 
13922   return CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
13923                                  Result.Val, Usage) &&
13924          CheckMemoryLeaks(Info);
13925 }
13926 
13927 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
13928                                  const VarDecl *VD,
13929                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
13930   assert(!isValueDependent() &&
13931          "Expression evaluator can't be called on a dependent expression.");
13932 
13933   // FIXME: Evaluating initializers for large array and record types can cause
13934   // performance problems. Only do so in C++11 for now.
13935   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
13936       !Ctx.getLangOpts().CPlusPlus11)
13937     return false;
13938 
13939   Expr::EvalStatus EStatus;
13940   EStatus.Diag = &Notes;
13941 
13942   EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
13943                                       ? EvalInfo::EM_ConstantExpression
13944                                       : EvalInfo::EM_ConstantFold);
13945   Info.setEvaluatingDecl(VD, Value);
13946   Info.InConstantContext = true;
13947 
13948   SourceLocation DeclLoc = VD->getLocation();
13949   QualType DeclTy = VD->getType();
13950 
13951   if (Info.EnableNewConstInterp) {
13952     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
13953     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
13954       return false;
13955   } else {
13956     LValue LVal;
13957     LVal.set(VD);
13958 
13959     if (!EvaluateInPlace(Value, Info, LVal, this,
13960                          /*AllowNonLiteralTypes=*/true) ||
13961         EStatus.HasSideEffects)
13962       return false;
13963 
13964     // At this point, any lifetime-extended temporaries are completely
13965     // initialized.
13966     Info.performLifetimeExtension();
13967 
13968     if (!Info.discardCleanups())
13969       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
13970   }
13971   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) &&
13972          CheckMemoryLeaks(Info);
13973 }
13974 
13975 bool VarDecl::evaluateDestruction(
13976     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
13977   Expr::EvalStatus EStatus;
13978   EStatus.Diag = &Notes;
13979 
13980   // Make a copy of the value for the destructor to mutate, if we know it.
13981   // Otherwise, treat the value as default-initialized; if the destructor works
13982   // anyway, then the destruction is constant (and must be essentially empty).
13983   APValue DestroyedValue =
13984       (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
13985           ? *getEvaluatedValue()
13986           : getDefaultInitValue(getType());
13987 
13988   EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression);
13989   Info.setEvaluatingDecl(this, DestroyedValue,
13990                          EvalInfo::EvaluatingDeclKind::Dtor);
13991   Info.InConstantContext = true;
13992 
13993   SourceLocation DeclLoc = getLocation();
13994   QualType DeclTy = getType();
13995 
13996   LValue LVal;
13997   LVal.set(this);
13998 
13999   if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) ||
14000       EStatus.HasSideEffects)
14001     return false;
14002 
14003   if (!Info.discardCleanups())
14004     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14005 
14006   ensureEvaluatedStmt()->HasConstantDestruction = true;
14007   return true;
14008 }
14009 
14010 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
14011 /// constant folded, but discard the result.
14012 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
14013   assert(!isValueDependent() &&
14014          "Expression evaluator can't be called on a dependent expression.");
14015 
14016   EvalResult Result;
14017   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
14018          !hasUnacceptableSideEffect(Result, SEK);
14019 }
14020 
14021 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
14022                     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 
14031   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
14032   (void)Result;
14033   assert(Result && "Could not evaluate expression");
14034   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14035 
14036   return EVResult.Val.getInt();
14037 }
14038 
14039 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
14040     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14041   assert(!isValueDependent() &&
14042          "Expression evaluator can't be called on a dependent expression.");
14043 
14044   EvalResult EVResult;
14045   EVResult.Diag = Diag;
14046   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14047   Info.InConstantContext = true;
14048   Info.CheckingForUndefinedBehavior = true;
14049 
14050   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
14051   (void)Result;
14052   assert(Result && "Could not evaluate expression");
14053   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14054 
14055   return EVResult.Val.getInt();
14056 }
14057 
14058 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
14059   assert(!isValueDependent() &&
14060          "Expression evaluator can't be called on a dependent expression.");
14061 
14062   bool IsConst;
14063   EvalResult EVResult;
14064   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
14065     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14066     Info.CheckingForUndefinedBehavior = true;
14067     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
14068   }
14069 }
14070 
14071 bool Expr::EvalResult::isGlobalLValue() const {
14072   assert(Val.isLValue());
14073   return IsGlobalLValue(Val.getLValueBase());
14074 }
14075 
14076 
14077 /// isIntegerConstantExpr - this recursive routine will test if an expression is
14078 /// an integer constant expression.
14079 
14080 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
14081 /// comma, etc
14082 
14083 // CheckICE - This function does the fundamental ICE checking: the returned
14084 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
14085 // and a (possibly null) SourceLocation indicating the location of the problem.
14086 //
14087 // Note that to reduce code duplication, this helper does no evaluation
14088 // itself; the caller checks whether the expression is evaluatable, and
14089 // in the rare cases where CheckICE actually cares about the evaluated
14090 // value, it calls into Evaluate.
14091 
14092 namespace {
14093 
14094 enum ICEKind {
14095   /// This expression is an ICE.
14096   IK_ICE,
14097   /// This expression is not an ICE, but if it isn't evaluated, it's
14098   /// a legal subexpression for an ICE. This return value is used to handle
14099   /// the comma operator in C99 mode, and non-constant subexpressions.
14100   IK_ICEIfUnevaluated,
14101   /// This expression is not an ICE, and is not a legal subexpression for one.
14102   IK_NotICE
14103 };
14104 
14105 struct ICEDiag {
14106   ICEKind Kind;
14107   SourceLocation Loc;
14108 
14109   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
14110 };
14111 
14112 }
14113 
14114 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
14115 
14116 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
14117 
14118 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
14119   Expr::EvalResult EVResult;
14120   Expr::EvalStatus Status;
14121   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
14122 
14123   Info.InConstantContext = true;
14124   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
14125       !EVResult.Val.isInt())
14126     return ICEDiag(IK_NotICE, E->getBeginLoc());
14127 
14128   return NoDiag();
14129 }
14130 
14131 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
14132   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
14133   if (!E->getType()->isIntegralOrEnumerationType())
14134     return ICEDiag(IK_NotICE, E->getBeginLoc());
14135 
14136   switch (E->getStmtClass()) {
14137 #define ABSTRACT_STMT(Node)
14138 #define STMT(Node, Base) case Expr::Node##Class:
14139 #define EXPR(Node, Base)
14140 #include "clang/AST/StmtNodes.inc"
14141   case Expr::PredefinedExprClass:
14142   case Expr::FloatingLiteralClass:
14143   case Expr::ImaginaryLiteralClass:
14144   case Expr::StringLiteralClass:
14145   case Expr::ArraySubscriptExprClass:
14146   case Expr::OMPArraySectionExprClass:
14147   case Expr::OMPArrayShapingExprClass:
14148   case Expr::OMPIteratorExprClass:
14149   case Expr::MemberExprClass:
14150   case Expr::CompoundAssignOperatorClass:
14151   case Expr::CompoundLiteralExprClass:
14152   case Expr::ExtVectorElementExprClass:
14153   case Expr::DesignatedInitExprClass:
14154   case Expr::ArrayInitLoopExprClass:
14155   case Expr::ArrayInitIndexExprClass:
14156   case Expr::NoInitExprClass:
14157   case Expr::DesignatedInitUpdateExprClass:
14158   case Expr::ImplicitValueInitExprClass:
14159   case Expr::ParenListExprClass:
14160   case Expr::VAArgExprClass:
14161   case Expr::AddrLabelExprClass:
14162   case Expr::StmtExprClass:
14163   case Expr::CXXMemberCallExprClass:
14164   case Expr::CUDAKernelCallExprClass:
14165   case Expr::CXXDynamicCastExprClass:
14166   case Expr::CXXTypeidExprClass:
14167   case Expr::CXXUuidofExprClass:
14168   case Expr::MSPropertyRefExprClass:
14169   case Expr::MSPropertySubscriptExprClass:
14170   case Expr::CXXNullPtrLiteralExprClass:
14171   case Expr::UserDefinedLiteralClass:
14172   case Expr::CXXThisExprClass:
14173   case Expr::CXXThrowExprClass:
14174   case Expr::CXXNewExprClass:
14175   case Expr::CXXDeleteExprClass:
14176   case Expr::CXXPseudoDestructorExprClass:
14177   case Expr::UnresolvedLookupExprClass:
14178   case Expr::TypoExprClass:
14179   case Expr::RecoveryExprClass:
14180   case Expr::DependentScopeDeclRefExprClass:
14181   case Expr::CXXConstructExprClass:
14182   case Expr::CXXInheritedCtorInitExprClass:
14183   case Expr::CXXStdInitializerListExprClass:
14184   case Expr::CXXBindTemporaryExprClass:
14185   case Expr::ExprWithCleanupsClass:
14186   case Expr::CXXTemporaryObjectExprClass:
14187   case Expr::CXXUnresolvedConstructExprClass:
14188   case Expr::CXXDependentScopeMemberExprClass:
14189   case Expr::UnresolvedMemberExprClass:
14190   case Expr::ObjCStringLiteralClass:
14191   case Expr::ObjCBoxedExprClass:
14192   case Expr::ObjCArrayLiteralClass:
14193   case Expr::ObjCDictionaryLiteralClass:
14194   case Expr::ObjCEncodeExprClass:
14195   case Expr::ObjCMessageExprClass:
14196   case Expr::ObjCSelectorExprClass:
14197   case Expr::ObjCProtocolExprClass:
14198   case Expr::ObjCIvarRefExprClass:
14199   case Expr::ObjCPropertyRefExprClass:
14200   case Expr::ObjCSubscriptRefExprClass:
14201   case Expr::ObjCIsaExprClass:
14202   case Expr::ObjCAvailabilityCheckExprClass:
14203   case Expr::ShuffleVectorExprClass:
14204   case Expr::ConvertVectorExprClass:
14205   case Expr::BlockExprClass:
14206   case Expr::NoStmtClass:
14207   case Expr::OpaqueValueExprClass:
14208   case Expr::PackExpansionExprClass:
14209   case Expr::SubstNonTypeTemplateParmPackExprClass:
14210   case Expr::FunctionParmPackExprClass:
14211   case Expr::AsTypeExprClass:
14212   case Expr::ObjCIndirectCopyRestoreExprClass:
14213   case Expr::MaterializeTemporaryExprClass:
14214   case Expr::PseudoObjectExprClass:
14215   case Expr::AtomicExprClass:
14216   case Expr::LambdaExprClass:
14217   case Expr::CXXFoldExprClass:
14218   case Expr::CoawaitExprClass:
14219   case Expr::DependentCoawaitExprClass:
14220   case Expr::CoyieldExprClass:
14221     return ICEDiag(IK_NotICE, E->getBeginLoc());
14222 
14223   case Expr::InitListExprClass: {
14224     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
14225     // form "T x = { a };" is equivalent to "T x = a;".
14226     // Unless we're initializing a reference, T is a scalar as it is known to be
14227     // of integral or enumeration type.
14228     if (E->isRValue())
14229       if (cast<InitListExpr>(E)->getNumInits() == 1)
14230         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
14231     return ICEDiag(IK_NotICE, E->getBeginLoc());
14232   }
14233 
14234   case Expr::SizeOfPackExprClass:
14235   case Expr::GNUNullExprClass:
14236   case Expr::SourceLocExprClass:
14237     return NoDiag();
14238 
14239   case Expr::SubstNonTypeTemplateParmExprClass:
14240     return
14241       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
14242 
14243   case Expr::ConstantExprClass:
14244     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
14245 
14246   case Expr::ParenExprClass:
14247     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
14248   case Expr::GenericSelectionExprClass:
14249     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
14250   case Expr::IntegerLiteralClass:
14251   case Expr::FixedPointLiteralClass:
14252   case Expr::CharacterLiteralClass:
14253   case Expr::ObjCBoolLiteralExprClass:
14254   case Expr::CXXBoolLiteralExprClass:
14255   case Expr::CXXScalarValueInitExprClass:
14256   case Expr::TypeTraitExprClass:
14257   case Expr::ConceptSpecializationExprClass:
14258   case Expr::RequiresExprClass:
14259   case Expr::ArrayTypeTraitExprClass:
14260   case Expr::ExpressionTraitExprClass:
14261   case Expr::CXXNoexceptExprClass:
14262     return NoDiag();
14263   case Expr::CallExprClass:
14264   case Expr::CXXOperatorCallExprClass: {
14265     // C99 6.6/3 allows function calls within unevaluated subexpressions of
14266     // constant expressions, but they can never be ICEs because an ICE cannot
14267     // contain an operand of (pointer to) function type.
14268     const CallExpr *CE = cast<CallExpr>(E);
14269     if (CE->getBuiltinCallee())
14270       return CheckEvalInICE(E, Ctx);
14271     return ICEDiag(IK_NotICE, E->getBeginLoc());
14272   }
14273   case Expr::CXXRewrittenBinaryOperatorClass:
14274     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
14275                     Ctx);
14276   case Expr::DeclRefExprClass: {
14277     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
14278       return NoDiag();
14279     const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
14280     if (Ctx.getLangOpts().CPlusPlus &&
14281         D && IsConstNonVolatile(D->getType())) {
14282       // Parameter variables are never constants.  Without this check,
14283       // getAnyInitializer() can find a default argument, which leads
14284       // to chaos.
14285       if (isa<ParmVarDecl>(D))
14286         return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14287 
14288       // C++ 7.1.5.1p2
14289       //   A variable of non-volatile const-qualified integral or enumeration
14290       //   type initialized by an ICE can be used in ICEs.
14291       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
14292         if (!Dcl->getType()->isIntegralOrEnumerationType())
14293           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14294 
14295         const VarDecl *VD;
14296         // Look for a declaration of this variable that has an initializer, and
14297         // check whether it is an ICE.
14298         if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
14299           return NoDiag();
14300         else
14301           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
14302       }
14303     }
14304     return ICEDiag(IK_NotICE, E->getBeginLoc());
14305   }
14306   case Expr::UnaryOperatorClass: {
14307     const UnaryOperator *Exp = cast<UnaryOperator>(E);
14308     switch (Exp->getOpcode()) {
14309     case UO_PostInc:
14310     case UO_PostDec:
14311     case UO_PreInc:
14312     case UO_PreDec:
14313     case UO_AddrOf:
14314     case UO_Deref:
14315     case UO_Coawait:
14316       // C99 6.6/3 allows increment and decrement within unevaluated
14317       // subexpressions of constant expressions, but they can never be ICEs
14318       // because an ICE cannot contain an lvalue operand.
14319       return ICEDiag(IK_NotICE, E->getBeginLoc());
14320     case UO_Extension:
14321     case UO_LNot:
14322     case UO_Plus:
14323     case UO_Minus:
14324     case UO_Not:
14325     case UO_Real:
14326     case UO_Imag:
14327       return CheckICE(Exp->getSubExpr(), Ctx);
14328     }
14329     llvm_unreachable("invalid unary operator class");
14330   }
14331   case Expr::OffsetOfExprClass: {
14332     // Note that per C99, offsetof must be an ICE. And AFAIK, using
14333     // EvaluateAsRValue matches the proposed gcc behavior for cases like
14334     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
14335     // compliance: we should warn earlier for offsetof expressions with
14336     // array subscripts that aren't ICEs, and if the array subscripts
14337     // are ICEs, the value of the offsetof must be an integer constant.
14338     return CheckEvalInICE(E, Ctx);
14339   }
14340   case Expr::UnaryExprOrTypeTraitExprClass: {
14341     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
14342     if ((Exp->getKind() ==  UETT_SizeOf) &&
14343         Exp->getTypeOfArgument()->isVariableArrayType())
14344       return ICEDiag(IK_NotICE, E->getBeginLoc());
14345     return NoDiag();
14346   }
14347   case Expr::BinaryOperatorClass: {
14348     const BinaryOperator *Exp = cast<BinaryOperator>(E);
14349     switch (Exp->getOpcode()) {
14350     case BO_PtrMemD:
14351     case BO_PtrMemI:
14352     case BO_Assign:
14353     case BO_MulAssign:
14354     case BO_DivAssign:
14355     case BO_RemAssign:
14356     case BO_AddAssign:
14357     case BO_SubAssign:
14358     case BO_ShlAssign:
14359     case BO_ShrAssign:
14360     case BO_AndAssign:
14361     case BO_XorAssign:
14362     case BO_OrAssign:
14363       // C99 6.6/3 allows assignments within unevaluated subexpressions of
14364       // constant expressions, but they can never be ICEs because an ICE cannot
14365       // contain an lvalue operand.
14366       return ICEDiag(IK_NotICE, E->getBeginLoc());
14367 
14368     case BO_Mul:
14369     case BO_Div:
14370     case BO_Rem:
14371     case BO_Add:
14372     case BO_Sub:
14373     case BO_Shl:
14374     case BO_Shr:
14375     case BO_LT:
14376     case BO_GT:
14377     case BO_LE:
14378     case BO_GE:
14379     case BO_EQ:
14380     case BO_NE:
14381     case BO_And:
14382     case BO_Xor:
14383     case BO_Or:
14384     case BO_Comma:
14385     case BO_Cmp: {
14386       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
14387       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
14388       if (Exp->getOpcode() == BO_Div ||
14389           Exp->getOpcode() == BO_Rem) {
14390         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
14391         // we don't evaluate one.
14392         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
14393           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
14394           if (REval == 0)
14395             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14396           if (REval.isSigned() && REval.isAllOnesValue()) {
14397             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
14398             if (LEval.isMinSignedValue())
14399               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14400           }
14401         }
14402       }
14403       if (Exp->getOpcode() == BO_Comma) {
14404         if (Ctx.getLangOpts().C99) {
14405           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
14406           // if it isn't evaluated.
14407           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
14408             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
14409         } else {
14410           // In both C89 and C++, commas in ICEs are illegal.
14411           return ICEDiag(IK_NotICE, E->getBeginLoc());
14412         }
14413       }
14414       return Worst(LHSResult, RHSResult);
14415     }
14416     case BO_LAnd:
14417     case BO_LOr: {
14418       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
14419       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
14420       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
14421         // Rare case where the RHS has a comma "side-effect"; we need
14422         // to actually check the condition to see whether the side
14423         // with the comma is evaluated.
14424         if ((Exp->getOpcode() == BO_LAnd) !=
14425             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
14426           return RHSResult;
14427         return NoDiag();
14428       }
14429 
14430       return Worst(LHSResult, RHSResult);
14431     }
14432     }
14433     llvm_unreachable("invalid binary operator kind");
14434   }
14435   case Expr::ImplicitCastExprClass:
14436   case Expr::CStyleCastExprClass:
14437   case Expr::CXXFunctionalCastExprClass:
14438   case Expr::CXXStaticCastExprClass:
14439   case Expr::CXXReinterpretCastExprClass:
14440   case Expr::CXXConstCastExprClass:
14441   case Expr::ObjCBridgedCastExprClass: {
14442     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
14443     if (isa<ExplicitCastExpr>(E)) {
14444       if (const FloatingLiteral *FL
14445             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
14446         unsigned DestWidth = Ctx.getIntWidth(E->getType());
14447         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
14448         APSInt IgnoredVal(DestWidth, !DestSigned);
14449         bool Ignored;
14450         // If the value does not fit in the destination type, the behavior is
14451         // undefined, so we are not required to treat it as a constant
14452         // expression.
14453         if (FL->getValue().convertToInteger(IgnoredVal,
14454                                             llvm::APFloat::rmTowardZero,
14455                                             &Ignored) & APFloat::opInvalidOp)
14456           return ICEDiag(IK_NotICE, E->getBeginLoc());
14457         return NoDiag();
14458       }
14459     }
14460     switch (cast<CastExpr>(E)->getCastKind()) {
14461     case CK_LValueToRValue:
14462     case CK_AtomicToNonAtomic:
14463     case CK_NonAtomicToAtomic:
14464     case CK_NoOp:
14465     case CK_IntegralToBoolean:
14466     case CK_IntegralCast:
14467       return CheckICE(SubExpr, Ctx);
14468     default:
14469       return ICEDiag(IK_NotICE, E->getBeginLoc());
14470     }
14471   }
14472   case Expr::BinaryConditionalOperatorClass: {
14473     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
14474     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
14475     if (CommonResult.Kind == IK_NotICE) return CommonResult;
14476     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
14477     if (FalseResult.Kind == IK_NotICE) return FalseResult;
14478     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
14479     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
14480         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
14481     return FalseResult;
14482   }
14483   case Expr::ConditionalOperatorClass: {
14484     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
14485     // If the condition (ignoring parens) is a __builtin_constant_p call,
14486     // then only the true side is actually considered in an integer constant
14487     // expression, and it is fully evaluated.  This is an important GNU
14488     // extension.  See GCC PR38377 for discussion.
14489     if (const CallExpr *CallCE
14490         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
14491       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
14492         return CheckEvalInICE(E, Ctx);
14493     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
14494     if (CondResult.Kind == IK_NotICE)
14495       return CondResult;
14496 
14497     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
14498     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
14499 
14500     if (TrueResult.Kind == IK_NotICE)
14501       return TrueResult;
14502     if (FalseResult.Kind == IK_NotICE)
14503       return FalseResult;
14504     if (CondResult.Kind == IK_ICEIfUnevaluated)
14505       return CondResult;
14506     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
14507       return NoDiag();
14508     // Rare case where the diagnostics depend on which side is evaluated
14509     // Note that if we get here, CondResult is 0, and at least one of
14510     // TrueResult and FalseResult is non-zero.
14511     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
14512       return FalseResult;
14513     return TrueResult;
14514   }
14515   case Expr::CXXDefaultArgExprClass:
14516     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
14517   case Expr::CXXDefaultInitExprClass:
14518     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
14519   case Expr::ChooseExprClass: {
14520     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
14521   }
14522   case Expr::BuiltinBitCastExprClass: {
14523     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
14524       return ICEDiag(IK_NotICE, E->getBeginLoc());
14525     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
14526   }
14527   }
14528 
14529   llvm_unreachable("Invalid StmtClass!");
14530 }
14531 
14532 /// Evaluate an expression as a C++11 integral constant expression.
14533 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
14534                                                     const Expr *E,
14535                                                     llvm::APSInt *Value,
14536                                                     SourceLocation *Loc) {
14537   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
14538     if (Loc) *Loc = E->getExprLoc();
14539     return false;
14540   }
14541 
14542   APValue Result;
14543   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
14544     return false;
14545 
14546   if (!Result.isInt()) {
14547     if (Loc) *Loc = E->getExprLoc();
14548     return false;
14549   }
14550 
14551   if (Value) *Value = Result.getInt();
14552   return true;
14553 }
14554 
14555 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
14556                                  SourceLocation *Loc) const {
14557   assert(!isValueDependent() &&
14558          "Expression evaluator can't be called on a dependent expression.");
14559 
14560   if (Ctx.getLangOpts().CPlusPlus11)
14561     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
14562 
14563   ICEDiag D = CheckICE(this, Ctx);
14564   if (D.Kind != IK_ICE) {
14565     if (Loc) *Loc = D.Loc;
14566     return false;
14567   }
14568   return true;
14569 }
14570 
14571 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
14572                                  SourceLocation *Loc, bool isEvaluated) const {
14573   assert(!isValueDependent() &&
14574          "Expression evaluator can't be called on a dependent expression.");
14575 
14576   if (Ctx.getLangOpts().CPlusPlus11)
14577     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
14578 
14579   if (!isIntegerConstantExpr(Ctx, Loc))
14580     return false;
14581 
14582   // The only possible side-effects here are due to UB discovered in the
14583   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
14584   // required to treat the expression as an ICE, so we produce the folded
14585   // value.
14586   EvalResult ExprResult;
14587   Expr::EvalStatus Status;
14588   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
14589   Info.InConstantContext = true;
14590 
14591   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
14592     llvm_unreachable("ICE cannot be evaluated!");
14593 
14594   Value = ExprResult.Val.getInt();
14595   return true;
14596 }
14597 
14598 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
14599   assert(!isValueDependent() &&
14600          "Expression evaluator can't be called on a dependent expression.");
14601 
14602   return CheckICE(this, Ctx).Kind == IK_ICE;
14603 }
14604 
14605 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
14606                                SourceLocation *Loc) const {
14607   assert(!isValueDependent() &&
14608          "Expression evaluator can't be called on a dependent expression.");
14609 
14610   // We support this checking in C++98 mode in order to diagnose compatibility
14611   // issues.
14612   assert(Ctx.getLangOpts().CPlusPlus);
14613 
14614   // Build evaluation settings.
14615   Expr::EvalStatus Status;
14616   SmallVector<PartialDiagnosticAt, 8> Diags;
14617   Status.Diag = &Diags;
14618   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
14619 
14620   APValue Scratch;
14621   bool IsConstExpr =
14622       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
14623       // FIXME: We don't produce a diagnostic for this, but the callers that
14624       // call us on arbitrary full-expressions should generally not care.
14625       Info.discardCleanups() && !Status.HasSideEffects;
14626 
14627   if (!Diags.empty()) {
14628     IsConstExpr = false;
14629     if (Loc) *Loc = Diags[0].first;
14630   } else if (!IsConstExpr) {
14631     // FIXME: This shouldn't happen.
14632     if (Loc) *Loc = getExprLoc();
14633   }
14634 
14635   return IsConstExpr;
14636 }
14637 
14638 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
14639                                     const FunctionDecl *Callee,
14640                                     ArrayRef<const Expr*> Args,
14641                                     const Expr *This) const {
14642   assert(!isValueDependent() &&
14643          "Expression evaluator can't be called on a dependent expression.");
14644 
14645   Expr::EvalStatus Status;
14646   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
14647   Info.InConstantContext = true;
14648 
14649   LValue ThisVal;
14650   const LValue *ThisPtr = nullptr;
14651   if (This) {
14652 #ifndef NDEBUG
14653     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
14654     assert(MD && "Don't provide `this` for non-methods.");
14655     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
14656 #endif
14657     if (!This->isValueDependent() &&
14658         EvaluateObjectArgument(Info, This, ThisVal) &&
14659         !Info.EvalStatus.HasSideEffects)
14660       ThisPtr = &ThisVal;
14661 
14662     // Ignore any side-effects from a failed evaluation. This is safe because
14663     // they can't interfere with any other argument evaluation.
14664     Info.EvalStatus.HasSideEffects = false;
14665   }
14666 
14667   ArgVector ArgValues(Args.size());
14668   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
14669        I != E; ++I) {
14670     if ((*I)->isValueDependent() ||
14671         !Evaluate(ArgValues[I - Args.begin()], Info, *I) ||
14672         Info.EvalStatus.HasSideEffects)
14673       // If evaluation fails, throw away the argument entirely.
14674       ArgValues[I - Args.begin()] = APValue();
14675 
14676     // Ignore any side-effects from a failed evaluation. This is safe because
14677     // they can't interfere with any other argument evaluation.
14678     Info.EvalStatus.HasSideEffects = false;
14679   }
14680 
14681   // Parameter cleanups happen in the caller and are not part of this
14682   // evaluation.
14683   Info.discardCleanups();
14684   Info.EvalStatus.HasSideEffects = false;
14685 
14686   // Build fake call to Callee.
14687   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
14688                        ArgValues.data());
14689   // FIXME: Missing ExprWithCleanups in enable_if conditions?
14690   FullExpressionRAII Scope(Info);
14691   return Evaluate(Value, Info, this) && Scope.destroy() &&
14692          !Info.EvalStatus.HasSideEffects;
14693 }
14694 
14695 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
14696                                    SmallVectorImpl<
14697                                      PartialDiagnosticAt> &Diags) {
14698   // FIXME: It would be useful to check constexpr function templates, but at the
14699   // moment the constant expression evaluator cannot cope with the non-rigorous
14700   // ASTs which we build for dependent expressions.
14701   if (FD->isDependentContext())
14702     return true;
14703 
14704   Expr::EvalStatus Status;
14705   Status.Diag = &Diags;
14706 
14707   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
14708   Info.InConstantContext = true;
14709   Info.CheckingPotentialConstantExpression = true;
14710 
14711   // The constexpr VM attempts to compile all methods to bytecode here.
14712   if (Info.EnableNewConstInterp) {
14713     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
14714     return Diags.empty();
14715   }
14716 
14717   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
14718   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
14719 
14720   // Fabricate an arbitrary expression on the stack and pretend that it
14721   // is a temporary being used as the 'this' pointer.
14722   LValue This;
14723   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
14724   This.set({&VIE, Info.CurrentCall->Index});
14725 
14726   ArrayRef<const Expr*> Args;
14727 
14728   APValue Scratch;
14729   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
14730     // Evaluate the call as a constant initializer, to allow the construction
14731     // of objects of non-literal types.
14732     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
14733     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
14734   } else {
14735     SourceLocation Loc = FD->getLocation();
14736     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
14737                        Args, FD->getBody(), Info, Scratch, nullptr);
14738   }
14739 
14740   return Diags.empty();
14741 }
14742 
14743 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
14744                                               const FunctionDecl *FD,
14745                                               SmallVectorImpl<
14746                                                 PartialDiagnosticAt> &Diags) {
14747   assert(!E->isValueDependent() &&
14748          "Expression evaluator can't be called on a dependent expression.");
14749 
14750   Expr::EvalStatus Status;
14751   Status.Diag = &Diags;
14752 
14753   EvalInfo Info(FD->getASTContext(), Status,
14754                 EvalInfo::EM_ConstantExpressionUnevaluated);
14755   Info.InConstantContext = true;
14756   Info.CheckingPotentialConstantExpression = true;
14757 
14758   // Fabricate a call stack frame to give the arguments a plausible cover story.
14759   ArrayRef<const Expr*> Args;
14760   ArgVector ArgValues(0);
14761   bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
14762   (void)Success;
14763   assert(Success &&
14764          "Failed to set up arguments for potential constant evaluation");
14765   CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
14766 
14767   APValue ResultScratch;
14768   Evaluate(ResultScratch, Info, E);
14769   return Diags.empty();
14770 }
14771 
14772 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
14773                                  unsigned Type) const {
14774   if (!getType()->isPointerType())
14775     return false;
14776 
14777   Expr::EvalStatus Status;
14778   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
14779   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
14780 }
14781