1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Expr constant evaluator.
10 //
11 // Constant expression evaluation produces four main results:
12 //
13 //  * A success/failure flag indicating whether constant folding was successful.
14 //    This is the 'bool' return value used by most of the code in this file. A
15 //    'false' return value indicates that constant folding has failed, and any
16 //    appropriate diagnostic has already been produced.
17 //
18 //  * An evaluated result, valid only if constant folding has not failed.
19 //
20 //  * A flag indicating if evaluation encountered (unevaluated) side-effects.
21 //    These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22 //    where it is possible to determine the evaluated result regardless.
23 //
24 //  * A set of notes indicating why the evaluation was not a constant expression
25 //    (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26 //    too, why the expression could not be folded.
27 //
28 // If we are checking for a potential constant expression, failure to constant
29 // fold a potential constant sub-expression will be indicated by a 'false'
30 // return value (the expression could not be folded) and no diagnostic (the
31 // expression is not necessarily non-constant).
32 //
33 //===----------------------------------------------------------------------===//
34 
35 #include "Interp/Context.h"
36 #include "Interp/Frame.h"
37 #include "Interp/State.h"
38 #include "clang/AST/APValue.h"
39 #include "clang/AST/ASTContext.h"
40 #include "clang/AST/ASTDiagnostic.h"
41 #include "clang/AST/ASTLambda.h"
42 #include "clang/AST/Attr.h"
43 #include "clang/AST/CXXInheritance.h"
44 #include "clang/AST/CharUnits.h"
45 #include "clang/AST/CurrentSourceLocExprScope.h"
46 #include "clang/AST/Expr.h"
47 #include "clang/AST/OSLog.h"
48 #include "clang/AST/OptionalDiagnostic.h"
49 #include "clang/AST/RecordLayout.h"
50 #include "clang/AST/StmtVisitor.h"
51 #include "clang/AST/TypeLoc.h"
52 #include "clang/Basic/Builtins.h"
53 #include "clang/Basic/TargetInfo.h"
54 #include "llvm/ADT/APFixedPoint.h"
55 #include "llvm/ADT/Optional.h"
56 #include "llvm/ADT/SmallBitVector.h"
57 #include "llvm/Support/Debug.h"
58 #include "llvm/Support/SaveAndRestore.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include <cstring>
61 #include <functional>
62 
63 #define DEBUG_TYPE "exprconstant"
64 
65 using namespace clang;
66 using llvm::APFixedPoint;
67 using llvm::APInt;
68 using llvm::APSInt;
69 using llvm::APFloat;
70 using llvm::FixedPointSemantics;
71 using llvm::Optional;
72 
73 namespace {
74   struct LValue;
75   class CallStackFrame;
76   class EvalInfo;
77 
78   using SourceLocExprScopeGuard =
79       CurrentSourceLocExprScope::SourceLocExprScopeGuard;
80 
81   static QualType getType(APValue::LValueBase B) {
82     if (!B) return QualType();
83     if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
84       // FIXME: It's unclear where we're supposed to take the type from, and
85       // this actually matters for arrays of unknown bound. Eg:
86       //
87       // extern int arr[]; void f() { extern int arr[3]; };
88       // constexpr int *p = &arr[1]; // valid?
89       //
90       // For now, we take the array bound from the most recent declaration.
91       for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
92            Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
93         QualType T = Redecl->getType();
94         if (!T->isIncompleteArrayType())
95           return T;
96       }
97       return D->getType();
98     }
99 
100     if (B.is<TypeInfoLValue>())
101       return B.getTypeInfoType();
102 
103     if (B.is<DynamicAllocLValue>())
104       return B.getDynamicAllocType();
105 
106     const Expr *Base = B.get<const Expr*>();
107 
108     // For a materialized temporary, the type of the temporary we materialized
109     // may not be the type of the expression.
110     if (const MaterializeTemporaryExpr *MTE =
111             dyn_cast<MaterializeTemporaryExpr>(Base)) {
112       SmallVector<const Expr *, 2> CommaLHSs;
113       SmallVector<SubobjectAdjustment, 2> Adjustments;
114       const Expr *Temp = MTE->getSubExpr();
115       const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
116                                                                Adjustments);
117       // Keep any cv-qualifiers from the reference if we generated a temporary
118       // for it directly. Otherwise use the type after adjustment.
119       if (!Adjustments.empty())
120         return Inner->getType();
121     }
122 
123     return Base->getType();
124   }
125 
126   /// Get an LValue path entry, which is known to not be an array index, as a
127   /// field declaration.
128   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
129     return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
130   }
131   /// Get an LValue path entry, which is known to not be an array index, as a
132   /// base class declaration.
133   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
134     return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
135   }
136   /// Determine whether this LValue path entry for a base class names a virtual
137   /// base class.
138   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
139     return E.getAsBaseOrMember().getInt();
140   }
141 
142   /// Given an expression, determine the type used to store the result of
143   /// evaluating that expression.
144   static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
145     if (E->isRValue())
146       return E->getType();
147     return Ctx.getLValueReferenceType(E->getType());
148   }
149 
150   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
151   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
152     const FunctionDecl *Callee = CE->getDirectCallee();
153     return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
154   }
155 
156   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
157   /// This will look through a single cast.
158   ///
159   /// Returns null if we couldn't unwrap a function with alloc_size.
160   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
161     if (!E->getType()->isPointerType())
162       return nullptr;
163 
164     E = E->IgnoreParens();
165     // If we're doing a variable assignment from e.g. malloc(N), there will
166     // probably be a cast of some kind. In exotic cases, we might also see a
167     // top-level ExprWithCleanups. Ignore them either way.
168     if (const auto *FE = dyn_cast<FullExpr>(E))
169       E = FE->getSubExpr()->IgnoreParens();
170 
171     if (const auto *Cast = dyn_cast<CastExpr>(E))
172       E = Cast->getSubExpr()->IgnoreParens();
173 
174     if (const auto *CE = dyn_cast<CallExpr>(E))
175       return getAllocSizeAttr(CE) ? CE : nullptr;
176     return nullptr;
177   }
178 
179   /// Determines whether or not the given Base contains a call to a function
180   /// with the alloc_size attribute.
181   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
182     const auto *E = Base.dyn_cast<const Expr *>();
183     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
184   }
185 
186   /// The bound to claim that an array of unknown bound has.
187   /// The value in MostDerivedArraySize is undefined in this case. So, set it
188   /// to an arbitrary value that's likely to loudly break things if it's used.
189   static const uint64_t AssumedSizeForUnsizedArray =
190       std::numeric_limits<uint64_t>::max() / 2;
191 
192   /// Determines if an LValue with the given LValueBase will have an unsized
193   /// array in its designator.
194   /// Find the path length and type of the most-derived subobject in the given
195   /// path, and find the size of the containing array, if any.
196   static unsigned
197   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
198                            ArrayRef<APValue::LValuePathEntry> Path,
199                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
200                            bool &FirstEntryIsUnsizedArray) {
201     // This only accepts LValueBases from APValues, and APValues don't support
202     // arrays that lack size info.
203     assert(!isBaseAnAllocSizeCall(Base) &&
204            "Unsized arrays shouldn't appear here");
205     unsigned MostDerivedLength = 0;
206     Type = getType(Base);
207 
208     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
209       if (Type->isArrayType()) {
210         const ArrayType *AT = Ctx.getAsArrayType(Type);
211         Type = AT->getElementType();
212         MostDerivedLength = I + 1;
213         IsArray = true;
214 
215         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
216           ArraySize = CAT->getSize().getZExtValue();
217         } else {
218           assert(I == 0 && "unexpected unsized array designator");
219           FirstEntryIsUnsizedArray = true;
220           ArraySize = AssumedSizeForUnsizedArray;
221         }
222       } else if (Type->isAnyComplexType()) {
223         const ComplexType *CT = Type->castAs<ComplexType>();
224         Type = CT->getElementType();
225         ArraySize = 2;
226         MostDerivedLength = I + 1;
227         IsArray = true;
228       } else if (const FieldDecl *FD = getAsField(Path[I])) {
229         Type = FD->getType();
230         ArraySize = 0;
231         MostDerivedLength = I + 1;
232         IsArray = false;
233       } else {
234         // Path[I] describes a base class.
235         ArraySize = 0;
236         IsArray = false;
237       }
238     }
239     return MostDerivedLength;
240   }
241 
242   /// A path from a glvalue to a subobject of that glvalue.
243   struct SubobjectDesignator {
244     /// True if the subobject was named in a manner not supported by C++11. Such
245     /// lvalues can still be folded, but they are not core constant expressions
246     /// and we cannot perform lvalue-to-rvalue conversions on them.
247     unsigned Invalid : 1;
248 
249     /// Is this a pointer one past the end of an object?
250     unsigned IsOnePastTheEnd : 1;
251 
252     /// Indicator of whether the first entry is an unsized array.
253     unsigned FirstEntryIsAnUnsizedArray : 1;
254 
255     /// Indicator of whether the most-derived object is an array element.
256     unsigned MostDerivedIsArrayElement : 1;
257 
258     /// The length of the path to the most-derived object of which this is a
259     /// subobject.
260     unsigned MostDerivedPathLength : 28;
261 
262     /// The size of the array of which the most-derived object is an element.
263     /// This will always be 0 if the most-derived object is not an array
264     /// element. 0 is not an indicator of whether or not the most-derived object
265     /// is an array, however, because 0-length arrays are allowed.
266     ///
267     /// If the current array is an unsized array, the value of this is
268     /// undefined.
269     uint64_t MostDerivedArraySize;
270 
271     /// The type of the most derived object referred to by this address.
272     QualType MostDerivedType;
273 
274     typedef APValue::LValuePathEntry PathEntry;
275 
276     /// The entries on the path from the glvalue to the designated subobject.
277     SmallVector<PathEntry, 8> Entries;
278 
279     SubobjectDesignator() : Invalid(true) {}
280 
281     explicit SubobjectDesignator(QualType T)
282         : Invalid(false), IsOnePastTheEnd(false),
283           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
284           MostDerivedPathLength(0), MostDerivedArraySize(0),
285           MostDerivedType(T) {}
286 
287     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
288         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
289           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
290           MostDerivedPathLength(0), MostDerivedArraySize(0) {
291       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
292       if (!Invalid) {
293         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
294         ArrayRef<PathEntry> VEntries = V.getLValuePath();
295         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
296         if (V.getLValueBase()) {
297           bool IsArray = false;
298           bool FirstIsUnsizedArray = false;
299           MostDerivedPathLength = findMostDerivedSubobject(
300               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
301               MostDerivedType, IsArray, FirstIsUnsizedArray);
302           MostDerivedIsArrayElement = IsArray;
303           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
304         }
305       }
306     }
307 
308     void truncate(ASTContext &Ctx, APValue::LValueBase Base,
309                   unsigned NewLength) {
310       if (Invalid)
311         return;
312 
313       assert(Base && "cannot truncate path for null pointer");
314       assert(NewLength <= Entries.size() && "not a truncation");
315 
316       if (NewLength == Entries.size())
317         return;
318       Entries.resize(NewLength);
319 
320       bool IsArray = false;
321       bool FirstIsUnsizedArray = false;
322       MostDerivedPathLength = findMostDerivedSubobject(
323           Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
324           FirstIsUnsizedArray);
325       MostDerivedIsArrayElement = IsArray;
326       FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
327     }
328 
329     void setInvalid() {
330       Invalid = true;
331       Entries.clear();
332     }
333 
334     /// Determine whether the most derived subobject is an array without a
335     /// known bound.
336     bool isMostDerivedAnUnsizedArray() const {
337       assert(!Invalid && "Calling this makes no sense on invalid designators");
338       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
339     }
340 
341     /// Determine what the most derived array's size is. Results in an assertion
342     /// failure if the most derived array lacks a size.
343     uint64_t getMostDerivedArraySize() const {
344       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
345       return MostDerivedArraySize;
346     }
347 
348     /// Determine whether this is a one-past-the-end pointer.
349     bool isOnePastTheEnd() const {
350       assert(!Invalid);
351       if (IsOnePastTheEnd)
352         return true;
353       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
354           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
355               MostDerivedArraySize)
356         return true;
357       return false;
358     }
359 
360     /// Get the range of valid index adjustments in the form
361     ///   {maximum value that can be subtracted from this pointer,
362     ///    maximum value that can be added to this pointer}
363     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
364       if (Invalid || isMostDerivedAnUnsizedArray())
365         return {0, 0};
366 
367       // [expr.add]p4: For the purposes of these operators, a pointer to a
368       // nonarray object behaves the same as a pointer to the first element of
369       // an array of length one with the type of the object as its element type.
370       bool IsArray = MostDerivedPathLength == Entries.size() &&
371                      MostDerivedIsArrayElement;
372       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
373                                     : (uint64_t)IsOnePastTheEnd;
374       uint64_t ArraySize =
375           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
376       return {ArrayIndex, ArraySize - ArrayIndex};
377     }
378 
379     /// Check that this refers to a valid subobject.
380     bool isValidSubobject() const {
381       if (Invalid)
382         return false;
383       return !isOnePastTheEnd();
384     }
385     /// Check that this refers to a valid subobject, and if not, produce a
386     /// relevant diagnostic and set the designator as invalid.
387     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
388 
389     /// Get the type of the designated object.
390     QualType getType(ASTContext &Ctx) const {
391       assert(!Invalid && "invalid designator has no subobject type");
392       return MostDerivedPathLength == Entries.size()
393                  ? MostDerivedType
394                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
395     }
396 
397     /// Update this designator to refer to the first element within this array.
398     void addArrayUnchecked(const ConstantArrayType *CAT) {
399       Entries.push_back(PathEntry::ArrayIndex(0));
400 
401       // This is a most-derived object.
402       MostDerivedType = CAT->getElementType();
403       MostDerivedIsArrayElement = true;
404       MostDerivedArraySize = CAT->getSize().getZExtValue();
405       MostDerivedPathLength = Entries.size();
406     }
407     /// Update this designator to refer to the first element within the array of
408     /// elements of type T. This is an array of unknown size.
409     void addUnsizedArrayUnchecked(QualType ElemTy) {
410       Entries.push_back(PathEntry::ArrayIndex(0));
411 
412       MostDerivedType = ElemTy;
413       MostDerivedIsArrayElement = true;
414       // The value in MostDerivedArraySize is undefined in this case. So, set it
415       // to an arbitrary value that's likely to loudly break things if it's
416       // used.
417       MostDerivedArraySize = AssumedSizeForUnsizedArray;
418       MostDerivedPathLength = Entries.size();
419     }
420     /// Update this designator to refer to the given base or member of this
421     /// object.
422     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
423       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
424 
425       // If this isn't a base class, it's a new most-derived object.
426       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
427         MostDerivedType = FD->getType();
428         MostDerivedIsArrayElement = false;
429         MostDerivedArraySize = 0;
430         MostDerivedPathLength = Entries.size();
431       }
432     }
433     /// Update this designator to refer to the given complex component.
434     void addComplexUnchecked(QualType EltTy, bool Imag) {
435       Entries.push_back(PathEntry::ArrayIndex(Imag));
436 
437       // This is technically a most-derived object, though in practice this
438       // is unlikely to matter.
439       MostDerivedType = EltTy;
440       MostDerivedIsArrayElement = true;
441       MostDerivedArraySize = 2;
442       MostDerivedPathLength = Entries.size();
443     }
444     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
445     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
446                                    const APSInt &N);
447     /// Add N to the address of this subobject.
448     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
449       if (Invalid || !N) return;
450       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
451       if (isMostDerivedAnUnsizedArray()) {
452         diagnoseUnsizedArrayPointerArithmetic(Info, E);
453         // Can't verify -- trust that the user is doing the right thing (or if
454         // not, trust that the caller will catch the bad behavior).
455         // FIXME: Should we reject if this overflows, at least?
456         Entries.back() = PathEntry::ArrayIndex(
457             Entries.back().getAsArrayIndex() + TruncatedN);
458         return;
459       }
460 
461       // [expr.add]p4: For the purposes of these operators, a pointer to a
462       // nonarray object behaves the same as a pointer to the first element of
463       // an array of length one with the type of the object as its element type.
464       bool IsArray = MostDerivedPathLength == Entries.size() &&
465                      MostDerivedIsArrayElement;
466       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
467                                     : (uint64_t)IsOnePastTheEnd;
468       uint64_t ArraySize =
469           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
470 
471       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
472         // Calculate the actual index in a wide enough type, so we can include
473         // it in the note.
474         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
475         (llvm::APInt&)N += ArrayIndex;
476         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
477         diagnosePointerArithmetic(Info, E, N);
478         setInvalid();
479         return;
480       }
481 
482       ArrayIndex += TruncatedN;
483       assert(ArrayIndex <= ArraySize &&
484              "bounds check succeeded for out-of-bounds index");
485 
486       if (IsArray)
487         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
488       else
489         IsOnePastTheEnd = (ArrayIndex != 0);
490     }
491   };
492 
493   /// A scope at the end of which an object can need to be destroyed.
494   enum class ScopeKind {
495     Block,
496     FullExpression,
497     Call
498   };
499 
500   /// A reference to a particular call and its arguments.
501   struct CallRef {
502     CallRef() : OrigCallee(), CallIndex(0), Version() {}
503     CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
504         : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
505 
506     explicit operator bool() const { return OrigCallee; }
507 
508     /// Get the parameter that the caller initialized, corresponding to the
509     /// given parameter in the callee.
510     const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
511       return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
512                         : PVD;
513     }
514 
515     /// The callee at the point where the arguments were evaluated. This might
516     /// be different from the actual callee (a different redeclaration, or a
517     /// virtual override), but this function's parameters are the ones that
518     /// appear in the parameter map.
519     const FunctionDecl *OrigCallee;
520     /// The call index of the frame that holds the argument values.
521     unsigned CallIndex;
522     /// The version of the parameters corresponding to this call.
523     unsigned Version;
524   };
525 
526   /// A stack frame in the constexpr call stack.
527   class CallStackFrame : public interp::Frame {
528   public:
529     EvalInfo &Info;
530 
531     /// Parent - The caller of this stack frame.
532     CallStackFrame *Caller;
533 
534     /// Callee - The function which was called.
535     const FunctionDecl *Callee;
536 
537     /// This - The binding for the this pointer in this call, if any.
538     const LValue *This;
539 
540     /// Information on how to find the arguments to this call. Our arguments
541     /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
542     /// key and this value as the version.
543     CallRef Arguments;
544 
545     /// Source location information about the default argument or default
546     /// initializer expression we're evaluating, if any.
547     CurrentSourceLocExprScope CurSourceLocExprScope;
548 
549     // Note that we intentionally use std::map here so that references to
550     // values are stable.
551     typedef std::pair<const void *, unsigned> MapKeyTy;
552     typedef std::map<MapKeyTy, APValue> MapTy;
553     /// Temporaries - Temporary lvalues materialized within this stack frame.
554     MapTy Temporaries;
555 
556     /// CallLoc - The location of the call expression for this call.
557     SourceLocation CallLoc;
558 
559     /// Index - The call index of this call.
560     unsigned Index;
561 
562     /// The stack of integers for tracking version numbers for temporaries.
563     SmallVector<unsigned, 2> TempVersionStack = {1};
564     unsigned CurTempVersion = TempVersionStack.back();
565 
566     unsigned getTempVersion() const { return TempVersionStack.back(); }
567 
568     void pushTempVersion() {
569       TempVersionStack.push_back(++CurTempVersion);
570     }
571 
572     void popTempVersion() {
573       TempVersionStack.pop_back();
574     }
575 
576     CallRef createCall(const FunctionDecl *Callee) {
577       return {Callee, Index, ++CurTempVersion};
578     }
579 
580     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
581     // on the overall stack usage of deeply-recursing constexpr evaluations.
582     // (We should cache this map rather than recomputing it repeatedly.)
583     // But let's try this and see how it goes; we can look into caching the map
584     // as a later change.
585 
586     /// LambdaCaptureFields - Mapping from captured variables/this to
587     /// corresponding data members in the closure class.
588     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
589     FieldDecl *LambdaThisCaptureField;
590 
591     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
592                    const FunctionDecl *Callee, const LValue *This,
593                    CallRef Arguments);
594     ~CallStackFrame();
595 
596     // Return the temporary for Key whose version number is Version.
597     APValue *getTemporary(const void *Key, unsigned Version) {
598       MapKeyTy KV(Key, Version);
599       auto LB = Temporaries.lower_bound(KV);
600       if (LB != Temporaries.end() && LB->first == KV)
601         return &LB->second;
602       // Pair (Key,Version) wasn't found in the map. Check that no elements
603       // in the map have 'Key' as their key.
604       assert((LB == Temporaries.end() || LB->first.first != Key) &&
605              (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
606              "Element with key 'Key' found in map");
607       return nullptr;
608     }
609 
610     // Return the current temporary for Key in the map.
611     APValue *getCurrentTemporary(const void *Key) {
612       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
613       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
614         return &std::prev(UB)->second;
615       return nullptr;
616     }
617 
618     // Return the version number of the current temporary for Key.
619     unsigned getCurrentTemporaryVersion(const void *Key) const {
620       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
621       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
622         return std::prev(UB)->first.second;
623       return 0;
624     }
625 
626     /// Allocate storage for an object of type T in this stack frame.
627     /// Populates LV with a handle to the created object. Key identifies
628     /// the temporary within the stack frame, and must not be reused without
629     /// bumping the temporary version number.
630     template<typename KeyT>
631     APValue &createTemporary(const KeyT *Key, QualType T,
632                              ScopeKind Scope, LValue &LV);
633 
634     /// Allocate storage for a parameter of a function call made in this frame.
635     APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
636 
637     void describe(llvm::raw_ostream &OS) override;
638 
639     Frame *getCaller() const override { return Caller; }
640     SourceLocation getCallLocation() const override { return CallLoc; }
641     const FunctionDecl *getCallee() const override { return Callee; }
642 
643     bool isStdFunction() const {
644       for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
645         if (DC->isStdNamespace())
646           return true;
647       return false;
648     }
649 
650   private:
651     APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
652                          ScopeKind Scope);
653   };
654 
655   /// Temporarily override 'this'.
656   class ThisOverrideRAII {
657   public:
658     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
659         : Frame(Frame), OldThis(Frame.This) {
660       if (Enable)
661         Frame.This = NewThis;
662     }
663     ~ThisOverrideRAII() {
664       Frame.This = OldThis;
665     }
666   private:
667     CallStackFrame &Frame;
668     const LValue *OldThis;
669   };
670 }
671 
672 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
673                               const LValue &This, QualType ThisType);
674 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
675                               APValue::LValueBase LVBase, APValue &Value,
676                               QualType T);
677 
678 namespace {
679   /// A cleanup, and a flag indicating whether it is lifetime-extended.
680   class Cleanup {
681     llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
682     APValue::LValueBase Base;
683     QualType T;
684 
685   public:
686     Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
687             ScopeKind Scope)
688         : Value(Val, Scope), Base(Base), T(T) {}
689 
690     /// Determine whether this cleanup should be performed at the end of the
691     /// given kind of scope.
692     bool isDestroyedAtEndOf(ScopeKind K) const {
693       return (int)Value.getInt() >= (int)K;
694     }
695     bool endLifetime(EvalInfo &Info, bool RunDestructors) {
696       if (RunDestructors) {
697         SourceLocation Loc;
698         if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
699           Loc = VD->getLocation();
700         else if (const Expr *E = Base.dyn_cast<const Expr*>())
701           Loc = E->getExprLoc();
702         return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
703       }
704       *Value.getPointer() = APValue();
705       return true;
706     }
707 
708     bool hasSideEffect() {
709       return T.isDestructedType();
710     }
711   };
712 
713   /// A reference to an object whose construction we are currently evaluating.
714   struct ObjectUnderConstruction {
715     APValue::LValueBase Base;
716     ArrayRef<APValue::LValuePathEntry> Path;
717     friend bool operator==(const ObjectUnderConstruction &LHS,
718                            const ObjectUnderConstruction &RHS) {
719       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
720     }
721     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
722       return llvm::hash_combine(Obj.Base, Obj.Path);
723     }
724   };
725   enum class ConstructionPhase {
726     None,
727     Bases,
728     AfterBases,
729     AfterFields,
730     Destroying,
731     DestroyingBases
732   };
733 }
734 
735 namespace llvm {
736 template<> struct DenseMapInfo<ObjectUnderConstruction> {
737   using Base = DenseMapInfo<APValue::LValueBase>;
738   static ObjectUnderConstruction getEmptyKey() {
739     return {Base::getEmptyKey(), {}}; }
740   static ObjectUnderConstruction getTombstoneKey() {
741     return {Base::getTombstoneKey(), {}};
742   }
743   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
744     return hash_value(Object);
745   }
746   static bool isEqual(const ObjectUnderConstruction &LHS,
747                       const ObjectUnderConstruction &RHS) {
748     return LHS == RHS;
749   }
750 };
751 }
752 
753 namespace {
754   /// A dynamically-allocated heap object.
755   struct DynAlloc {
756     /// The value of this heap-allocated object.
757     APValue Value;
758     /// The allocating expression; used for diagnostics. Either a CXXNewExpr
759     /// or a CallExpr (the latter is for direct calls to operator new inside
760     /// std::allocator<T>::allocate).
761     const Expr *AllocExpr = nullptr;
762 
763     enum Kind {
764       New,
765       ArrayNew,
766       StdAllocator
767     };
768 
769     /// Get the kind of the allocation. This must match between allocation
770     /// and deallocation.
771     Kind getKind() const {
772       if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
773         return NE->isArray() ? ArrayNew : New;
774       assert(isa<CallExpr>(AllocExpr));
775       return StdAllocator;
776     }
777   };
778 
779   struct DynAllocOrder {
780     bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
781       return L.getIndex() < R.getIndex();
782     }
783   };
784 
785   /// EvalInfo - This is a private struct used by the evaluator to capture
786   /// information about a subexpression as it is folded.  It retains information
787   /// about the AST context, but also maintains information about the folded
788   /// expression.
789   ///
790   /// If an expression could be evaluated, it is still possible it is not a C
791   /// "integer constant expression" or constant expression.  If not, this struct
792   /// captures information about how and why not.
793   ///
794   /// One bit of information passed *into* the request for constant folding
795   /// indicates whether the subexpression is "evaluated" or not according to C
796   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
797   /// evaluate the expression regardless of what the RHS is, but C only allows
798   /// certain things in certain situations.
799   class EvalInfo : public interp::State {
800   public:
801     ASTContext &Ctx;
802 
803     /// EvalStatus - Contains information about the evaluation.
804     Expr::EvalStatus &EvalStatus;
805 
806     /// CurrentCall - The top of the constexpr call stack.
807     CallStackFrame *CurrentCall;
808 
809     /// CallStackDepth - The number of calls in the call stack right now.
810     unsigned CallStackDepth;
811 
812     /// NextCallIndex - The next call index to assign.
813     unsigned NextCallIndex;
814 
815     /// StepsLeft - The remaining number of evaluation steps we're permitted
816     /// to perform. This is essentially a limit for the number of statements
817     /// we will evaluate.
818     unsigned StepsLeft;
819 
820     /// Enable the experimental new constant interpreter. If an expression is
821     /// not supported by the interpreter, an error is triggered.
822     bool EnableNewConstInterp;
823 
824     /// BottomFrame - The frame in which evaluation started. This must be
825     /// initialized after CurrentCall and CallStackDepth.
826     CallStackFrame BottomFrame;
827 
828     /// A stack of values whose lifetimes end at the end of some surrounding
829     /// evaluation frame.
830     llvm::SmallVector<Cleanup, 16> CleanupStack;
831 
832     /// EvaluatingDecl - This is the declaration whose initializer is being
833     /// evaluated, if any.
834     APValue::LValueBase EvaluatingDecl;
835 
836     enum class EvaluatingDeclKind {
837       None,
838       /// We're evaluating the construction of EvaluatingDecl.
839       Ctor,
840       /// We're evaluating the destruction of EvaluatingDecl.
841       Dtor,
842     };
843     EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
844 
845     /// EvaluatingDeclValue - This is the value being constructed for the
846     /// declaration whose initializer is being evaluated, if any.
847     APValue *EvaluatingDeclValue;
848 
849     /// Set of objects that are currently being constructed.
850     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
851         ObjectsUnderConstruction;
852 
853     /// Current heap allocations, along with the location where each was
854     /// allocated. We use std::map here because we need stable addresses
855     /// for the stored APValues.
856     std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
857 
858     /// The number of heap allocations performed so far in this evaluation.
859     unsigned NumHeapAllocs = 0;
860 
861     struct EvaluatingConstructorRAII {
862       EvalInfo &EI;
863       ObjectUnderConstruction Object;
864       bool DidInsert;
865       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
866                                 bool HasBases)
867           : EI(EI), Object(Object) {
868         DidInsert =
869             EI.ObjectsUnderConstruction
870                 .insert({Object, HasBases ? ConstructionPhase::Bases
871                                           : ConstructionPhase::AfterBases})
872                 .second;
873       }
874       void finishedConstructingBases() {
875         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
876       }
877       void finishedConstructingFields() {
878         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
879       }
880       ~EvaluatingConstructorRAII() {
881         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
882       }
883     };
884 
885     struct EvaluatingDestructorRAII {
886       EvalInfo &EI;
887       ObjectUnderConstruction Object;
888       bool DidInsert;
889       EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
890           : EI(EI), Object(Object) {
891         DidInsert = EI.ObjectsUnderConstruction
892                         .insert({Object, ConstructionPhase::Destroying})
893                         .second;
894       }
895       void startedDestroyingBases() {
896         EI.ObjectsUnderConstruction[Object] =
897             ConstructionPhase::DestroyingBases;
898       }
899       ~EvaluatingDestructorRAII() {
900         if (DidInsert)
901           EI.ObjectsUnderConstruction.erase(Object);
902       }
903     };
904 
905     ConstructionPhase
906     isEvaluatingCtorDtor(APValue::LValueBase Base,
907                          ArrayRef<APValue::LValuePathEntry> Path) {
908       return ObjectsUnderConstruction.lookup({Base, Path});
909     }
910 
911     /// If we're currently speculatively evaluating, the outermost call stack
912     /// depth at which we can mutate state, otherwise 0.
913     unsigned SpeculativeEvaluationDepth = 0;
914 
915     /// The current array initialization index, if we're performing array
916     /// initialization.
917     uint64_t ArrayInitIndex = -1;
918 
919     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
920     /// notes attached to it will also be stored, otherwise they will not be.
921     bool HasActiveDiagnostic;
922 
923     /// Have we emitted a diagnostic explaining why we couldn't constant
924     /// fold (not just why it's not strictly a constant expression)?
925     bool HasFoldFailureDiagnostic;
926 
927     /// Whether or not we're in a context where the front end requires a
928     /// constant value.
929     bool InConstantContext;
930 
931     /// Whether we're checking that an expression is a potential constant
932     /// expression. If so, do not fail on constructs that could become constant
933     /// later on (such as a use of an undefined global).
934     bool CheckingPotentialConstantExpression = false;
935 
936     /// Whether we're checking for an expression that has undefined behavior.
937     /// If so, we will produce warnings if we encounter an operation that is
938     /// always undefined.
939     bool CheckingForUndefinedBehavior = false;
940 
941     enum EvaluationMode {
942       /// Evaluate as a constant expression. Stop if we find that the expression
943       /// is not a constant expression.
944       EM_ConstantExpression,
945 
946       /// Evaluate as a constant expression. Stop if we find that the expression
947       /// is not a constant expression. Some expressions can be retried in the
948       /// optimizer if we don't constant fold them here, but in an unevaluated
949       /// context we try to fold them immediately since the optimizer never
950       /// gets a chance to look at it.
951       EM_ConstantExpressionUnevaluated,
952 
953       /// Fold the expression to a constant. Stop if we hit a side-effect that
954       /// we can't model.
955       EM_ConstantFold,
956 
957       /// Evaluate in any way we know how. Don't worry about side-effects that
958       /// can't be modeled.
959       EM_IgnoreSideEffects,
960     } EvalMode;
961 
962     /// Are we checking whether the expression is a potential constant
963     /// expression?
964     bool checkingPotentialConstantExpression() const override  {
965       return CheckingPotentialConstantExpression;
966     }
967 
968     /// Are we checking an expression for overflow?
969     // FIXME: We should check for any kind of undefined or suspicious behavior
970     // in such constructs, not just overflow.
971     bool checkingForUndefinedBehavior() const override {
972       return CheckingForUndefinedBehavior;
973     }
974 
975     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
976         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
977           CallStackDepth(0), NextCallIndex(1),
978           StepsLeft(C.getLangOpts().ConstexprStepLimit),
979           EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
980           BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()),
981           EvaluatingDecl((const ValueDecl *)nullptr),
982           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
983           HasFoldFailureDiagnostic(false), InConstantContext(false),
984           EvalMode(Mode) {}
985 
986     ~EvalInfo() {
987       discardCleanups();
988     }
989 
990     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
991                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
992       EvaluatingDecl = Base;
993       IsEvaluatingDecl = EDK;
994       EvaluatingDeclValue = &Value;
995     }
996 
997     bool CheckCallLimit(SourceLocation Loc) {
998       // Don't perform any constexpr calls (other than the call we're checking)
999       // when checking a potential constant expression.
1000       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
1001         return false;
1002       if (NextCallIndex == 0) {
1003         // NextCallIndex has wrapped around.
1004         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1005         return false;
1006       }
1007       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1008         return true;
1009       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1010         << getLangOpts().ConstexprCallDepth;
1011       return false;
1012     }
1013 
1014     std::pair<CallStackFrame *, unsigned>
1015     getCallFrameAndDepth(unsigned CallIndex) {
1016       assert(CallIndex && "no call index in getCallFrameAndDepth");
1017       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1018       // be null in this loop.
1019       unsigned Depth = CallStackDepth;
1020       CallStackFrame *Frame = CurrentCall;
1021       while (Frame->Index > CallIndex) {
1022         Frame = Frame->Caller;
1023         --Depth;
1024       }
1025       if (Frame->Index == CallIndex)
1026         return {Frame, Depth};
1027       return {nullptr, 0};
1028     }
1029 
1030     bool nextStep(const Stmt *S) {
1031       if (!StepsLeft) {
1032         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1033         return false;
1034       }
1035       --StepsLeft;
1036       return true;
1037     }
1038 
1039     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1040 
1041     Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
1042       Optional<DynAlloc*> Result;
1043       auto It = HeapAllocs.find(DA);
1044       if (It != HeapAllocs.end())
1045         Result = &It->second;
1046       return Result;
1047     }
1048 
1049     /// Get the allocated storage for the given parameter of the given call.
1050     APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1051       CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1052       return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1053                    : nullptr;
1054     }
1055 
1056     /// Information about a stack frame for std::allocator<T>::[de]allocate.
1057     struct StdAllocatorCaller {
1058       unsigned FrameIndex;
1059       QualType ElemType;
1060       explicit operator bool() const { return FrameIndex != 0; };
1061     };
1062 
1063     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1064       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1065            Call = Call->Caller) {
1066         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1067         if (!MD)
1068           continue;
1069         const IdentifierInfo *FnII = MD->getIdentifier();
1070         if (!FnII || !FnII->isStr(FnName))
1071           continue;
1072 
1073         const auto *CTSD =
1074             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1075         if (!CTSD)
1076           continue;
1077 
1078         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1079         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1080         if (CTSD->isInStdNamespace() && ClassII &&
1081             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1082             TAL[0].getKind() == TemplateArgument::Type)
1083           return {Call->Index, TAL[0].getAsType()};
1084       }
1085 
1086       return {};
1087     }
1088 
1089     void performLifetimeExtension() {
1090       // Disable the cleanups for lifetime-extended temporaries.
1091       CleanupStack.erase(std::remove_if(CleanupStack.begin(),
1092                                         CleanupStack.end(),
1093                                         [](Cleanup &C) {
1094                                           return !C.isDestroyedAtEndOf(
1095                                               ScopeKind::FullExpression);
1096                                         }),
1097                          CleanupStack.end());
1098      }
1099 
1100     /// Throw away any remaining cleanups at the end of evaluation. If any
1101     /// cleanups would have had a side-effect, note that as an unmodeled
1102     /// side-effect and return false. Otherwise, return true.
1103     bool discardCleanups() {
1104       for (Cleanup &C : CleanupStack) {
1105         if (C.hasSideEffect() && !noteSideEffect()) {
1106           CleanupStack.clear();
1107           return false;
1108         }
1109       }
1110       CleanupStack.clear();
1111       return true;
1112     }
1113 
1114   private:
1115     interp::Frame *getCurrentFrame() override { return CurrentCall; }
1116     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1117 
1118     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1119     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1120 
1121     void setFoldFailureDiagnostic(bool Flag) override {
1122       HasFoldFailureDiagnostic = Flag;
1123     }
1124 
1125     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1126 
1127     ASTContext &getCtx() const override { return Ctx; }
1128 
1129     // If we have a prior diagnostic, it will be noting that the expression
1130     // isn't a constant expression. This diagnostic is more important,
1131     // unless we require this evaluation to produce a constant expression.
1132     //
1133     // FIXME: We might want to show both diagnostics to the user in
1134     // EM_ConstantFold mode.
1135     bool hasPriorDiagnostic() override {
1136       if (!EvalStatus.Diag->empty()) {
1137         switch (EvalMode) {
1138         case EM_ConstantFold:
1139         case EM_IgnoreSideEffects:
1140           if (!HasFoldFailureDiagnostic)
1141             break;
1142           // We've already failed to fold something. Keep that diagnostic.
1143           LLVM_FALLTHROUGH;
1144         case EM_ConstantExpression:
1145         case EM_ConstantExpressionUnevaluated:
1146           setActiveDiagnostic(false);
1147           return true;
1148         }
1149       }
1150       return false;
1151     }
1152 
1153     unsigned getCallStackDepth() override { return CallStackDepth; }
1154 
1155   public:
1156     /// Should we continue evaluation after encountering a side-effect that we
1157     /// couldn't model?
1158     bool keepEvaluatingAfterSideEffect() {
1159       switch (EvalMode) {
1160       case EM_IgnoreSideEffects:
1161         return true;
1162 
1163       case EM_ConstantExpression:
1164       case EM_ConstantExpressionUnevaluated:
1165       case EM_ConstantFold:
1166         // By default, assume any side effect might be valid in some other
1167         // evaluation of this expression from a different context.
1168         return checkingPotentialConstantExpression() ||
1169                checkingForUndefinedBehavior();
1170       }
1171       llvm_unreachable("Missed EvalMode case");
1172     }
1173 
1174     /// Note that we have had a side-effect, and determine whether we should
1175     /// keep evaluating.
1176     bool noteSideEffect() {
1177       EvalStatus.HasSideEffects = true;
1178       return keepEvaluatingAfterSideEffect();
1179     }
1180 
1181     /// Should we continue evaluation after encountering undefined behavior?
1182     bool keepEvaluatingAfterUndefinedBehavior() {
1183       switch (EvalMode) {
1184       case EM_IgnoreSideEffects:
1185       case EM_ConstantFold:
1186         return true;
1187 
1188       case EM_ConstantExpression:
1189       case EM_ConstantExpressionUnevaluated:
1190         return checkingForUndefinedBehavior();
1191       }
1192       llvm_unreachable("Missed EvalMode case");
1193     }
1194 
1195     /// Note that we hit something that was technically undefined behavior, but
1196     /// that we can evaluate past it (such as signed overflow or floating-point
1197     /// division by zero.)
1198     bool noteUndefinedBehavior() override {
1199       EvalStatus.HasUndefinedBehavior = true;
1200       return keepEvaluatingAfterUndefinedBehavior();
1201     }
1202 
1203     /// Should we continue evaluation as much as possible after encountering a
1204     /// construct which can't be reduced to a value?
1205     bool keepEvaluatingAfterFailure() const override {
1206       if (!StepsLeft)
1207         return false;
1208 
1209       switch (EvalMode) {
1210       case EM_ConstantExpression:
1211       case EM_ConstantExpressionUnevaluated:
1212       case EM_ConstantFold:
1213       case EM_IgnoreSideEffects:
1214         return checkingPotentialConstantExpression() ||
1215                checkingForUndefinedBehavior();
1216       }
1217       llvm_unreachable("Missed EvalMode case");
1218     }
1219 
1220     /// Notes that we failed to evaluate an expression that other expressions
1221     /// directly depend on, and determine if we should keep evaluating. This
1222     /// should only be called if we actually intend to keep evaluating.
1223     ///
1224     /// Call noteSideEffect() instead if we may be able to ignore the value that
1225     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1226     ///
1227     /// (Foo(), 1)      // use noteSideEffect
1228     /// (Foo() || true) // use noteSideEffect
1229     /// Foo() + 1       // use noteFailure
1230     LLVM_NODISCARD bool noteFailure() {
1231       // Failure when evaluating some expression often means there is some
1232       // subexpression whose evaluation was skipped. Therefore, (because we
1233       // don't track whether we skipped an expression when unwinding after an
1234       // evaluation failure) every evaluation failure that bubbles up from a
1235       // subexpression implies that a side-effect has potentially happened. We
1236       // skip setting the HasSideEffects flag to true until we decide to
1237       // continue evaluating after that point, which happens here.
1238       bool KeepGoing = keepEvaluatingAfterFailure();
1239       EvalStatus.HasSideEffects |= KeepGoing;
1240       return KeepGoing;
1241     }
1242 
1243     class ArrayInitLoopIndex {
1244       EvalInfo &Info;
1245       uint64_t OuterIndex;
1246 
1247     public:
1248       ArrayInitLoopIndex(EvalInfo &Info)
1249           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1250         Info.ArrayInitIndex = 0;
1251       }
1252       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1253 
1254       operator uint64_t&() { return Info.ArrayInitIndex; }
1255     };
1256   };
1257 
1258   /// Object used to treat all foldable expressions as constant expressions.
1259   struct FoldConstant {
1260     EvalInfo &Info;
1261     bool Enabled;
1262     bool HadNoPriorDiags;
1263     EvalInfo::EvaluationMode OldMode;
1264 
1265     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1266       : Info(Info),
1267         Enabled(Enabled),
1268         HadNoPriorDiags(Info.EvalStatus.Diag &&
1269                         Info.EvalStatus.Diag->empty() &&
1270                         !Info.EvalStatus.HasSideEffects),
1271         OldMode(Info.EvalMode) {
1272       if (Enabled)
1273         Info.EvalMode = EvalInfo::EM_ConstantFold;
1274     }
1275     void keepDiagnostics() { Enabled = false; }
1276     ~FoldConstant() {
1277       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1278           !Info.EvalStatus.HasSideEffects)
1279         Info.EvalStatus.Diag->clear();
1280       Info.EvalMode = OldMode;
1281     }
1282   };
1283 
1284   /// RAII object used to set the current evaluation mode to ignore
1285   /// side-effects.
1286   struct IgnoreSideEffectsRAII {
1287     EvalInfo &Info;
1288     EvalInfo::EvaluationMode OldMode;
1289     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1290         : Info(Info), OldMode(Info.EvalMode) {
1291       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1292     }
1293 
1294     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1295   };
1296 
1297   /// RAII object used to optionally suppress diagnostics and side-effects from
1298   /// a speculative evaluation.
1299   class SpeculativeEvaluationRAII {
1300     EvalInfo *Info = nullptr;
1301     Expr::EvalStatus OldStatus;
1302     unsigned OldSpeculativeEvaluationDepth;
1303 
1304     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1305       Info = Other.Info;
1306       OldStatus = Other.OldStatus;
1307       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1308       Other.Info = nullptr;
1309     }
1310 
1311     void maybeRestoreState() {
1312       if (!Info)
1313         return;
1314 
1315       Info->EvalStatus = OldStatus;
1316       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1317     }
1318 
1319   public:
1320     SpeculativeEvaluationRAII() = default;
1321 
1322     SpeculativeEvaluationRAII(
1323         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1324         : Info(&Info), OldStatus(Info.EvalStatus),
1325           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1326       Info.EvalStatus.Diag = NewDiag;
1327       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1328     }
1329 
1330     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1331     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1332       moveFromAndCancel(std::move(Other));
1333     }
1334 
1335     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1336       maybeRestoreState();
1337       moveFromAndCancel(std::move(Other));
1338       return *this;
1339     }
1340 
1341     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1342   };
1343 
1344   /// RAII object wrapping a full-expression or block scope, and handling
1345   /// the ending of the lifetime of temporaries created within it.
1346   template<ScopeKind Kind>
1347   class ScopeRAII {
1348     EvalInfo &Info;
1349     unsigned OldStackSize;
1350   public:
1351     ScopeRAII(EvalInfo &Info)
1352         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1353       // Push a new temporary version. This is needed to distinguish between
1354       // temporaries created in different iterations of a loop.
1355       Info.CurrentCall->pushTempVersion();
1356     }
1357     bool destroy(bool RunDestructors = true) {
1358       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1359       OldStackSize = -1U;
1360       return OK;
1361     }
1362     ~ScopeRAII() {
1363       if (OldStackSize != -1U)
1364         destroy(false);
1365       // Body moved to a static method to encourage the compiler to inline away
1366       // instances of this class.
1367       Info.CurrentCall->popTempVersion();
1368     }
1369   private:
1370     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1371                         unsigned OldStackSize) {
1372       assert(OldStackSize <= Info.CleanupStack.size() &&
1373              "running cleanups out of order?");
1374 
1375       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1376       // for a full-expression scope.
1377       bool Success = true;
1378       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1379         if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1380           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1381             Success = false;
1382             break;
1383           }
1384         }
1385       }
1386 
1387       // Compact any retained cleanups.
1388       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1389       if (Kind != ScopeKind::Block)
1390         NewEnd =
1391             std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1392               return C.isDestroyedAtEndOf(Kind);
1393             });
1394       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1395       return Success;
1396     }
1397   };
1398   typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1399   typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1400   typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1401 }
1402 
1403 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1404                                          CheckSubobjectKind CSK) {
1405   if (Invalid)
1406     return false;
1407   if (isOnePastTheEnd()) {
1408     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1409       << CSK;
1410     setInvalid();
1411     return false;
1412   }
1413   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1414   // must actually be at least one array element; even a VLA cannot have a
1415   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1416   return true;
1417 }
1418 
1419 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1420                                                                 const Expr *E) {
1421   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1422   // Do not set the designator as invalid: we can represent this situation,
1423   // and correct handling of __builtin_object_size requires us to do so.
1424 }
1425 
1426 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1427                                                     const Expr *E,
1428                                                     const APSInt &N) {
1429   // If we're complaining, we must be able to statically determine the size of
1430   // the most derived array.
1431   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1432     Info.CCEDiag(E, diag::note_constexpr_array_index)
1433       << N << /*array*/ 0
1434       << static_cast<unsigned>(getMostDerivedArraySize());
1435   else
1436     Info.CCEDiag(E, diag::note_constexpr_array_index)
1437       << N << /*non-array*/ 1;
1438   setInvalid();
1439 }
1440 
1441 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1442                                const FunctionDecl *Callee, const LValue *This,
1443                                CallRef Call)
1444     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1445       Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1446   Info.CurrentCall = this;
1447   ++Info.CallStackDepth;
1448 }
1449 
1450 CallStackFrame::~CallStackFrame() {
1451   assert(Info.CurrentCall == this && "calls retired out of order");
1452   --Info.CallStackDepth;
1453   Info.CurrentCall = Caller;
1454 }
1455 
1456 static bool isRead(AccessKinds AK) {
1457   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1458 }
1459 
1460 static bool isModification(AccessKinds AK) {
1461   switch (AK) {
1462   case AK_Read:
1463   case AK_ReadObjectRepresentation:
1464   case AK_MemberCall:
1465   case AK_DynamicCast:
1466   case AK_TypeId:
1467     return false;
1468   case AK_Assign:
1469   case AK_Increment:
1470   case AK_Decrement:
1471   case AK_Construct:
1472   case AK_Destroy:
1473     return true;
1474   }
1475   llvm_unreachable("unknown access kind");
1476 }
1477 
1478 static bool isAnyAccess(AccessKinds AK) {
1479   return isRead(AK) || isModification(AK);
1480 }
1481 
1482 /// Is this an access per the C++ definition?
1483 static bool isFormalAccess(AccessKinds AK) {
1484   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1485 }
1486 
1487 /// Is this kind of axcess valid on an indeterminate object value?
1488 static bool isValidIndeterminateAccess(AccessKinds AK) {
1489   switch (AK) {
1490   case AK_Read:
1491   case AK_Increment:
1492   case AK_Decrement:
1493     // These need the object's value.
1494     return false;
1495 
1496   case AK_ReadObjectRepresentation:
1497   case AK_Assign:
1498   case AK_Construct:
1499   case AK_Destroy:
1500     // Construction and destruction don't need the value.
1501     return true;
1502 
1503   case AK_MemberCall:
1504   case AK_DynamicCast:
1505   case AK_TypeId:
1506     // These aren't really meaningful on scalars.
1507     return true;
1508   }
1509   llvm_unreachable("unknown access kind");
1510 }
1511 
1512 namespace {
1513   struct ComplexValue {
1514   private:
1515     bool IsInt;
1516 
1517   public:
1518     APSInt IntReal, IntImag;
1519     APFloat FloatReal, FloatImag;
1520 
1521     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1522 
1523     void makeComplexFloat() { IsInt = false; }
1524     bool isComplexFloat() const { return !IsInt; }
1525     APFloat &getComplexFloatReal() { return FloatReal; }
1526     APFloat &getComplexFloatImag() { return FloatImag; }
1527 
1528     void makeComplexInt() { IsInt = true; }
1529     bool isComplexInt() const { return IsInt; }
1530     APSInt &getComplexIntReal() { return IntReal; }
1531     APSInt &getComplexIntImag() { return IntImag; }
1532 
1533     void moveInto(APValue &v) const {
1534       if (isComplexFloat())
1535         v = APValue(FloatReal, FloatImag);
1536       else
1537         v = APValue(IntReal, IntImag);
1538     }
1539     void setFrom(const APValue &v) {
1540       assert(v.isComplexFloat() || v.isComplexInt());
1541       if (v.isComplexFloat()) {
1542         makeComplexFloat();
1543         FloatReal = v.getComplexFloatReal();
1544         FloatImag = v.getComplexFloatImag();
1545       } else {
1546         makeComplexInt();
1547         IntReal = v.getComplexIntReal();
1548         IntImag = v.getComplexIntImag();
1549       }
1550     }
1551   };
1552 
1553   struct LValue {
1554     APValue::LValueBase Base;
1555     CharUnits Offset;
1556     SubobjectDesignator Designator;
1557     bool IsNullPtr : 1;
1558     bool InvalidBase : 1;
1559 
1560     const APValue::LValueBase getLValueBase() const { return Base; }
1561     CharUnits &getLValueOffset() { return Offset; }
1562     const CharUnits &getLValueOffset() const { return Offset; }
1563     SubobjectDesignator &getLValueDesignator() { return Designator; }
1564     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1565     bool isNullPointer() const { return IsNullPtr;}
1566 
1567     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1568     unsigned getLValueVersion() const { return Base.getVersion(); }
1569 
1570     void moveInto(APValue &V) const {
1571       if (Designator.Invalid)
1572         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1573       else {
1574         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1575         V = APValue(Base, Offset, Designator.Entries,
1576                     Designator.IsOnePastTheEnd, IsNullPtr);
1577       }
1578     }
1579     void setFrom(ASTContext &Ctx, const APValue &V) {
1580       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1581       Base = V.getLValueBase();
1582       Offset = V.getLValueOffset();
1583       InvalidBase = false;
1584       Designator = SubobjectDesignator(Ctx, V);
1585       IsNullPtr = V.isNullPointer();
1586     }
1587 
1588     void set(APValue::LValueBase B, bool BInvalid = false) {
1589 #ifndef NDEBUG
1590       // We only allow a few types of invalid bases. Enforce that here.
1591       if (BInvalid) {
1592         const auto *E = B.get<const Expr *>();
1593         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1594                "Unexpected type of invalid base");
1595       }
1596 #endif
1597 
1598       Base = B;
1599       Offset = CharUnits::fromQuantity(0);
1600       InvalidBase = BInvalid;
1601       Designator = SubobjectDesignator(getType(B));
1602       IsNullPtr = false;
1603     }
1604 
1605     void setNull(ASTContext &Ctx, QualType PointerTy) {
1606       Base = (Expr *)nullptr;
1607       Offset =
1608           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1609       InvalidBase = false;
1610       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1611       IsNullPtr = true;
1612     }
1613 
1614     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1615       set(B, true);
1616     }
1617 
1618     std::string toString(ASTContext &Ctx, QualType T) const {
1619       APValue Printable;
1620       moveInto(Printable);
1621       return Printable.getAsString(Ctx, T);
1622     }
1623 
1624   private:
1625     // Check that this LValue is not based on a null pointer. If it is, produce
1626     // a diagnostic and mark the designator as invalid.
1627     template <typename GenDiagType>
1628     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1629       if (Designator.Invalid)
1630         return false;
1631       if (IsNullPtr) {
1632         GenDiag();
1633         Designator.setInvalid();
1634         return false;
1635       }
1636       return true;
1637     }
1638 
1639   public:
1640     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1641                           CheckSubobjectKind CSK) {
1642       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1643         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1644       });
1645     }
1646 
1647     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1648                                        AccessKinds AK) {
1649       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1650         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1651       });
1652     }
1653 
1654     // Check this LValue refers to an object. If not, set the designator to be
1655     // invalid and emit a diagnostic.
1656     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1657       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1658              Designator.checkSubobject(Info, E, CSK);
1659     }
1660 
1661     void addDecl(EvalInfo &Info, const Expr *E,
1662                  const Decl *D, bool Virtual = false) {
1663       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1664         Designator.addDeclUnchecked(D, Virtual);
1665     }
1666     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1667       if (!Designator.Entries.empty()) {
1668         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1669         Designator.setInvalid();
1670         return;
1671       }
1672       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1673         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1674         Designator.FirstEntryIsAnUnsizedArray = true;
1675         Designator.addUnsizedArrayUnchecked(ElemTy);
1676       }
1677     }
1678     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1679       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1680         Designator.addArrayUnchecked(CAT);
1681     }
1682     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1683       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1684         Designator.addComplexUnchecked(EltTy, Imag);
1685     }
1686     void clearIsNullPointer() {
1687       IsNullPtr = false;
1688     }
1689     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1690                               const APSInt &Index, CharUnits ElementSize) {
1691       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1692       // but we're not required to diagnose it and it's valid in C++.)
1693       if (!Index)
1694         return;
1695 
1696       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1697       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1698       // offsets.
1699       uint64_t Offset64 = Offset.getQuantity();
1700       uint64_t ElemSize64 = ElementSize.getQuantity();
1701       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1702       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1703 
1704       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1705         Designator.adjustIndex(Info, E, Index);
1706       clearIsNullPointer();
1707     }
1708     void adjustOffset(CharUnits N) {
1709       Offset += N;
1710       if (N.getQuantity())
1711         clearIsNullPointer();
1712     }
1713   };
1714 
1715   struct MemberPtr {
1716     MemberPtr() {}
1717     explicit MemberPtr(const ValueDecl *Decl) :
1718       DeclAndIsDerivedMember(Decl, false), Path() {}
1719 
1720     /// The member or (direct or indirect) field referred to by this member
1721     /// pointer, or 0 if this is a null member pointer.
1722     const ValueDecl *getDecl() const {
1723       return DeclAndIsDerivedMember.getPointer();
1724     }
1725     /// Is this actually a member of some type derived from the relevant class?
1726     bool isDerivedMember() const {
1727       return DeclAndIsDerivedMember.getInt();
1728     }
1729     /// Get the class which the declaration actually lives in.
1730     const CXXRecordDecl *getContainingRecord() const {
1731       return cast<CXXRecordDecl>(
1732           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1733     }
1734 
1735     void moveInto(APValue &V) const {
1736       V = APValue(getDecl(), isDerivedMember(), Path);
1737     }
1738     void setFrom(const APValue &V) {
1739       assert(V.isMemberPointer());
1740       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1741       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1742       Path.clear();
1743       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1744       Path.insert(Path.end(), P.begin(), P.end());
1745     }
1746 
1747     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1748     /// whether the member is a member of some class derived from the class type
1749     /// of the member pointer.
1750     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1751     /// Path - The path of base/derived classes from the member declaration's
1752     /// class (exclusive) to the class type of the member pointer (inclusive).
1753     SmallVector<const CXXRecordDecl*, 4> Path;
1754 
1755     /// Perform a cast towards the class of the Decl (either up or down the
1756     /// hierarchy).
1757     bool castBack(const CXXRecordDecl *Class) {
1758       assert(!Path.empty());
1759       const CXXRecordDecl *Expected;
1760       if (Path.size() >= 2)
1761         Expected = Path[Path.size() - 2];
1762       else
1763         Expected = getContainingRecord();
1764       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1765         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1766         // if B does not contain the original member and is not a base or
1767         // derived class of the class containing the original member, the result
1768         // of the cast is undefined.
1769         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1770         // (D::*). We consider that to be a language defect.
1771         return false;
1772       }
1773       Path.pop_back();
1774       return true;
1775     }
1776     /// Perform a base-to-derived member pointer cast.
1777     bool castToDerived(const CXXRecordDecl *Derived) {
1778       if (!getDecl())
1779         return true;
1780       if (!isDerivedMember()) {
1781         Path.push_back(Derived);
1782         return true;
1783       }
1784       if (!castBack(Derived))
1785         return false;
1786       if (Path.empty())
1787         DeclAndIsDerivedMember.setInt(false);
1788       return true;
1789     }
1790     /// Perform a derived-to-base member pointer cast.
1791     bool castToBase(const CXXRecordDecl *Base) {
1792       if (!getDecl())
1793         return true;
1794       if (Path.empty())
1795         DeclAndIsDerivedMember.setInt(true);
1796       if (isDerivedMember()) {
1797         Path.push_back(Base);
1798         return true;
1799       }
1800       return castBack(Base);
1801     }
1802   };
1803 
1804   /// Compare two member pointers, which are assumed to be of the same type.
1805   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1806     if (!LHS.getDecl() || !RHS.getDecl())
1807       return !LHS.getDecl() && !RHS.getDecl();
1808     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1809       return false;
1810     return LHS.Path == RHS.Path;
1811   }
1812 }
1813 
1814 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1815 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1816                             const LValue &This, const Expr *E,
1817                             bool AllowNonLiteralTypes = false);
1818 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1819                            bool InvalidBaseOK = false);
1820 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1821                             bool InvalidBaseOK = false);
1822 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1823                                   EvalInfo &Info);
1824 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1825 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1826 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1827                                     EvalInfo &Info);
1828 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1829 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1830 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1831                            EvalInfo &Info);
1832 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1833 
1834 /// Evaluate an integer or fixed point expression into an APResult.
1835 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1836                                         EvalInfo &Info);
1837 
1838 /// Evaluate only a fixed point expression into an APResult.
1839 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1840                                EvalInfo &Info);
1841 
1842 //===----------------------------------------------------------------------===//
1843 // Misc utilities
1844 //===----------------------------------------------------------------------===//
1845 
1846 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1847 /// preserving its value (by extending by up to one bit as needed).
1848 static void negateAsSigned(APSInt &Int) {
1849   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1850     Int = Int.extend(Int.getBitWidth() + 1);
1851     Int.setIsSigned(true);
1852   }
1853   Int = -Int;
1854 }
1855 
1856 template<typename KeyT>
1857 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1858                                          ScopeKind Scope, LValue &LV) {
1859   unsigned Version = getTempVersion();
1860   APValue::LValueBase Base(Key, Index, Version);
1861   LV.set(Base);
1862   return createLocal(Base, Key, T, Scope);
1863 }
1864 
1865 /// Allocate storage for a parameter of a function call made in this frame.
1866 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1867                                      LValue &LV) {
1868   assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1869   APValue::LValueBase Base(PVD, Index, Args.Version);
1870   LV.set(Base);
1871   // We always destroy parameters at the end of the call, even if we'd allow
1872   // them to live to the end of the full-expression at runtime, in order to
1873   // give portable results and match other compilers.
1874   return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1875 }
1876 
1877 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1878                                      QualType T, ScopeKind Scope) {
1879   assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1880   unsigned Version = Base.getVersion();
1881   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1882   assert(Result.isAbsent() && "local created multiple times");
1883 
1884   // If we're creating a local immediately in the operand of a speculative
1885   // evaluation, don't register a cleanup to be run outside the speculative
1886   // evaluation context, since we won't actually be able to initialize this
1887   // object.
1888   if (Index <= Info.SpeculativeEvaluationDepth) {
1889     if (T.isDestructedType())
1890       Info.noteSideEffect();
1891   } else {
1892     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1893   }
1894   return Result;
1895 }
1896 
1897 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1898   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1899     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1900     return nullptr;
1901   }
1902 
1903   DynamicAllocLValue DA(NumHeapAllocs++);
1904   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1905   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1906                                    std::forward_as_tuple(DA), std::tuple<>());
1907   assert(Result.second && "reused a heap alloc index?");
1908   Result.first->second.AllocExpr = E;
1909   return &Result.first->second.Value;
1910 }
1911 
1912 /// Produce a string describing the given constexpr call.
1913 void CallStackFrame::describe(raw_ostream &Out) {
1914   unsigned ArgIndex = 0;
1915   bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1916                       !isa<CXXConstructorDecl>(Callee) &&
1917                       cast<CXXMethodDecl>(Callee)->isInstance();
1918 
1919   if (!IsMemberCall)
1920     Out << *Callee << '(';
1921 
1922   if (This && IsMemberCall) {
1923     APValue Val;
1924     This->moveInto(Val);
1925     Val.printPretty(Out, Info.Ctx,
1926                     This->Designator.MostDerivedType);
1927     // FIXME: Add parens around Val if needed.
1928     Out << "->" << *Callee << '(';
1929     IsMemberCall = false;
1930   }
1931 
1932   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1933        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1934     if (ArgIndex > (unsigned)IsMemberCall)
1935       Out << ", ";
1936 
1937     const ParmVarDecl *Param = *I;
1938     APValue *V = Info.getParamSlot(Arguments, Param);
1939     if (V)
1940       V->printPretty(Out, Info.Ctx, Param->getType());
1941     else
1942       Out << "<...>";
1943 
1944     if (ArgIndex == 0 && IsMemberCall)
1945       Out << "->" << *Callee << '(';
1946   }
1947 
1948   Out << ')';
1949 }
1950 
1951 /// Evaluate an expression to see if it had side-effects, and discard its
1952 /// result.
1953 /// \return \c true if the caller should keep evaluating.
1954 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1955   APValue Scratch;
1956   if (!Evaluate(Scratch, Info, E))
1957     // We don't need the value, but we might have skipped a side effect here.
1958     return Info.noteSideEffect();
1959   return true;
1960 }
1961 
1962 /// Should this call expression be treated as a string literal?
1963 static bool IsStringLiteralCall(const CallExpr *E) {
1964   unsigned Builtin = E->getBuiltinCallee();
1965   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1966           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1967 }
1968 
1969 static bool IsGlobalLValue(APValue::LValueBase B) {
1970   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1971   // constant expression of pointer type that evaluates to...
1972 
1973   // ... a null pointer value, or a prvalue core constant expression of type
1974   // std::nullptr_t.
1975   if (!B) return true;
1976 
1977   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1978     // ... the address of an object with static storage duration,
1979     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1980       return VD->hasGlobalStorage();
1981     // ... the address of a function,
1982     // ... the address of a GUID [MS extension],
1983     return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D);
1984   }
1985 
1986   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1987     return true;
1988 
1989   const Expr *E = B.get<const Expr*>();
1990   switch (E->getStmtClass()) {
1991   default:
1992     return false;
1993   case Expr::CompoundLiteralExprClass: {
1994     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1995     return CLE->isFileScope() && CLE->isLValue();
1996   }
1997   case Expr::MaterializeTemporaryExprClass:
1998     // A materialized temporary might have been lifetime-extended to static
1999     // storage duration.
2000     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2001   // A string literal has static storage duration.
2002   case Expr::StringLiteralClass:
2003   case Expr::PredefinedExprClass:
2004   case Expr::ObjCStringLiteralClass:
2005   case Expr::ObjCEncodeExprClass:
2006     return true;
2007   case Expr::ObjCBoxedExprClass:
2008     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2009   case Expr::CallExprClass:
2010     return IsStringLiteralCall(cast<CallExpr>(E));
2011   // For GCC compatibility, &&label has static storage duration.
2012   case Expr::AddrLabelExprClass:
2013     return true;
2014   // A Block literal expression may be used as the initialization value for
2015   // Block variables at global or local static scope.
2016   case Expr::BlockExprClass:
2017     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2018   case Expr::ImplicitValueInitExprClass:
2019     // FIXME:
2020     // We can never form an lvalue with an implicit value initialization as its
2021     // base through expression evaluation, so these only appear in one case: the
2022     // implicit variable declaration we invent when checking whether a constexpr
2023     // constructor can produce a constant expression. We must assume that such
2024     // an expression might be a global lvalue.
2025     return true;
2026   }
2027 }
2028 
2029 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2030   return LVal.Base.dyn_cast<const ValueDecl*>();
2031 }
2032 
2033 static bool IsLiteralLValue(const LValue &Value) {
2034   if (Value.getLValueCallIndex())
2035     return false;
2036   const Expr *E = Value.Base.dyn_cast<const Expr*>();
2037   return E && !isa<MaterializeTemporaryExpr>(E);
2038 }
2039 
2040 static bool IsWeakLValue(const LValue &Value) {
2041   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2042   return Decl && Decl->isWeak();
2043 }
2044 
2045 static bool isZeroSized(const LValue &Value) {
2046   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2047   if (Decl && isa<VarDecl>(Decl)) {
2048     QualType Ty = Decl->getType();
2049     if (Ty->isArrayType())
2050       return Ty->isIncompleteType() ||
2051              Decl->getASTContext().getTypeSize(Ty) == 0;
2052   }
2053   return false;
2054 }
2055 
2056 static bool HasSameBase(const LValue &A, const LValue &B) {
2057   if (!A.getLValueBase())
2058     return !B.getLValueBase();
2059   if (!B.getLValueBase())
2060     return false;
2061 
2062   if (A.getLValueBase().getOpaqueValue() !=
2063       B.getLValueBase().getOpaqueValue())
2064     return false;
2065 
2066   return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2067          A.getLValueVersion() == B.getLValueVersion();
2068 }
2069 
2070 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2071   assert(Base && "no location for a null lvalue");
2072   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2073 
2074   // For a parameter, find the corresponding call stack frame (if it still
2075   // exists), and point at the parameter of the function definition we actually
2076   // invoked.
2077   if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2078     unsigned Idx = PVD->getFunctionScopeIndex();
2079     for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2080       if (F->Arguments.CallIndex == Base.getCallIndex() &&
2081           F->Arguments.Version == Base.getVersion() && F->Callee &&
2082           Idx < F->Callee->getNumParams()) {
2083         VD = F->Callee->getParamDecl(Idx);
2084         break;
2085       }
2086     }
2087   }
2088 
2089   if (VD)
2090     Info.Note(VD->getLocation(), diag::note_declared_at);
2091   else if (const Expr *E = Base.dyn_cast<const Expr*>())
2092     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2093   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2094     // FIXME: Produce a note for dangling pointers too.
2095     if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
2096       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2097                 diag::note_constexpr_dynamic_alloc_here);
2098   }
2099   // We have no information to show for a typeid(T) object.
2100 }
2101 
2102 enum class CheckEvaluationResultKind {
2103   ConstantExpression,
2104   FullyInitialized,
2105 };
2106 
2107 /// Materialized temporaries that we've already checked to determine if they're
2108 /// initializsed by a constant expression.
2109 using CheckedTemporaries =
2110     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2111 
2112 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2113                                   EvalInfo &Info, SourceLocation DiagLoc,
2114                                   QualType Type, const APValue &Value,
2115                                   Expr::ConstExprUsage Usage,
2116                                   SourceLocation SubobjectLoc,
2117                                   CheckedTemporaries &CheckedTemps);
2118 
2119 /// Check that this reference or pointer core constant expression is a valid
2120 /// value for an address or reference constant expression. Return true if we
2121 /// can fold this expression, whether or not it's a constant expression.
2122 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2123                                           QualType Type, const LValue &LVal,
2124                                           Expr::ConstExprUsage Usage,
2125                                           CheckedTemporaries &CheckedTemps) {
2126   bool IsReferenceType = Type->isReferenceType();
2127 
2128   APValue::LValueBase Base = LVal.getLValueBase();
2129   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2130 
2131   if (auto *VD = LVal.getLValueBase().dyn_cast<const ValueDecl *>()) {
2132     if (auto *FD = dyn_cast<FunctionDecl>(VD)) {
2133       if (FD->isConsteval()) {
2134         Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2135             << !Type->isAnyPointerType();
2136         Info.Note(FD->getLocation(), diag::note_declared_at);
2137         return false;
2138       }
2139     }
2140   }
2141 
2142   // Check that the object is a global. Note that the fake 'this' object we
2143   // manufacture when checking potential constant expressions is conservatively
2144   // assumed to be global here.
2145   if (!IsGlobalLValue(Base)) {
2146     if (Info.getLangOpts().CPlusPlus11) {
2147       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2148       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2149         << IsReferenceType << !Designator.Entries.empty()
2150         << !!VD << VD;
2151 
2152       auto *VarD = dyn_cast_or_null<VarDecl>(VD);
2153       if (VarD && VarD->isConstexpr()) {
2154         // Non-static local constexpr variables have unintuitive semantics:
2155         //   constexpr int a = 1;
2156         //   constexpr const int *p = &a;
2157         // ... is invalid because the address of 'a' is not constant. Suggest
2158         // adding a 'static' in this case.
2159         Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2160             << VarD
2161             << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2162       } else {
2163         NoteLValueLocation(Info, Base);
2164       }
2165     } else {
2166       Info.FFDiag(Loc);
2167     }
2168     // Don't allow references to temporaries to escape.
2169     return false;
2170   }
2171   assert((Info.checkingPotentialConstantExpression() ||
2172           LVal.getLValueCallIndex() == 0) &&
2173          "have call index for global lvalue");
2174 
2175   if (Base.is<DynamicAllocLValue>()) {
2176     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2177         << IsReferenceType << !Designator.Entries.empty();
2178     NoteLValueLocation(Info, Base);
2179     return false;
2180   }
2181 
2182   if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
2183     if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
2184       // Check if this is a thread-local variable.
2185       if (Var->getTLSKind())
2186         // FIXME: Diagnostic!
2187         return false;
2188 
2189       // A dllimport variable never acts like a constant.
2190       if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
2191         // FIXME: Diagnostic!
2192         return false;
2193     }
2194     if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
2195       // __declspec(dllimport) must be handled very carefully:
2196       // We must never initialize an expression with the thunk in C++.
2197       // Doing otherwise would allow the same id-expression to yield
2198       // different addresses for the same function in different translation
2199       // units.  However, this means that we must dynamically initialize the
2200       // expression with the contents of the import address table at runtime.
2201       //
2202       // The C language has no notion of ODR; furthermore, it has no notion of
2203       // dynamic initialization.  This means that we are permitted to
2204       // perform initialization with the address of the thunk.
2205       if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
2206           FD->hasAttr<DLLImportAttr>())
2207         // FIXME: Diagnostic!
2208         return false;
2209     }
2210   } else if (const auto *MTE = dyn_cast_or_null<MaterializeTemporaryExpr>(
2211                  Base.dyn_cast<const Expr *>())) {
2212     if (CheckedTemps.insert(MTE).second) {
2213       QualType TempType = getType(Base);
2214       if (TempType.isDestructedType()) {
2215         Info.FFDiag(MTE->getExprLoc(),
2216                     diag::note_constexpr_unsupported_tempoarary_nontrivial_dtor)
2217             << TempType;
2218         return false;
2219       }
2220 
2221       APValue *V = MTE->getOrCreateValue(false);
2222       assert(V && "evasluation result refers to uninitialised temporary");
2223       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2224                                  Info, MTE->getExprLoc(), TempType, *V,
2225                                  Usage, SourceLocation(), CheckedTemps))
2226         return false;
2227     }
2228   }
2229 
2230   // Allow address constant expressions to be past-the-end pointers. This is
2231   // an extension: the standard requires them to point to an object.
2232   if (!IsReferenceType)
2233     return true;
2234 
2235   // A reference constant expression must refer to an object.
2236   if (!Base) {
2237     // FIXME: diagnostic
2238     Info.CCEDiag(Loc);
2239     return true;
2240   }
2241 
2242   // Does this refer one past the end of some object?
2243   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2244     const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2245     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2246       << !Designator.Entries.empty() << !!VD << VD;
2247     NoteLValueLocation(Info, Base);
2248   }
2249 
2250   return true;
2251 }
2252 
2253 /// Member pointers are constant expressions unless they point to a
2254 /// non-virtual dllimport member function.
2255 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2256                                                  SourceLocation Loc,
2257                                                  QualType Type,
2258                                                  const APValue &Value,
2259                                                  Expr::ConstExprUsage Usage) {
2260   const ValueDecl *Member = Value.getMemberPointerDecl();
2261   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2262   if (!FD)
2263     return true;
2264   if (FD->isConsteval()) {
2265     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2266     Info.Note(FD->getLocation(), diag::note_declared_at);
2267     return false;
2268   }
2269   return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
2270          !FD->hasAttr<DLLImportAttr>();
2271 }
2272 
2273 /// Check that this core constant expression is of literal type, and if not,
2274 /// produce an appropriate diagnostic.
2275 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2276                              const LValue *This = nullptr) {
2277   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
2278     return true;
2279 
2280   // C++1y: A constant initializer for an object o [...] may also invoke
2281   // constexpr constructors for o and its subobjects even if those objects
2282   // are of non-literal class types.
2283   //
2284   // C++11 missed this detail for aggregates, so classes like this:
2285   //   struct foo_t { union { int i; volatile int j; } u; };
2286   // are not (obviously) initializable like so:
2287   //   __attribute__((__require_constant_initialization__))
2288   //   static const foo_t x = {{0}};
2289   // because "i" is a subobject with non-literal initialization (due to the
2290   // volatile member of the union). See:
2291   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2292   // Therefore, we use the C++1y behavior.
2293   if (This && Info.EvaluatingDecl == This->getLValueBase())
2294     return true;
2295 
2296   // Prvalue constant expressions must be of literal types.
2297   if (Info.getLangOpts().CPlusPlus11)
2298     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2299       << E->getType();
2300   else
2301     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2302   return false;
2303 }
2304 
2305 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2306                                   EvalInfo &Info, SourceLocation DiagLoc,
2307                                   QualType Type, const APValue &Value,
2308                                   Expr::ConstExprUsage Usage,
2309                                   SourceLocation SubobjectLoc,
2310                                   CheckedTemporaries &CheckedTemps) {
2311   if (!Value.hasValue()) {
2312     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2313       << true << Type;
2314     if (SubobjectLoc.isValid())
2315       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2316     return false;
2317   }
2318 
2319   // We allow _Atomic(T) to be initialized from anything that T can be
2320   // initialized from.
2321   if (const AtomicType *AT = Type->getAs<AtomicType>())
2322     Type = AT->getValueType();
2323 
2324   // Core issue 1454: For a literal constant expression of array or class type,
2325   // each subobject of its value shall have been initialized by a constant
2326   // expression.
2327   if (Value.isArray()) {
2328     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2329     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2330       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2331                                  Value.getArrayInitializedElt(I), Usage,
2332                                  SubobjectLoc, CheckedTemps))
2333         return false;
2334     }
2335     if (!Value.hasArrayFiller())
2336       return true;
2337     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2338                                  Value.getArrayFiller(), Usage, SubobjectLoc,
2339                                  CheckedTemps);
2340   }
2341   if (Value.isUnion() && Value.getUnionField()) {
2342     return CheckEvaluationResult(
2343         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2344         Value.getUnionValue(), Usage, Value.getUnionField()->getLocation(),
2345         CheckedTemps);
2346   }
2347   if (Value.isStruct()) {
2348     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2349     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2350       unsigned BaseIndex = 0;
2351       for (const CXXBaseSpecifier &BS : CD->bases()) {
2352         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2353                                    Value.getStructBase(BaseIndex), Usage,
2354                                    BS.getBeginLoc(), CheckedTemps))
2355           return false;
2356         ++BaseIndex;
2357       }
2358     }
2359     for (const auto *I : RD->fields()) {
2360       if (I->isUnnamedBitfield())
2361         continue;
2362 
2363       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2364                                  Value.getStructField(I->getFieldIndex()),
2365                                  Usage, I->getLocation(), CheckedTemps))
2366         return false;
2367     }
2368   }
2369 
2370   if (Value.isLValue() &&
2371       CERK == CheckEvaluationResultKind::ConstantExpression) {
2372     LValue LVal;
2373     LVal.setFrom(Info.Ctx, Value);
2374     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage,
2375                                          CheckedTemps);
2376   }
2377 
2378   if (Value.isMemberPointer() &&
2379       CERK == CheckEvaluationResultKind::ConstantExpression)
2380     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
2381 
2382   // Everything else is fine.
2383   return true;
2384 }
2385 
2386 /// Check that this core constant expression value is a valid value for a
2387 /// constant expression. If not, report an appropriate diagnostic. Does not
2388 /// check that the expression is of literal type.
2389 static bool
2390 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2391                         const APValue &Value,
2392                         Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
2393   // Nothing to check for a constant expression of type 'cv void'.
2394   if (Type->isVoidType())
2395     return true;
2396 
2397   CheckedTemporaries CheckedTemps;
2398   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2399                                Info, DiagLoc, Type, Value, Usage,
2400                                SourceLocation(), CheckedTemps);
2401 }
2402 
2403 /// Check that this evaluated value is fully-initialized and can be loaded by
2404 /// an lvalue-to-rvalue conversion.
2405 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2406                                   QualType Type, const APValue &Value) {
2407   CheckedTemporaries CheckedTemps;
2408   return CheckEvaluationResult(
2409       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2410       Expr::EvaluateForCodeGen, SourceLocation(), CheckedTemps);
2411 }
2412 
2413 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2414 /// "the allocated storage is deallocated within the evaluation".
2415 static bool CheckMemoryLeaks(EvalInfo &Info) {
2416   if (!Info.HeapAllocs.empty()) {
2417     // We can still fold to a constant despite a compile-time memory leak,
2418     // so long as the heap allocation isn't referenced in the result (we check
2419     // that in CheckConstantExpression).
2420     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2421                  diag::note_constexpr_memory_leak)
2422         << unsigned(Info.HeapAllocs.size() - 1);
2423   }
2424   return true;
2425 }
2426 
2427 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2428   // A null base expression indicates a null pointer.  These are always
2429   // evaluatable, and they are false unless the offset is zero.
2430   if (!Value.getLValueBase()) {
2431     Result = !Value.getLValueOffset().isZero();
2432     return true;
2433   }
2434 
2435   // We have a non-null base.  These are generally known to be true, but if it's
2436   // a weak declaration it can be null at runtime.
2437   Result = true;
2438   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2439   return !Decl || !Decl->isWeak();
2440 }
2441 
2442 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2443   switch (Val.getKind()) {
2444   case APValue::None:
2445   case APValue::Indeterminate:
2446     return false;
2447   case APValue::Int:
2448     Result = Val.getInt().getBoolValue();
2449     return true;
2450   case APValue::FixedPoint:
2451     Result = Val.getFixedPoint().getBoolValue();
2452     return true;
2453   case APValue::Float:
2454     Result = !Val.getFloat().isZero();
2455     return true;
2456   case APValue::ComplexInt:
2457     Result = Val.getComplexIntReal().getBoolValue() ||
2458              Val.getComplexIntImag().getBoolValue();
2459     return true;
2460   case APValue::ComplexFloat:
2461     Result = !Val.getComplexFloatReal().isZero() ||
2462              !Val.getComplexFloatImag().isZero();
2463     return true;
2464   case APValue::LValue:
2465     return EvalPointerValueAsBool(Val, Result);
2466   case APValue::MemberPointer:
2467     Result = Val.getMemberPointerDecl();
2468     return true;
2469   case APValue::Vector:
2470   case APValue::Array:
2471   case APValue::Struct:
2472   case APValue::Union:
2473   case APValue::AddrLabelDiff:
2474     return false;
2475   }
2476 
2477   llvm_unreachable("unknown APValue kind");
2478 }
2479 
2480 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2481                                        EvalInfo &Info) {
2482   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2483   APValue Val;
2484   if (!Evaluate(Val, Info, E))
2485     return false;
2486   return HandleConversionToBool(Val, Result);
2487 }
2488 
2489 template<typename T>
2490 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2491                            const T &SrcValue, QualType DestType) {
2492   Info.CCEDiag(E, diag::note_constexpr_overflow)
2493     << SrcValue << DestType;
2494   return Info.noteUndefinedBehavior();
2495 }
2496 
2497 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2498                                  QualType SrcType, const APFloat &Value,
2499                                  QualType DestType, APSInt &Result) {
2500   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2501   // Determine whether we are converting to unsigned or signed.
2502   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2503 
2504   Result = APSInt(DestWidth, !DestSigned);
2505   bool ignored;
2506   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2507       & APFloat::opInvalidOp)
2508     return HandleOverflow(Info, E, Value, DestType);
2509   return true;
2510 }
2511 
2512 /// Get rounding mode used for evaluation of the specified expression.
2513 /// \param[out] DynamicRM Is set to true is the requested rounding mode is
2514 ///                       dynamic.
2515 /// If rounding mode is unknown at compile time, still try to evaluate the
2516 /// expression. If the result is exact, it does not depend on rounding mode.
2517 /// So return "tonearest" mode instead of "dynamic".
2518 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E,
2519                                                 bool &DynamicRM) {
2520   llvm::RoundingMode RM =
2521       E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2522   DynamicRM = (RM == llvm::RoundingMode::Dynamic);
2523   if (DynamicRM)
2524     RM = llvm::RoundingMode::NearestTiesToEven;
2525   return RM;
2526 }
2527 
2528 /// Check if the given evaluation result is allowed for constant evaluation.
2529 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2530                                      APFloat::opStatus St) {
2531   // In a constant context, assume that any dynamic rounding mode or FP
2532   // exception state matches the default floating-point environment.
2533   if (Info.InConstantContext)
2534     return true;
2535 
2536   FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2537   if ((St & APFloat::opInexact) &&
2538       FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2539     // Inexact result means that it depends on rounding mode. If the requested
2540     // mode is dynamic, the evaluation cannot be made in compile time.
2541     Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2542     return false;
2543   }
2544 
2545   if ((St & APFloat::opStatus::opInvalidOp) &&
2546       FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) {
2547     // There is no usefully definable result.
2548     Info.FFDiag(E);
2549     return false;
2550   }
2551 
2552   // FIXME: if:
2553   // - evaluation triggered other FP exception, and
2554   // - exception mode is not "ignore", and
2555   // - the expression being evaluated is not a part of global variable
2556   //   initializer,
2557   // the evaluation probably need to be rejected.
2558   return true;
2559 }
2560 
2561 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2562                                    QualType SrcType, QualType DestType,
2563                                    APFloat &Result) {
2564   assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2565   bool DynamicRM;
2566   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2567   APFloat::opStatus St;
2568   APFloat Value = Result;
2569   bool ignored;
2570   St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2571   return checkFloatingPointResult(Info, E, St);
2572 }
2573 
2574 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2575                                  QualType DestType, QualType SrcType,
2576                                  const APSInt &Value) {
2577   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2578   // Figure out if this is a truncate, extend or noop cast.
2579   // If the input is signed, do a sign extend, noop, or truncate.
2580   APSInt Result = Value.extOrTrunc(DestWidth);
2581   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2582   if (DestType->isBooleanType())
2583     Result = Value.getBoolValue();
2584   return Result;
2585 }
2586 
2587 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2588                                  QualType SrcType, const APSInt &Value,
2589                                  QualType DestType, APFloat &Result) {
2590   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2591   Result.convertFromAPInt(Value, Value.isSigned(),
2592                           APFloat::rmNearestTiesToEven);
2593   return true;
2594 }
2595 
2596 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2597                                   APValue &Value, const FieldDecl *FD) {
2598   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2599 
2600   if (!Value.isInt()) {
2601     // Trying to store a pointer-cast-to-integer into a bitfield.
2602     // FIXME: In this case, we should provide the diagnostic for casting
2603     // a pointer to an integer.
2604     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2605     Info.FFDiag(E);
2606     return false;
2607   }
2608 
2609   APSInt &Int = Value.getInt();
2610   unsigned OldBitWidth = Int.getBitWidth();
2611   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2612   if (NewBitWidth < OldBitWidth)
2613     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2614   return true;
2615 }
2616 
2617 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2618                                   llvm::APInt &Res) {
2619   APValue SVal;
2620   if (!Evaluate(SVal, Info, E))
2621     return false;
2622   if (SVal.isInt()) {
2623     Res = SVal.getInt();
2624     return true;
2625   }
2626   if (SVal.isFloat()) {
2627     Res = SVal.getFloat().bitcastToAPInt();
2628     return true;
2629   }
2630   if (SVal.isVector()) {
2631     QualType VecTy = E->getType();
2632     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2633     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2634     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2635     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2636     Res = llvm::APInt::getNullValue(VecSize);
2637     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2638       APValue &Elt = SVal.getVectorElt(i);
2639       llvm::APInt EltAsInt;
2640       if (Elt.isInt()) {
2641         EltAsInt = Elt.getInt();
2642       } else if (Elt.isFloat()) {
2643         EltAsInt = Elt.getFloat().bitcastToAPInt();
2644       } else {
2645         // Don't try to handle vectors of anything other than int or float
2646         // (not sure if it's possible to hit this case).
2647         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2648         return false;
2649       }
2650       unsigned BaseEltSize = EltAsInt.getBitWidth();
2651       if (BigEndian)
2652         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2653       else
2654         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2655     }
2656     return true;
2657   }
2658   // Give up if the input isn't an int, float, or vector.  For example, we
2659   // reject "(v4i16)(intptr_t)&a".
2660   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2661   return false;
2662 }
2663 
2664 /// Perform the given integer operation, which is known to need at most BitWidth
2665 /// bits, and check for overflow in the original type (if that type was not an
2666 /// unsigned type).
2667 template<typename Operation>
2668 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2669                                  const APSInt &LHS, const APSInt &RHS,
2670                                  unsigned BitWidth, Operation Op,
2671                                  APSInt &Result) {
2672   if (LHS.isUnsigned()) {
2673     Result = Op(LHS, RHS);
2674     return true;
2675   }
2676 
2677   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2678   Result = Value.trunc(LHS.getBitWidth());
2679   if (Result.extend(BitWidth) != Value) {
2680     if (Info.checkingForUndefinedBehavior())
2681       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2682                                        diag::warn_integer_constant_overflow)
2683           << Result.toString(10) << E->getType();
2684     else
2685       return HandleOverflow(Info, E, Value, E->getType());
2686   }
2687   return true;
2688 }
2689 
2690 /// Perform the given binary integer operation.
2691 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2692                               BinaryOperatorKind Opcode, APSInt RHS,
2693                               APSInt &Result) {
2694   switch (Opcode) {
2695   default:
2696     Info.FFDiag(E);
2697     return false;
2698   case BO_Mul:
2699     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2700                                 std::multiplies<APSInt>(), Result);
2701   case BO_Add:
2702     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2703                                 std::plus<APSInt>(), Result);
2704   case BO_Sub:
2705     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2706                                 std::minus<APSInt>(), Result);
2707   case BO_And: Result = LHS & RHS; return true;
2708   case BO_Xor: Result = LHS ^ RHS; return true;
2709   case BO_Or:  Result = LHS | RHS; return true;
2710   case BO_Div:
2711   case BO_Rem:
2712     if (RHS == 0) {
2713       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2714       return false;
2715     }
2716     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2717     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2718     // this operation and gives the two's complement result.
2719     if (RHS.isNegative() && RHS.isAllOnesValue() &&
2720         LHS.isSigned() && LHS.isMinSignedValue())
2721       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2722                             E->getType());
2723     return true;
2724   case BO_Shl: {
2725     if (Info.getLangOpts().OpenCL)
2726       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2727       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2728                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2729                     RHS.isUnsigned());
2730     else if (RHS.isSigned() && RHS.isNegative()) {
2731       // During constant-folding, a negative shift is an opposite shift. Such
2732       // a shift is not a constant expression.
2733       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2734       RHS = -RHS;
2735       goto shift_right;
2736     }
2737   shift_left:
2738     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2739     // the shifted type.
2740     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2741     if (SA != RHS) {
2742       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2743         << RHS << E->getType() << LHS.getBitWidth();
2744     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2745       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2746       // operand, and must not overflow the corresponding unsigned type.
2747       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2748       // E1 x 2^E2 module 2^N.
2749       if (LHS.isNegative())
2750         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2751       else if (LHS.countLeadingZeros() < SA)
2752         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2753     }
2754     Result = LHS << SA;
2755     return true;
2756   }
2757   case BO_Shr: {
2758     if (Info.getLangOpts().OpenCL)
2759       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2760       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2761                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2762                     RHS.isUnsigned());
2763     else if (RHS.isSigned() && RHS.isNegative()) {
2764       // During constant-folding, a negative shift is an opposite shift. Such a
2765       // shift is not a constant expression.
2766       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2767       RHS = -RHS;
2768       goto shift_left;
2769     }
2770   shift_right:
2771     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2772     // shifted type.
2773     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2774     if (SA != RHS)
2775       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2776         << RHS << E->getType() << LHS.getBitWidth();
2777     Result = LHS >> SA;
2778     return true;
2779   }
2780 
2781   case BO_LT: Result = LHS < RHS; return true;
2782   case BO_GT: Result = LHS > RHS; return true;
2783   case BO_LE: Result = LHS <= RHS; return true;
2784   case BO_GE: Result = LHS >= RHS; return true;
2785   case BO_EQ: Result = LHS == RHS; return true;
2786   case BO_NE: Result = LHS != RHS; return true;
2787   case BO_Cmp:
2788     llvm_unreachable("BO_Cmp should be handled elsewhere");
2789   }
2790 }
2791 
2792 /// Perform the given binary floating-point operation, in-place, on LHS.
2793 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2794                                   APFloat &LHS, BinaryOperatorKind Opcode,
2795                                   const APFloat &RHS) {
2796   bool DynamicRM;
2797   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2798   APFloat::opStatus St;
2799   switch (Opcode) {
2800   default:
2801     Info.FFDiag(E);
2802     return false;
2803   case BO_Mul:
2804     St = LHS.multiply(RHS, RM);
2805     break;
2806   case BO_Add:
2807     St = LHS.add(RHS, RM);
2808     break;
2809   case BO_Sub:
2810     St = LHS.subtract(RHS, RM);
2811     break;
2812   case BO_Div:
2813     // [expr.mul]p4:
2814     //   If the second operand of / or % is zero the behavior is undefined.
2815     if (RHS.isZero())
2816       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2817     St = LHS.divide(RHS, RM);
2818     break;
2819   }
2820 
2821   // [expr.pre]p4:
2822   //   If during the evaluation of an expression, the result is not
2823   //   mathematically defined [...], the behavior is undefined.
2824   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2825   if (LHS.isNaN()) {
2826     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2827     return Info.noteUndefinedBehavior();
2828   }
2829 
2830   return checkFloatingPointResult(Info, E, St);
2831 }
2832 
2833 static bool handleLogicalOpForVector(const APInt &LHSValue,
2834                                      BinaryOperatorKind Opcode,
2835                                      const APInt &RHSValue, APInt &Result) {
2836   bool LHS = (LHSValue != 0);
2837   bool RHS = (RHSValue != 0);
2838 
2839   if (Opcode == BO_LAnd)
2840     Result = LHS && RHS;
2841   else
2842     Result = LHS || RHS;
2843   return true;
2844 }
2845 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2846                                      BinaryOperatorKind Opcode,
2847                                      const APFloat &RHSValue, APInt &Result) {
2848   bool LHS = !LHSValue.isZero();
2849   bool RHS = !RHSValue.isZero();
2850 
2851   if (Opcode == BO_LAnd)
2852     Result = LHS && RHS;
2853   else
2854     Result = LHS || RHS;
2855   return true;
2856 }
2857 
2858 static bool handleLogicalOpForVector(const APValue &LHSValue,
2859                                      BinaryOperatorKind Opcode,
2860                                      const APValue &RHSValue, APInt &Result) {
2861   // The result is always an int type, however operands match the first.
2862   if (LHSValue.getKind() == APValue::Int)
2863     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2864                                     RHSValue.getInt(), Result);
2865   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2866   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2867                                   RHSValue.getFloat(), Result);
2868 }
2869 
2870 template <typename APTy>
2871 static bool
2872 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2873                                const APTy &RHSValue, APInt &Result) {
2874   switch (Opcode) {
2875   default:
2876     llvm_unreachable("unsupported binary operator");
2877   case BO_EQ:
2878     Result = (LHSValue == RHSValue);
2879     break;
2880   case BO_NE:
2881     Result = (LHSValue != RHSValue);
2882     break;
2883   case BO_LT:
2884     Result = (LHSValue < RHSValue);
2885     break;
2886   case BO_GT:
2887     Result = (LHSValue > RHSValue);
2888     break;
2889   case BO_LE:
2890     Result = (LHSValue <= RHSValue);
2891     break;
2892   case BO_GE:
2893     Result = (LHSValue >= RHSValue);
2894     break;
2895   }
2896 
2897   return true;
2898 }
2899 
2900 static bool handleCompareOpForVector(const APValue &LHSValue,
2901                                      BinaryOperatorKind Opcode,
2902                                      const APValue &RHSValue, APInt &Result) {
2903   // The result is always an int type, however operands match the first.
2904   if (LHSValue.getKind() == APValue::Int)
2905     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2906                                           RHSValue.getInt(), Result);
2907   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2908   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2909                                         RHSValue.getFloat(), Result);
2910 }
2911 
2912 // Perform binary operations for vector types, in place on the LHS.
2913 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2914                                     BinaryOperatorKind Opcode,
2915                                     APValue &LHSValue,
2916                                     const APValue &RHSValue) {
2917   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2918          "Operation not supported on vector types");
2919 
2920   const auto *VT = E->getType()->castAs<VectorType>();
2921   unsigned NumElements = VT->getNumElements();
2922   QualType EltTy = VT->getElementType();
2923 
2924   // In the cases (typically C as I've observed) where we aren't evaluating
2925   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2926   // just give up.
2927   if (!LHSValue.isVector()) {
2928     assert(LHSValue.isLValue() &&
2929            "A vector result that isn't a vector OR uncalculated LValue");
2930     Info.FFDiag(E);
2931     return false;
2932   }
2933 
2934   assert(LHSValue.getVectorLength() == NumElements &&
2935          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2936 
2937   SmallVector<APValue, 4> ResultElements;
2938 
2939   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
2940     APValue LHSElt = LHSValue.getVectorElt(EltNum);
2941     APValue RHSElt = RHSValue.getVectorElt(EltNum);
2942 
2943     if (EltTy->isIntegerType()) {
2944       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
2945                        EltTy->isUnsignedIntegerType()};
2946       bool Success = true;
2947 
2948       if (BinaryOperator::isLogicalOp(Opcode))
2949         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2950       else if (BinaryOperator::isComparisonOp(Opcode))
2951         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2952       else
2953         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
2954                                     RHSElt.getInt(), EltResult);
2955 
2956       if (!Success) {
2957         Info.FFDiag(E);
2958         return false;
2959       }
2960       ResultElements.emplace_back(EltResult);
2961 
2962     } else if (EltTy->isFloatingType()) {
2963       assert(LHSElt.getKind() == APValue::Float &&
2964              RHSElt.getKind() == APValue::Float &&
2965              "Mismatched LHS/RHS/Result Type");
2966       APFloat LHSFloat = LHSElt.getFloat();
2967 
2968       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
2969                                  RHSElt.getFloat())) {
2970         Info.FFDiag(E);
2971         return false;
2972       }
2973 
2974       ResultElements.emplace_back(LHSFloat);
2975     }
2976   }
2977 
2978   LHSValue = APValue(ResultElements.data(), ResultElements.size());
2979   return true;
2980 }
2981 
2982 /// Cast an lvalue referring to a base subobject to a derived class, by
2983 /// truncating the lvalue's path to the given length.
2984 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2985                                const RecordDecl *TruncatedType,
2986                                unsigned TruncatedElements) {
2987   SubobjectDesignator &D = Result.Designator;
2988 
2989   // Check we actually point to a derived class object.
2990   if (TruncatedElements == D.Entries.size())
2991     return true;
2992   assert(TruncatedElements >= D.MostDerivedPathLength &&
2993          "not casting to a derived class");
2994   if (!Result.checkSubobject(Info, E, CSK_Derived))
2995     return false;
2996 
2997   // Truncate the path to the subobject, and remove any derived-to-base offsets.
2998   const RecordDecl *RD = TruncatedType;
2999   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3000     if (RD->isInvalidDecl()) return false;
3001     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3002     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3003     if (isVirtualBaseClass(D.Entries[I]))
3004       Result.Offset -= Layout.getVBaseClassOffset(Base);
3005     else
3006       Result.Offset -= Layout.getBaseClassOffset(Base);
3007     RD = Base;
3008   }
3009   D.Entries.resize(TruncatedElements);
3010   return true;
3011 }
3012 
3013 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3014                                    const CXXRecordDecl *Derived,
3015                                    const CXXRecordDecl *Base,
3016                                    const ASTRecordLayout *RL = nullptr) {
3017   if (!RL) {
3018     if (Derived->isInvalidDecl()) return false;
3019     RL = &Info.Ctx.getASTRecordLayout(Derived);
3020   }
3021 
3022   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3023   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3024   return true;
3025 }
3026 
3027 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3028                              const CXXRecordDecl *DerivedDecl,
3029                              const CXXBaseSpecifier *Base) {
3030   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3031 
3032   if (!Base->isVirtual())
3033     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3034 
3035   SubobjectDesignator &D = Obj.Designator;
3036   if (D.Invalid)
3037     return false;
3038 
3039   // Extract most-derived object and corresponding type.
3040   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3041   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3042     return false;
3043 
3044   // Find the virtual base class.
3045   if (DerivedDecl->isInvalidDecl()) return false;
3046   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3047   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3048   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3049   return true;
3050 }
3051 
3052 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3053                                  QualType Type, LValue &Result) {
3054   for (CastExpr::path_const_iterator PathI = E->path_begin(),
3055                                      PathE = E->path_end();
3056        PathI != PathE; ++PathI) {
3057     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3058                           *PathI))
3059       return false;
3060     Type = (*PathI)->getType();
3061   }
3062   return true;
3063 }
3064 
3065 /// Cast an lvalue referring to a derived class to a known base subobject.
3066 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3067                             const CXXRecordDecl *DerivedRD,
3068                             const CXXRecordDecl *BaseRD) {
3069   CXXBasePaths Paths(/*FindAmbiguities=*/false,
3070                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
3071   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3072     llvm_unreachable("Class must be derived from the passed in base class!");
3073 
3074   for (CXXBasePathElement &Elem : Paths.front())
3075     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3076       return false;
3077   return true;
3078 }
3079 
3080 /// Update LVal to refer to the given field, which must be a member of the type
3081 /// currently described by LVal.
3082 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3083                                const FieldDecl *FD,
3084                                const ASTRecordLayout *RL = nullptr) {
3085   if (!RL) {
3086     if (FD->getParent()->isInvalidDecl()) return false;
3087     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3088   }
3089 
3090   unsigned I = FD->getFieldIndex();
3091   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3092   LVal.addDecl(Info, E, FD);
3093   return true;
3094 }
3095 
3096 /// Update LVal to refer to the given indirect field.
3097 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3098                                        LValue &LVal,
3099                                        const IndirectFieldDecl *IFD) {
3100   for (const auto *C : IFD->chain())
3101     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3102       return false;
3103   return true;
3104 }
3105 
3106 /// Get the size of the given type in char units.
3107 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3108                          QualType Type, CharUnits &Size) {
3109   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3110   // extension.
3111   if (Type->isVoidType() || Type->isFunctionType()) {
3112     Size = CharUnits::One();
3113     return true;
3114   }
3115 
3116   if (Type->isDependentType()) {
3117     Info.FFDiag(Loc);
3118     return false;
3119   }
3120 
3121   if (!Type->isConstantSizeType()) {
3122     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3123     // FIXME: Better diagnostic.
3124     Info.FFDiag(Loc);
3125     return false;
3126   }
3127 
3128   Size = Info.Ctx.getTypeSizeInChars(Type);
3129   return true;
3130 }
3131 
3132 /// Update a pointer value to model pointer arithmetic.
3133 /// \param Info - Information about the ongoing evaluation.
3134 /// \param E - The expression being evaluated, for diagnostic purposes.
3135 /// \param LVal - The pointer value to be updated.
3136 /// \param EltTy - The pointee type represented by LVal.
3137 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3138 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3139                                         LValue &LVal, QualType EltTy,
3140                                         APSInt Adjustment) {
3141   CharUnits SizeOfPointee;
3142   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3143     return false;
3144 
3145   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3146   return true;
3147 }
3148 
3149 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3150                                         LValue &LVal, QualType EltTy,
3151                                         int64_t Adjustment) {
3152   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3153                                      APSInt::get(Adjustment));
3154 }
3155 
3156 /// Update an lvalue to refer to a component of a complex number.
3157 /// \param Info - Information about the ongoing evaluation.
3158 /// \param LVal - The lvalue to be updated.
3159 /// \param EltTy - The complex number's component type.
3160 /// \param Imag - False for the real component, true for the imaginary.
3161 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3162                                        LValue &LVal, QualType EltTy,
3163                                        bool Imag) {
3164   if (Imag) {
3165     CharUnits SizeOfComponent;
3166     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3167       return false;
3168     LVal.Offset += SizeOfComponent;
3169   }
3170   LVal.addComplex(Info, E, EltTy, Imag);
3171   return true;
3172 }
3173 
3174 /// Try to evaluate the initializer for a variable declaration.
3175 ///
3176 /// \param Info   Information about the ongoing evaluation.
3177 /// \param E      An expression to be used when printing diagnostics.
3178 /// \param VD     The variable whose initializer should be obtained.
3179 /// \param Version The version of the variable within the frame.
3180 /// \param Frame  The frame in which the variable was created. Must be null
3181 ///               if this variable is not local to the evaluation.
3182 /// \param Result Filled in with a pointer to the value of the variable.
3183 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3184                                 const VarDecl *VD, CallStackFrame *Frame,
3185                                 unsigned Version, APValue *&Result) {
3186   APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3187 
3188   // If this is a local variable, dig out its value.
3189   if (Frame) {
3190     Result = Frame->getTemporary(VD, Version);
3191     if (Result)
3192       return true;
3193 
3194     if (!isa<ParmVarDecl>(VD)) {
3195       // Assume variables referenced within a lambda's call operator that were
3196       // not declared within the call operator are captures and during checking
3197       // of a potential constant expression, assume they are unknown constant
3198       // expressions.
3199       assert(isLambdaCallOperator(Frame->Callee) &&
3200              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3201              "missing value for local variable");
3202       if (Info.checkingPotentialConstantExpression())
3203         return false;
3204       // FIXME: This diagnostic is bogus; we do support captures. Is this code
3205       // still reachable at all?
3206       Info.FFDiag(E->getBeginLoc(),
3207                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3208           << "captures not currently allowed";
3209       return false;
3210     }
3211   }
3212 
3213   if (isa<ParmVarDecl>(VD)) {
3214     // Assume parameters of a potential constant expression are usable in
3215     // constant expressions.
3216     if (!Info.checkingPotentialConstantExpression() ||
3217         !Info.CurrentCall->Callee ||
3218         !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3219       if (Info.getLangOpts().CPlusPlus11) {
3220         Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3221             << VD;
3222         NoteLValueLocation(Info, Base);
3223       } else {
3224         Info.FFDiag(E);
3225       }
3226     }
3227     return false;
3228   }
3229 
3230   // Dig out the initializer, and use the declaration which it's attached to.
3231   // FIXME: We should eventually check whether the variable has a reachable
3232   // initializing declaration.
3233   const Expr *Init = VD->getAnyInitializer(VD);
3234   if (!Init) {
3235     // Don't diagnose during potential constant expression checking; an
3236     // initializer might be added later.
3237     if (!Info.checkingPotentialConstantExpression()) {
3238       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3239         << VD;
3240       NoteLValueLocation(Info, Base);
3241     }
3242     return false;
3243   }
3244 
3245   if (Init->isValueDependent()) {
3246     // The DeclRefExpr is not value-dependent, but the variable it refers to
3247     // has a value-dependent initializer. This should only happen in
3248     // constant-folding cases, where the variable is not actually of a suitable
3249     // type for use in a constant expression (otherwise the DeclRefExpr would
3250     // have been value-dependent too), so diagnose that.
3251     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3252     if (!Info.checkingPotentialConstantExpression()) {
3253       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3254                          ? diag::note_constexpr_ltor_non_constexpr
3255                          : diag::note_constexpr_ltor_non_integral, 1)
3256           << VD << VD->getType();
3257       NoteLValueLocation(Info, Base);
3258     }
3259     return false;
3260   }
3261 
3262   // If we're currently evaluating the initializer of this declaration, use that
3263   // in-flight value.
3264   if (declaresSameEntity(Info.EvaluatingDecl.dyn_cast<const ValueDecl *>(),
3265                          VD)) {
3266     Result = Info.EvaluatingDeclValue;
3267     return true;
3268   }
3269 
3270   // Check that we can fold the initializer. In C++, we will have already done
3271   // this in the cases where it matters for conformance.
3272   if (!VD->evaluateValue()) {
3273     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3274     NoteLValueLocation(Info, Base);
3275     return false;
3276   }
3277 
3278   // Check that the variable is actually usable in constant expressions. For a
3279   // const integral variable or a reference, we might have a non-constant
3280   // initializer that we can nonetheless evaluate the initializer for. Such
3281   // variables are not usable in constant expressions. In C++98, the
3282   // initializer also syntactically needs to be an ICE.
3283   //
3284   // FIXME: We don't diagnose cases that aren't potentially usable in constant
3285   // expressions here; doing so would regress diagnostics for things like
3286   // reading from a volatile constexpr variable.
3287   if ((!VD->hasConstantInitialization() &&
3288        VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3289       (Info.getLangOpts().CPlusPlus && !Info.getLangOpts().CPlusPlus11 &&
3290        !VD->hasICEInitializer(Info.Ctx))) {
3291     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3292     NoteLValueLocation(Info, Base);
3293   }
3294 
3295   // Never use the initializer of a weak variable, not even for constant
3296   // folding. We can't be sure that this is the definition that will be used.
3297   if (VD->isWeak()) {
3298     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3299     NoteLValueLocation(Info, Base);
3300     return false;
3301   }
3302 
3303   Result = VD->getEvaluatedValue();
3304   return true;
3305 }
3306 
3307 /// Get the base index of the given base class within an APValue representing
3308 /// the given derived class.
3309 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3310                              const CXXRecordDecl *Base) {
3311   Base = Base->getCanonicalDecl();
3312   unsigned Index = 0;
3313   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3314          E = Derived->bases_end(); I != E; ++I, ++Index) {
3315     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3316       return Index;
3317   }
3318 
3319   llvm_unreachable("base class missing from derived class's bases list");
3320 }
3321 
3322 /// Extract the value of a character from a string literal.
3323 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3324                                             uint64_t Index) {
3325   assert(!isa<SourceLocExpr>(Lit) &&
3326          "SourceLocExpr should have already been converted to a StringLiteral");
3327 
3328   // FIXME: Support MakeStringConstant
3329   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3330     std::string Str;
3331     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3332     assert(Index <= Str.size() && "Index too large");
3333     return APSInt::getUnsigned(Str.c_str()[Index]);
3334   }
3335 
3336   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3337     Lit = PE->getFunctionName();
3338   const StringLiteral *S = cast<StringLiteral>(Lit);
3339   const ConstantArrayType *CAT =
3340       Info.Ctx.getAsConstantArrayType(S->getType());
3341   assert(CAT && "string literal isn't an array");
3342   QualType CharType = CAT->getElementType();
3343   assert(CharType->isIntegerType() && "unexpected character type");
3344 
3345   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3346                CharType->isUnsignedIntegerType());
3347   if (Index < S->getLength())
3348     Value = S->getCodeUnit(Index);
3349   return Value;
3350 }
3351 
3352 // Expand a string literal into an array of characters.
3353 //
3354 // FIXME: This is inefficient; we should probably introduce something similar
3355 // to the LLVM ConstantDataArray to make this cheaper.
3356 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3357                                 APValue &Result,
3358                                 QualType AllocType = QualType()) {
3359   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3360       AllocType.isNull() ? S->getType() : AllocType);
3361   assert(CAT && "string literal isn't an array");
3362   QualType CharType = CAT->getElementType();
3363   assert(CharType->isIntegerType() && "unexpected character type");
3364 
3365   unsigned Elts = CAT->getSize().getZExtValue();
3366   Result = APValue(APValue::UninitArray(),
3367                    std::min(S->getLength(), Elts), Elts);
3368   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3369                CharType->isUnsignedIntegerType());
3370   if (Result.hasArrayFiller())
3371     Result.getArrayFiller() = APValue(Value);
3372   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3373     Value = S->getCodeUnit(I);
3374     Result.getArrayInitializedElt(I) = APValue(Value);
3375   }
3376 }
3377 
3378 // Expand an array so that it has more than Index filled elements.
3379 static void expandArray(APValue &Array, unsigned Index) {
3380   unsigned Size = Array.getArraySize();
3381   assert(Index < Size);
3382 
3383   // Always at least double the number of elements for which we store a value.
3384   unsigned OldElts = Array.getArrayInitializedElts();
3385   unsigned NewElts = std::max(Index+1, OldElts * 2);
3386   NewElts = std::min(Size, std::max(NewElts, 8u));
3387 
3388   // Copy the data across.
3389   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3390   for (unsigned I = 0; I != OldElts; ++I)
3391     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3392   for (unsigned I = OldElts; I != NewElts; ++I)
3393     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3394   if (NewValue.hasArrayFiller())
3395     NewValue.getArrayFiller() = Array.getArrayFiller();
3396   Array.swap(NewValue);
3397 }
3398 
3399 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3400 /// conversion. If it's of class type, we may assume that the copy operation
3401 /// is trivial. Note that this is never true for a union type with fields
3402 /// (because the copy always "reads" the active member) and always true for
3403 /// a non-class type.
3404 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3405 static bool isReadByLvalueToRvalueConversion(QualType T) {
3406   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3407   return !RD || isReadByLvalueToRvalueConversion(RD);
3408 }
3409 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3410   // FIXME: A trivial copy of a union copies the object representation, even if
3411   // the union is empty.
3412   if (RD->isUnion())
3413     return !RD->field_empty();
3414   if (RD->isEmpty())
3415     return false;
3416 
3417   for (auto *Field : RD->fields())
3418     if (!Field->isUnnamedBitfield() &&
3419         isReadByLvalueToRvalueConversion(Field->getType()))
3420       return true;
3421 
3422   for (auto &BaseSpec : RD->bases())
3423     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3424       return true;
3425 
3426   return false;
3427 }
3428 
3429 /// Diagnose an attempt to read from any unreadable field within the specified
3430 /// type, which might be a class type.
3431 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3432                                   QualType T) {
3433   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3434   if (!RD)
3435     return false;
3436 
3437   if (!RD->hasMutableFields())
3438     return false;
3439 
3440   for (auto *Field : RD->fields()) {
3441     // If we're actually going to read this field in some way, then it can't
3442     // be mutable. If we're in a union, then assigning to a mutable field
3443     // (even an empty one) can change the active member, so that's not OK.
3444     // FIXME: Add core issue number for the union case.
3445     if (Field->isMutable() &&
3446         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3447       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3448       Info.Note(Field->getLocation(), diag::note_declared_at);
3449       return true;
3450     }
3451 
3452     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3453       return true;
3454   }
3455 
3456   for (auto &BaseSpec : RD->bases())
3457     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3458       return true;
3459 
3460   // All mutable fields were empty, and thus not actually read.
3461   return false;
3462 }
3463 
3464 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3465                                         APValue::LValueBase Base,
3466                                         bool MutableSubobject = false) {
3467   // A temporary we created.
3468   if (Base.getCallIndex())
3469     return true;
3470 
3471   auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3472   if (!Evaluating)
3473     return false;
3474 
3475   auto *BaseD = Base.dyn_cast<const ValueDecl*>();
3476 
3477   switch (Info.IsEvaluatingDecl) {
3478   case EvalInfo::EvaluatingDeclKind::None:
3479     return false;
3480 
3481   case EvalInfo::EvaluatingDeclKind::Ctor:
3482     // The variable whose initializer we're evaluating.
3483     if (BaseD)
3484       return declaresSameEntity(Evaluating, BaseD);
3485 
3486     // A temporary lifetime-extended by the variable whose initializer we're
3487     // evaluating.
3488     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3489       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3490         return declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating);
3491     return false;
3492 
3493   case EvalInfo::EvaluatingDeclKind::Dtor:
3494     // C++2a [expr.const]p6:
3495     //   [during constant destruction] the lifetime of a and its non-mutable
3496     //   subobjects (but not its mutable subobjects) [are] considered to start
3497     //   within e.
3498     //
3499     // FIXME: We can meaningfully extend this to cover non-const objects, but
3500     // we will need special handling: we should be able to access only
3501     // subobjects of such objects that are themselves declared const.
3502     if (!BaseD ||
3503         !(BaseD->getType().isConstQualified() ||
3504           BaseD->getType()->isReferenceType()) ||
3505         MutableSubobject)
3506       return false;
3507     return declaresSameEntity(Evaluating, BaseD);
3508   }
3509 
3510   llvm_unreachable("unknown evaluating decl kind");
3511 }
3512 
3513 namespace {
3514 /// A handle to a complete object (an object that is not a subobject of
3515 /// another object).
3516 struct CompleteObject {
3517   /// The identity of the object.
3518   APValue::LValueBase Base;
3519   /// The value of the complete object.
3520   APValue *Value;
3521   /// The type of the complete object.
3522   QualType Type;
3523 
3524   CompleteObject() : Value(nullptr) {}
3525   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3526       : Base(Base), Value(Value), Type(Type) {}
3527 
3528   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3529     // If this isn't a "real" access (eg, if it's just accessing the type
3530     // info), allow it. We assume the type doesn't change dynamically for
3531     // subobjects of constexpr objects (even though we'd hit UB here if it
3532     // did). FIXME: Is this right?
3533     if (!isAnyAccess(AK))
3534       return true;
3535 
3536     // In C++14 onwards, it is permitted to read a mutable member whose
3537     // lifetime began within the evaluation.
3538     // FIXME: Should we also allow this in C++11?
3539     if (!Info.getLangOpts().CPlusPlus14)
3540       return false;
3541     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3542   }
3543 
3544   explicit operator bool() const { return !Type.isNull(); }
3545 };
3546 } // end anonymous namespace
3547 
3548 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3549                                  bool IsMutable = false) {
3550   // C++ [basic.type.qualifier]p1:
3551   // - A const object is an object of type const T or a non-mutable subobject
3552   //   of a const object.
3553   if (ObjType.isConstQualified() && !IsMutable)
3554     SubobjType.addConst();
3555   // - A volatile object is an object of type const T or a subobject of a
3556   //   volatile object.
3557   if (ObjType.isVolatileQualified())
3558     SubobjType.addVolatile();
3559   return SubobjType;
3560 }
3561 
3562 /// Find the designated sub-object of an rvalue.
3563 template<typename SubobjectHandler>
3564 typename SubobjectHandler::result_type
3565 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3566               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3567   if (Sub.Invalid)
3568     // A diagnostic will have already been produced.
3569     return handler.failed();
3570   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3571     if (Info.getLangOpts().CPlusPlus11)
3572       Info.FFDiag(E, Sub.isOnePastTheEnd()
3573                          ? diag::note_constexpr_access_past_end
3574                          : diag::note_constexpr_access_unsized_array)
3575           << handler.AccessKind;
3576     else
3577       Info.FFDiag(E);
3578     return handler.failed();
3579   }
3580 
3581   APValue *O = Obj.Value;
3582   QualType ObjType = Obj.Type;
3583   const FieldDecl *LastField = nullptr;
3584   const FieldDecl *VolatileField = nullptr;
3585 
3586   // Walk the designator's path to find the subobject.
3587   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3588     // Reading an indeterminate value is undefined, but assigning over one is OK.
3589     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3590         (O->isIndeterminate() &&
3591          !isValidIndeterminateAccess(handler.AccessKind))) {
3592       if (!Info.checkingPotentialConstantExpression())
3593         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3594             << handler.AccessKind << O->isIndeterminate();
3595       return handler.failed();
3596     }
3597 
3598     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3599     //    const and volatile semantics are not applied on an object under
3600     //    {con,de}struction.
3601     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3602         ObjType->isRecordType() &&
3603         Info.isEvaluatingCtorDtor(
3604             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3605                                          Sub.Entries.begin() + I)) !=
3606                           ConstructionPhase::None) {
3607       ObjType = Info.Ctx.getCanonicalType(ObjType);
3608       ObjType.removeLocalConst();
3609       ObjType.removeLocalVolatile();
3610     }
3611 
3612     // If this is our last pass, check that the final object type is OK.
3613     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3614       // Accesses to volatile objects are prohibited.
3615       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3616         if (Info.getLangOpts().CPlusPlus) {
3617           int DiagKind;
3618           SourceLocation Loc;
3619           const NamedDecl *Decl = nullptr;
3620           if (VolatileField) {
3621             DiagKind = 2;
3622             Loc = VolatileField->getLocation();
3623             Decl = VolatileField;
3624           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3625             DiagKind = 1;
3626             Loc = VD->getLocation();
3627             Decl = VD;
3628           } else {
3629             DiagKind = 0;
3630             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3631               Loc = E->getExprLoc();
3632           }
3633           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3634               << handler.AccessKind << DiagKind << Decl;
3635           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3636         } else {
3637           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3638         }
3639         return handler.failed();
3640       }
3641 
3642       // If we are reading an object of class type, there may still be more
3643       // things we need to check: if there are any mutable subobjects, we
3644       // cannot perform this read. (This only happens when performing a trivial
3645       // copy or assignment.)
3646       if (ObjType->isRecordType() &&
3647           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3648           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3649         return handler.failed();
3650     }
3651 
3652     if (I == N) {
3653       if (!handler.found(*O, ObjType))
3654         return false;
3655 
3656       // If we modified a bit-field, truncate it to the right width.
3657       if (isModification(handler.AccessKind) &&
3658           LastField && LastField->isBitField() &&
3659           !truncateBitfieldValue(Info, E, *O, LastField))
3660         return false;
3661 
3662       return true;
3663     }
3664 
3665     LastField = nullptr;
3666     if (ObjType->isArrayType()) {
3667       // Next subobject is an array element.
3668       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3669       assert(CAT && "vla in literal type?");
3670       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3671       if (CAT->getSize().ule(Index)) {
3672         // Note, it should not be possible to form a pointer with a valid
3673         // designator which points more than one past the end of the array.
3674         if (Info.getLangOpts().CPlusPlus11)
3675           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3676             << handler.AccessKind;
3677         else
3678           Info.FFDiag(E);
3679         return handler.failed();
3680       }
3681 
3682       ObjType = CAT->getElementType();
3683 
3684       if (O->getArrayInitializedElts() > Index)
3685         O = &O->getArrayInitializedElt(Index);
3686       else if (!isRead(handler.AccessKind)) {
3687         expandArray(*O, Index);
3688         O = &O->getArrayInitializedElt(Index);
3689       } else
3690         O = &O->getArrayFiller();
3691     } else if (ObjType->isAnyComplexType()) {
3692       // Next subobject is a complex number.
3693       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3694       if (Index > 1) {
3695         if (Info.getLangOpts().CPlusPlus11)
3696           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3697             << handler.AccessKind;
3698         else
3699           Info.FFDiag(E);
3700         return handler.failed();
3701       }
3702 
3703       ObjType = getSubobjectType(
3704           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3705 
3706       assert(I == N - 1 && "extracting subobject of scalar?");
3707       if (O->isComplexInt()) {
3708         return handler.found(Index ? O->getComplexIntImag()
3709                                    : O->getComplexIntReal(), ObjType);
3710       } else {
3711         assert(O->isComplexFloat());
3712         return handler.found(Index ? O->getComplexFloatImag()
3713                                    : O->getComplexFloatReal(), ObjType);
3714       }
3715     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3716       if (Field->isMutable() &&
3717           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3718         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3719           << handler.AccessKind << Field;
3720         Info.Note(Field->getLocation(), diag::note_declared_at);
3721         return handler.failed();
3722       }
3723 
3724       // Next subobject is a class, struct or union field.
3725       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3726       if (RD->isUnion()) {
3727         const FieldDecl *UnionField = O->getUnionField();
3728         if (!UnionField ||
3729             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3730           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3731             // Placement new onto an inactive union member makes it active.
3732             O->setUnion(Field, APValue());
3733           } else {
3734             // FIXME: If O->getUnionValue() is absent, report that there's no
3735             // active union member rather than reporting the prior active union
3736             // member. We'll need to fix nullptr_t to not use APValue() as its
3737             // representation first.
3738             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3739                 << handler.AccessKind << Field << !UnionField << UnionField;
3740             return handler.failed();
3741           }
3742         }
3743         O = &O->getUnionValue();
3744       } else
3745         O = &O->getStructField(Field->getFieldIndex());
3746 
3747       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3748       LastField = Field;
3749       if (Field->getType().isVolatileQualified())
3750         VolatileField = Field;
3751     } else {
3752       // Next subobject is a base class.
3753       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3754       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3755       O = &O->getStructBase(getBaseIndex(Derived, Base));
3756 
3757       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3758     }
3759   }
3760 }
3761 
3762 namespace {
3763 struct ExtractSubobjectHandler {
3764   EvalInfo &Info;
3765   const Expr *E;
3766   APValue &Result;
3767   const AccessKinds AccessKind;
3768 
3769   typedef bool result_type;
3770   bool failed() { return false; }
3771   bool found(APValue &Subobj, QualType SubobjType) {
3772     Result = Subobj;
3773     if (AccessKind == AK_ReadObjectRepresentation)
3774       return true;
3775     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3776   }
3777   bool found(APSInt &Value, QualType SubobjType) {
3778     Result = APValue(Value);
3779     return true;
3780   }
3781   bool found(APFloat &Value, QualType SubobjType) {
3782     Result = APValue(Value);
3783     return true;
3784   }
3785 };
3786 } // end anonymous namespace
3787 
3788 /// Extract the designated sub-object of an rvalue.
3789 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3790                              const CompleteObject &Obj,
3791                              const SubobjectDesignator &Sub, APValue &Result,
3792                              AccessKinds AK = AK_Read) {
3793   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3794   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3795   return findSubobject(Info, E, Obj, Sub, Handler);
3796 }
3797 
3798 namespace {
3799 struct ModifySubobjectHandler {
3800   EvalInfo &Info;
3801   APValue &NewVal;
3802   const Expr *E;
3803 
3804   typedef bool result_type;
3805   static const AccessKinds AccessKind = AK_Assign;
3806 
3807   bool checkConst(QualType QT) {
3808     // Assigning to a const object has undefined behavior.
3809     if (QT.isConstQualified()) {
3810       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3811       return false;
3812     }
3813     return true;
3814   }
3815 
3816   bool failed() { return false; }
3817   bool found(APValue &Subobj, QualType SubobjType) {
3818     if (!checkConst(SubobjType))
3819       return false;
3820     // We've been given ownership of NewVal, so just swap it in.
3821     Subobj.swap(NewVal);
3822     return true;
3823   }
3824   bool found(APSInt &Value, QualType SubobjType) {
3825     if (!checkConst(SubobjType))
3826       return false;
3827     if (!NewVal.isInt()) {
3828       // Maybe trying to write a cast pointer value into a complex?
3829       Info.FFDiag(E);
3830       return false;
3831     }
3832     Value = NewVal.getInt();
3833     return true;
3834   }
3835   bool found(APFloat &Value, QualType SubobjType) {
3836     if (!checkConst(SubobjType))
3837       return false;
3838     Value = NewVal.getFloat();
3839     return true;
3840   }
3841 };
3842 } // end anonymous namespace
3843 
3844 const AccessKinds ModifySubobjectHandler::AccessKind;
3845 
3846 /// Update the designated sub-object of an rvalue to the given value.
3847 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3848                             const CompleteObject &Obj,
3849                             const SubobjectDesignator &Sub,
3850                             APValue &NewVal) {
3851   ModifySubobjectHandler Handler = { Info, NewVal, E };
3852   return findSubobject(Info, E, Obj, Sub, Handler);
3853 }
3854 
3855 /// Find the position where two subobject designators diverge, or equivalently
3856 /// the length of the common initial subsequence.
3857 static unsigned FindDesignatorMismatch(QualType ObjType,
3858                                        const SubobjectDesignator &A,
3859                                        const SubobjectDesignator &B,
3860                                        bool &WasArrayIndex) {
3861   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3862   for (/**/; I != N; ++I) {
3863     if (!ObjType.isNull() &&
3864         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3865       // Next subobject is an array element.
3866       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3867         WasArrayIndex = true;
3868         return I;
3869       }
3870       if (ObjType->isAnyComplexType())
3871         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3872       else
3873         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3874     } else {
3875       if (A.Entries[I].getAsBaseOrMember() !=
3876           B.Entries[I].getAsBaseOrMember()) {
3877         WasArrayIndex = false;
3878         return I;
3879       }
3880       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3881         // Next subobject is a field.
3882         ObjType = FD->getType();
3883       else
3884         // Next subobject is a base class.
3885         ObjType = QualType();
3886     }
3887   }
3888   WasArrayIndex = false;
3889   return I;
3890 }
3891 
3892 /// Determine whether the given subobject designators refer to elements of the
3893 /// same array object.
3894 static bool AreElementsOfSameArray(QualType ObjType,
3895                                    const SubobjectDesignator &A,
3896                                    const SubobjectDesignator &B) {
3897   if (A.Entries.size() != B.Entries.size())
3898     return false;
3899 
3900   bool IsArray = A.MostDerivedIsArrayElement;
3901   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3902     // A is a subobject of the array element.
3903     return false;
3904 
3905   // If A (and B) designates an array element, the last entry will be the array
3906   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3907   // of length 1' case, and the entire path must match.
3908   bool WasArrayIndex;
3909   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3910   return CommonLength >= A.Entries.size() - IsArray;
3911 }
3912 
3913 /// Find the complete object to which an LValue refers.
3914 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3915                                          AccessKinds AK, const LValue &LVal,
3916                                          QualType LValType) {
3917   if (LVal.InvalidBase) {
3918     Info.FFDiag(E);
3919     return CompleteObject();
3920   }
3921 
3922   if (!LVal.Base) {
3923     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3924     return CompleteObject();
3925   }
3926 
3927   CallStackFrame *Frame = nullptr;
3928   unsigned Depth = 0;
3929   if (LVal.getLValueCallIndex()) {
3930     std::tie(Frame, Depth) =
3931         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3932     if (!Frame) {
3933       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3934         << AK << LVal.Base.is<const ValueDecl*>();
3935       NoteLValueLocation(Info, LVal.Base);
3936       return CompleteObject();
3937     }
3938   }
3939 
3940   bool IsAccess = isAnyAccess(AK);
3941 
3942   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3943   // is not a constant expression (even if the object is non-volatile). We also
3944   // apply this rule to C++98, in order to conform to the expected 'volatile'
3945   // semantics.
3946   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3947     if (Info.getLangOpts().CPlusPlus)
3948       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3949         << AK << LValType;
3950     else
3951       Info.FFDiag(E);
3952     return CompleteObject();
3953   }
3954 
3955   // Compute value storage location and type of base object.
3956   APValue *BaseVal = nullptr;
3957   QualType BaseType = getType(LVal.Base);
3958 
3959   if (const ConstantExpr *CE =
3960           dyn_cast_or_null<ConstantExpr>(LVal.Base.dyn_cast<const Expr *>())) {
3961     /// Nested immediate invocation have been previously removed so if we found
3962     /// a ConstantExpr it can only be the EvaluatingDecl.
3963     assert(CE->isImmediateInvocation() && CE == Info.EvaluatingDecl);
3964     (void)CE;
3965     BaseVal = Info.EvaluatingDeclValue;
3966   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
3967     // Allow reading from a GUID declaration.
3968     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
3969       if (isModification(AK)) {
3970         // All the remaining cases do not permit modification of the object.
3971         Info.FFDiag(E, diag::note_constexpr_modify_global);
3972         return CompleteObject();
3973       }
3974       APValue &V = GD->getAsAPValue();
3975       if (V.isAbsent()) {
3976         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
3977             << GD->getType();
3978         return CompleteObject();
3979       }
3980       return CompleteObject(LVal.Base, &V, GD->getType());
3981     }
3982 
3983     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3984     // In C++11, constexpr, non-volatile variables initialized with constant
3985     // expressions are constant expressions too. Inside constexpr functions,
3986     // parameters are constant expressions even if they're non-const.
3987     // In C++1y, objects local to a constant expression (those with a Frame) are
3988     // both readable and writable inside constant expressions.
3989     // In C, such things can also be folded, although they are not ICEs.
3990     const VarDecl *VD = dyn_cast<VarDecl>(D);
3991     if (VD) {
3992       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3993         VD = VDef;
3994     }
3995     if (!VD || VD->isInvalidDecl()) {
3996       Info.FFDiag(E);
3997       return CompleteObject();
3998     }
3999 
4000     // In OpenCL if a variable is in constant address space it is a const value.
4001     bool IsConstant = BaseType.isConstQualified() ||
4002                       (Info.getLangOpts().OpenCL &&
4003                        BaseType.getAddressSpace() == LangAS::opencl_constant);
4004 
4005     // Unless we're looking at a local variable or argument in a constexpr call,
4006     // the variable we're reading must be const.
4007     if (!Frame) {
4008       if (IsAccess && isa<ParmVarDecl>(VD)) {
4009         // Access of a parameter that's not associated with a frame isn't going
4010         // to work out, but we can leave it to evaluateVarDeclInit to provide a
4011         // suitable diagnostic.
4012       } else if (Info.getLangOpts().CPlusPlus14 &&
4013                  lifetimeStartedInEvaluation(Info, LVal.Base)) {
4014         // OK, we can read and modify an object if we're in the process of
4015         // evaluating its initializer, because its lifetime began in this
4016         // evaluation.
4017       } else if (isModification(AK)) {
4018         // All the remaining cases do not permit modification of the object.
4019         Info.FFDiag(E, diag::note_constexpr_modify_global);
4020         return CompleteObject();
4021       } else if (VD->isConstexpr()) {
4022         // OK, we can read this variable.
4023       } else if (BaseType->isIntegralOrEnumerationType()) {
4024         // In OpenCL if a variable is in constant address space it is a const
4025         // value.
4026         if (!IsConstant) {
4027           if (!IsAccess)
4028             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4029           if (Info.getLangOpts().CPlusPlus) {
4030             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4031             Info.Note(VD->getLocation(), diag::note_declared_at);
4032           } else {
4033             Info.FFDiag(E);
4034           }
4035           return CompleteObject();
4036         }
4037       } else if (!IsAccess) {
4038         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4039       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4040                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4041         // This variable might end up being constexpr. Don't diagnose it yet.
4042       } else if (IsConstant) {
4043         // Keep evaluating to see what we can do. In particular, we support
4044         // folding of const floating-point types, in order to make static const
4045         // data members of such types (supported as an extension) more useful.
4046         if (Info.getLangOpts().CPlusPlus) {
4047           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4048                               ? diag::note_constexpr_ltor_non_constexpr
4049                               : diag::note_constexpr_ltor_non_integral, 1)
4050               << VD << BaseType;
4051           Info.Note(VD->getLocation(), diag::note_declared_at);
4052         } else {
4053           Info.CCEDiag(E);
4054         }
4055       } else {
4056         // Never allow reading a non-const value.
4057         if (Info.getLangOpts().CPlusPlus) {
4058           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4059                              ? diag::note_constexpr_ltor_non_constexpr
4060                              : diag::note_constexpr_ltor_non_integral, 1)
4061               << VD << BaseType;
4062           Info.Note(VD->getLocation(), diag::note_declared_at);
4063         } else {
4064           Info.FFDiag(E);
4065         }
4066         return CompleteObject();
4067       }
4068     }
4069 
4070     if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4071       return CompleteObject();
4072   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4073     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
4074     if (!Alloc) {
4075       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4076       return CompleteObject();
4077     }
4078     return CompleteObject(LVal.Base, &(*Alloc)->Value,
4079                           LVal.Base.getDynamicAllocType());
4080   } else {
4081     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4082 
4083     if (!Frame) {
4084       if (const MaterializeTemporaryExpr *MTE =
4085               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4086         assert(MTE->getStorageDuration() == SD_Static &&
4087                "should have a frame for a non-global materialized temporary");
4088 
4089         // Per C++1y [expr.const]p2:
4090         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4091         //   - a [...] glvalue of integral or enumeration type that refers to
4092         //     a non-volatile const object [...]
4093         //   [...]
4094         //   - a [...] glvalue of literal type that refers to a non-volatile
4095         //     object whose lifetime began within the evaluation of e.
4096         //
4097         // C++11 misses the 'began within the evaluation of e' check and
4098         // instead allows all temporaries, including things like:
4099         //   int &&r = 1;
4100         //   int x = ++r;
4101         //   constexpr int k = r;
4102         // Therefore we use the C++14 rules in C++11 too.
4103         //
4104         // Note that temporaries whose lifetimes began while evaluating a
4105         // variable's constructor are not usable while evaluating the
4106         // corresponding destructor, not even if they're of const-qualified
4107         // types.
4108         if (!(BaseType.isConstQualified() &&
4109               BaseType->isIntegralOrEnumerationType()) &&
4110             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4111           if (!IsAccess)
4112             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4113           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4114           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4115           return CompleteObject();
4116         }
4117 
4118         BaseVal = MTE->getOrCreateValue(false);
4119         assert(BaseVal && "got reference to unevaluated temporary");
4120       } else {
4121         if (!IsAccess)
4122           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4123         APValue Val;
4124         LVal.moveInto(Val);
4125         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4126             << AK
4127             << Val.getAsString(Info.Ctx,
4128                                Info.Ctx.getLValueReferenceType(LValType));
4129         NoteLValueLocation(Info, LVal.Base);
4130         return CompleteObject();
4131       }
4132     } else {
4133       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4134       assert(BaseVal && "missing value for temporary");
4135     }
4136   }
4137 
4138   // In C++14, we can't safely access any mutable state when we might be
4139   // evaluating after an unmodeled side effect. Parameters are modeled as state
4140   // in the caller, but aren't visible once the call returns, so they can be
4141   // modified in a speculatively-evaluated call.
4142   //
4143   // FIXME: Not all local state is mutable. Allow local constant subobjects
4144   // to be read here (but take care with 'mutable' fields).
4145   unsigned VisibleDepth = Depth;
4146   if (llvm::isa_and_nonnull<ParmVarDecl>(
4147           LVal.Base.dyn_cast<const ValueDecl *>()))
4148     ++VisibleDepth;
4149   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4150        Info.EvalStatus.HasSideEffects) ||
4151       (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4152     return CompleteObject();
4153 
4154   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4155 }
4156 
4157 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4158 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4159 /// glvalue referred to by an entity of reference type.
4160 ///
4161 /// \param Info - Information about the ongoing evaluation.
4162 /// \param Conv - The expression for which we are performing the conversion.
4163 ///               Used for diagnostics.
4164 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4165 ///               case of a non-class type).
4166 /// \param LVal - The glvalue on which we are attempting to perform this action.
4167 /// \param RVal - The produced value will be placed here.
4168 /// \param WantObjectRepresentation - If true, we're looking for the object
4169 ///               representation rather than the value, and in particular,
4170 ///               there is no requirement that the result be fully initialized.
4171 static bool
4172 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4173                                const LValue &LVal, APValue &RVal,
4174                                bool WantObjectRepresentation = false) {
4175   if (LVal.Designator.Invalid)
4176     return false;
4177 
4178   // Check for special cases where there is no existing APValue to look at.
4179   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4180 
4181   AccessKinds AK =
4182       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4183 
4184   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4185     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4186       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4187       // initializer until now for such expressions. Such an expression can't be
4188       // an ICE in C, so this only matters for fold.
4189       if (Type.isVolatileQualified()) {
4190         Info.FFDiag(Conv);
4191         return false;
4192       }
4193       APValue Lit;
4194       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4195         return false;
4196       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4197       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4198     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4199       // Special-case character extraction so we don't have to construct an
4200       // APValue for the whole string.
4201       assert(LVal.Designator.Entries.size() <= 1 &&
4202              "Can only read characters from string literals");
4203       if (LVal.Designator.Entries.empty()) {
4204         // Fail for now for LValue to RValue conversion of an array.
4205         // (This shouldn't show up in C/C++, but it could be triggered by a
4206         // weird EvaluateAsRValue call from a tool.)
4207         Info.FFDiag(Conv);
4208         return false;
4209       }
4210       if (LVal.Designator.isOnePastTheEnd()) {
4211         if (Info.getLangOpts().CPlusPlus11)
4212           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4213         else
4214           Info.FFDiag(Conv);
4215         return false;
4216       }
4217       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4218       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4219       return true;
4220     }
4221   }
4222 
4223   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4224   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4225 }
4226 
4227 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4228 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4229                              QualType LValType, APValue &Val) {
4230   if (LVal.Designator.Invalid)
4231     return false;
4232 
4233   if (!Info.getLangOpts().CPlusPlus14) {
4234     Info.FFDiag(E);
4235     return false;
4236   }
4237 
4238   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4239   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4240 }
4241 
4242 namespace {
4243 struct CompoundAssignSubobjectHandler {
4244   EvalInfo &Info;
4245   const CompoundAssignOperator *E;
4246   QualType PromotedLHSType;
4247   BinaryOperatorKind Opcode;
4248   const APValue &RHS;
4249 
4250   static const AccessKinds AccessKind = AK_Assign;
4251 
4252   typedef bool result_type;
4253 
4254   bool checkConst(QualType QT) {
4255     // Assigning to a const object has undefined behavior.
4256     if (QT.isConstQualified()) {
4257       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4258       return false;
4259     }
4260     return true;
4261   }
4262 
4263   bool failed() { return false; }
4264   bool found(APValue &Subobj, QualType SubobjType) {
4265     switch (Subobj.getKind()) {
4266     case APValue::Int:
4267       return found(Subobj.getInt(), SubobjType);
4268     case APValue::Float:
4269       return found(Subobj.getFloat(), SubobjType);
4270     case APValue::ComplexInt:
4271     case APValue::ComplexFloat:
4272       // FIXME: Implement complex compound assignment.
4273       Info.FFDiag(E);
4274       return false;
4275     case APValue::LValue:
4276       return foundPointer(Subobj, SubobjType);
4277     case APValue::Vector:
4278       return foundVector(Subobj, SubobjType);
4279     default:
4280       // FIXME: can this happen?
4281       Info.FFDiag(E);
4282       return false;
4283     }
4284   }
4285 
4286   bool foundVector(APValue &Value, QualType SubobjType) {
4287     if (!checkConst(SubobjType))
4288       return false;
4289 
4290     if (!SubobjType->isVectorType()) {
4291       Info.FFDiag(E);
4292       return false;
4293     }
4294     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4295   }
4296 
4297   bool found(APSInt &Value, QualType SubobjType) {
4298     if (!checkConst(SubobjType))
4299       return false;
4300 
4301     if (!SubobjType->isIntegerType()) {
4302       // We don't support compound assignment on integer-cast-to-pointer
4303       // values.
4304       Info.FFDiag(E);
4305       return false;
4306     }
4307 
4308     if (RHS.isInt()) {
4309       APSInt LHS =
4310           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4311       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4312         return false;
4313       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4314       return true;
4315     } else if (RHS.isFloat()) {
4316       APFloat FValue(0.0);
4317       return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
4318                                   FValue) &&
4319              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4320              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4321                                   Value);
4322     }
4323 
4324     Info.FFDiag(E);
4325     return false;
4326   }
4327   bool found(APFloat &Value, QualType SubobjType) {
4328     return checkConst(SubobjType) &&
4329            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4330                                   Value) &&
4331            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4332            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4333   }
4334   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4335     if (!checkConst(SubobjType))
4336       return false;
4337 
4338     QualType PointeeType;
4339     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4340       PointeeType = PT->getPointeeType();
4341 
4342     if (PointeeType.isNull() || !RHS.isInt() ||
4343         (Opcode != BO_Add && Opcode != BO_Sub)) {
4344       Info.FFDiag(E);
4345       return false;
4346     }
4347 
4348     APSInt Offset = RHS.getInt();
4349     if (Opcode == BO_Sub)
4350       negateAsSigned(Offset);
4351 
4352     LValue LVal;
4353     LVal.setFrom(Info.Ctx, Subobj);
4354     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4355       return false;
4356     LVal.moveInto(Subobj);
4357     return true;
4358   }
4359 };
4360 } // end anonymous namespace
4361 
4362 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4363 
4364 /// Perform a compound assignment of LVal <op>= RVal.
4365 static bool handleCompoundAssignment(EvalInfo &Info,
4366                                      const CompoundAssignOperator *E,
4367                                      const LValue &LVal, QualType LValType,
4368                                      QualType PromotedLValType,
4369                                      BinaryOperatorKind Opcode,
4370                                      const APValue &RVal) {
4371   if (LVal.Designator.Invalid)
4372     return false;
4373 
4374   if (!Info.getLangOpts().CPlusPlus14) {
4375     Info.FFDiag(E);
4376     return false;
4377   }
4378 
4379   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4380   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4381                                              RVal };
4382   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4383 }
4384 
4385 namespace {
4386 struct IncDecSubobjectHandler {
4387   EvalInfo &Info;
4388   const UnaryOperator *E;
4389   AccessKinds AccessKind;
4390   APValue *Old;
4391 
4392   typedef bool result_type;
4393 
4394   bool checkConst(QualType QT) {
4395     // Assigning to a const object has undefined behavior.
4396     if (QT.isConstQualified()) {
4397       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4398       return false;
4399     }
4400     return true;
4401   }
4402 
4403   bool failed() { return false; }
4404   bool found(APValue &Subobj, QualType SubobjType) {
4405     // Stash the old value. Also clear Old, so we don't clobber it later
4406     // if we're post-incrementing a complex.
4407     if (Old) {
4408       *Old = Subobj;
4409       Old = nullptr;
4410     }
4411 
4412     switch (Subobj.getKind()) {
4413     case APValue::Int:
4414       return found(Subobj.getInt(), SubobjType);
4415     case APValue::Float:
4416       return found(Subobj.getFloat(), SubobjType);
4417     case APValue::ComplexInt:
4418       return found(Subobj.getComplexIntReal(),
4419                    SubobjType->castAs<ComplexType>()->getElementType()
4420                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4421     case APValue::ComplexFloat:
4422       return found(Subobj.getComplexFloatReal(),
4423                    SubobjType->castAs<ComplexType>()->getElementType()
4424                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4425     case APValue::LValue:
4426       return foundPointer(Subobj, SubobjType);
4427     default:
4428       // FIXME: can this happen?
4429       Info.FFDiag(E);
4430       return false;
4431     }
4432   }
4433   bool found(APSInt &Value, QualType SubobjType) {
4434     if (!checkConst(SubobjType))
4435       return false;
4436 
4437     if (!SubobjType->isIntegerType()) {
4438       // We don't support increment / decrement on integer-cast-to-pointer
4439       // values.
4440       Info.FFDiag(E);
4441       return false;
4442     }
4443 
4444     if (Old) *Old = APValue(Value);
4445 
4446     // bool arithmetic promotes to int, and the conversion back to bool
4447     // doesn't reduce mod 2^n, so special-case it.
4448     if (SubobjType->isBooleanType()) {
4449       if (AccessKind == AK_Increment)
4450         Value = 1;
4451       else
4452         Value = !Value;
4453       return true;
4454     }
4455 
4456     bool WasNegative = Value.isNegative();
4457     if (AccessKind == AK_Increment) {
4458       ++Value;
4459 
4460       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4461         APSInt ActualValue(Value, /*IsUnsigned*/true);
4462         return HandleOverflow(Info, E, ActualValue, SubobjType);
4463       }
4464     } else {
4465       --Value;
4466 
4467       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4468         unsigned BitWidth = Value.getBitWidth();
4469         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4470         ActualValue.setBit(BitWidth);
4471         return HandleOverflow(Info, E, ActualValue, SubobjType);
4472       }
4473     }
4474     return true;
4475   }
4476   bool found(APFloat &Value, QualType SubobjType) {
4477     if (!checkConst(SubobjType))
4478       return false;
4479 
4480     if (Old) *Old = APValue(Value);
4481 
4482     APFloat One(Value.getSemantics(), 1);
4483     if (AccessKind == AK_Increment)
4484       Value.add(One, APFloat::rmNearestTiesToEven);
4485     else
4486       Value.subtract(One, APFloat::rmNearestTiesToEven);
4487     return true;
4488   }
4489   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4490     if (!checkConst(SubobjType))
4491       return false;
4492 
4493     QualType PointeeType;
4494     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4495       PointeeType = PT->getPointeeType();
4496     else {
4497       Info.FFDiag(E);
4498       return false;
4499     }
4500 
4501     LValue LVal;
4502     LVal.setFrom(Info.Ctx, Subobj);
4503     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4504                                      AccessKind == AK_Increment ? 1 : -1))
4505       return false;
4506     LVal.moveInto(Subobj);
4507     return true;
4508   }
4509 };
4510 } // end anonymous namespace
4511 
4512 /// Perform an increment or decrement on LVal.
4513 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4514                          QualType LValType, bool IsIncrement, APValue *Old) {
4515   if (LVal.Designator.Invalid)
4516     return false;
4517 
4518   if (!Info.getLangOpts().CPlusPlus14) {
4519     Info.FFDiag(E);
4520     return false;
4521   }
4522 
4523   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4524   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4525   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4526   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4527 }
4528 
4529 /// Build an lvalue for the object argument of a member function call.
4530 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4531                                    LValue &This) {
4532   if (Object->getType()->isPointerType() && Object->isRValue())
4533     return EvaluatePointer(Object, This, Info);
4534 
4535   if (Object->isGLValue())
4536     return EvaluateLValue(Object, This, Info);
4537 
4538   if (Object->getType()->isLiteralType(Info.Ctx))
4539     return EvaluateTemporary(Object, This, Info);
4540 
4541   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4542   return false;
4543 }
4544 
4545 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4546 /// lvalue referring to the result.
4547 ///
4548 /// \param Info - Information about the ongoing evaluation.
4549 /// \param LV - An lvalue referring to the base of the member pointer.
4550 /// \param RHS - The member pointer expression.
4551 /// \param IncludeMember - Specifies whether the member itself is included in
4552 ///        the resulting LValue subobject designator. This is not possible when
4553 ///        creating a bound member function.
4554 /// \return The field or method declaration to which the member pointer refers,
4555 ///         or 0 if evaluation fails.
4556 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4557                                                   QualType LVType,
4558                                                   LValue &LV,
4559                                                   const Expr *RHS,
4560                                                   bool IncludeMember = true) {
4561   MemberPtr MemPtr;
4562   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4563     return nullptr;
4564 
4565   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4566   // member value, the behavior is undefined.
4567   if (!MemPtr.getDecl()) {
4568     // FIXME: Specific diagnostic.
4569     Info.FFDiag(RHS);
4570     return nullptr;
4571   }
4572 
4573   if (MemPtr.isDerivedMember()) {
4574     // This is a member of some derived class. Truncate LV appropriately.
4575     // The end of the derived-to-base path for the base object must match the
4576     // derived-to-base path for the member pointer.
4577     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4578         LV.Designator.Entries.size()) {
4579       Info.FFDiag(RHS);
4580       return nullptr;
4581     }
4582     unsigned PathLengthToMember =
4583         LV.Designator.Entries.size() - MemPtr.Path.size();
4584     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4585       const CXXRecordDecl *LVDecl = getAsBaseClass(
4586           LV.Designator.Entries[PathLengthToMember + I]);
4587       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4588       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4589         Info.FFDiag(RHS);
4590         return nullptr;
4591       }
4592     }
4593 
4594     // Truncate the lvalue to the appropriate derived class.
4595     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4596                             PathLengthToMember))
4597       return nullptr;
4598   } else if (!MemPtr.Path.empty()) {
4599     // Extend the LValue path with the member pointer's path.
4600     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4601                                   MemPtr.Path.size() + IncludeMember);
4602 
4603     // Walk down to the appropriate base class.
4604     if (const PointerType *PT = LVType->getAs<PointerType>())
4605       LVType = PT->getPointeeType();
4606     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4607     assert(RD && "member pointer access on non-class-type expression");
4608     // The first class in the path is that of the lvalue.
4609     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4610       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4611       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4612         return nullptr;
4613       RD = Base;
4614     }
4615     // Finally cast to the class containing the member.
4616     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4617                                 MemPtr.getContainingRecord()))
4618       return nullptr;
4619   }
4620 
4621   // Add the member. Note that we cannot build bound member functions here.
4622   if (IncludeMember) {
4623     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4624       if (!HandleLValueMember(Info, RHS, LV, FD))
4625         return nullptr;
4626     } else if (const IndirectFieldDecl *IFD =
4627                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4628       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4629         return nullptr;
4630     } else {
4631       llvm_unreachable("can't construct reference to bound member function");
4632     }
4633   }
4634 
4635   return MemPtr.getDecl();
4636 }
4637 
4638 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4639                                                   const BinaryOperator *BO,
4640                                                   LValue &LV,
4641                                                   bool IncludeMember = true) {
4642   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4643 
4644   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4645     if (Info.noteFailure()) {
4646       MemberPtr MemPtr;
4647       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4648     }
4649     return nullptr;
4650   }
4651 
4652   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4653                                    BO->getRHS(), IncludeMember);
4654 }
4655 
4656 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4657 /// the provided lvalue, which currently refers to the base object.
4658 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4659                                     LValue &Result) {
4660   SubobjectDesignator &D = Result.Designator;
4661   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4662     return false;
4663 
4664   QualType TargetQT = E->getType();
4665   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4666     TargetQT = PT->getPointeeType();
4667 
4668   // Check this cast lands within the final derived-to-base subobject path.
4669   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4670     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4671       << D.MostDerivedType << TargetQT;
4672     return false;
4673   }
4674 
4675   // Check the type of the final cast. We don't need to check the path,
4676   // since a cast can only be formed if the path is unique.
4677   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4678   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4679   const CXXRecordDecl *FinalType;
4680   if (NewEntriesSize == D.MostDerivedPathLength)
4681     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4682   else
4683     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4684   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4685     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4686       << D.MostDerivedType << TargetQT;
4687     return false;
4688   }
4689 
4690   // Truncate the lvalue to the appropriate derived class.
4691   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4692 }
4693 
4694 /// Get the value to use for a default-initialized object of type T.
4695 /// Return false if it encounters something invalid.
4696 static bool getDefaultInitValue(QualType T, APValue &Result) {
4697   bool Success = true;
4698   if (auto *RD = T->getAsCXXRecordDecl()) {
4699     if (RD->isInvalidDecl()) {
4700       Result = APValue();
4701       return false;
4702     }
4703     if (RD->isUnion()) {
4704       Result = APValue((const FieldDecl *)nullptr);
4705       return true;
4706     }
4707     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4708                      std::distance(RD->field_begin(), RD->field_end()));
4709 
4710     unsigned Index = 0;
4711     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4712                                                   End = RD->bases_end();
4713          I != End; ++I, ++Index)
4714       Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4715 
4716     for (const auto *I : RD->fields()) {
4717       if (I->isUnnamedBitfield())
4718         continue;
4719       Success &= getDefaultInitValue(I->getType(),
4720                                      Result.getStructField(I->getFieldIndex()));
4721     }
4722     return Success;
4723   }
4724 
4725   if (auto *AT =
4726           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4727     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4728     if (Result.hasArrayFiller())
4729       Success &=
4730           getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4731 
4732     return Success;
4733   }
4734 
4735   Result = APValue::IndeterminateValue();
4736   return true;
4737 }
4738 
4739 namespace {
4740 enum EvalStmtResult {
4741   /// Evaluation failed.
4742   ESR_Failed,
4743   /// Hit a 'return' statement.
4744   ESR_Returned,
4745   /// Evaluation succeeded.
4746   ESR_Succeeded,
4747   /// Hit a 'continue' statement.
4748   ESR_Continue,
4749   /// Hit a 'break' statement.
4750   ESR_Break,
4751   /// Still scanning for 'case' or 'default' statement.
4752   ESR_CaseNotFound
4753 };
4754 }
4755 
4756 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4757   // We don't need to evaluate the initializer for a static local.
4758   if (!VD->hasLocalStorage())
4759     return true;
4760 
4761   LValue Result;
4762   APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4763                                                    ScopeKind::Block, Result);
4764 
4765   const Expr *InitE = VD->getInit();
4766   if (!InitE)
4767     return getDefaultInitValue(VD->getType(), Val);
4768 
4769   if (InitE->isValueDependent())
4770     return false;
4771 
4772   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4773     // Wipe out any partially-computed value, to allow tracking that this
4774     // evaluation failed.
4775     Val = APValue();
4776     return false;
4777   }
4778 
4779   return true;
4780 }
4781 
4782 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4783   bool OK = true;
4784 
4785   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4786     OK &= EvaluateVarDecl(Info, VD);
4787 
4788   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4789     for (auto *BD : DD->bindings())
4790       if (auto *VD = BD->getHoldingVar())
4791         OK &= EvaluateDecl(Info, VD);
4792 
4793   return OK;
4794 }
4795 
4796 
4797 /// Evaluate a condition (either a variable declaration or an expression).
4798 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4799                          const Expr *Cond, bool &Result) {
4800   FullExpressionRAII Scope(Info);
4801   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4802     return false;
4803   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4804     return false;
4805   return Scope.destroy();
4806 }
4807 
4808 namespace {
4809 /// A location where the result (returned value) of evaluating a
4810 /// statement should be stored.
4811 struct StmtResult {
4812   /// The APValue that should be filled in with the returned value.
4813   APValue &Value;
4814   /// The location containing the result, if any (used to support RVO).
4815   const LValue *Slot;
4816 };
4817 
4818 struct TempVersionRAII {
4819   CallStackFrame &Frame;
4820 
4821   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4822     Frame.pushTempVersion();
4823   }
4824 
4825   ~TempVersionRAII() {
4826     Frame.popTempVersion();
4827   }
4828 };
4829 
4830 }
4831 
4832 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4833                                    const Stmt *S,
4834                                    const SwitchCase *SC = nullptr);
4835 
4836 /// Evaluate the body of a loop, and translate the result as appropriate.
4837 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4838                                        const Stmt *Body,
4839                                        const SwitchCase *Case = nullptr) {
4840   BlockScopeRAII Scope(Info);
4841 
4842   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4843   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4844     ESR = ESR_Failed;
4845 
4846   switch (ESR) {
4847   case ESR_Break:
4848     return ESR_Succeeded;
4849   case ESR_Succeeded:
4850   case ESR_Continue:
4851     return ESR_Continue;
4852   case ESR_Failed:
4853   case ESR_Returned:
4854   case ESR_CaseNotFound:
4855     return ESR;
4856   }
4857   llvm_unreachable("Invalid EvalStmtResult!");
4858 }
4859 
4860 /// Evaluate a switch statement.
4861 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4862                                      const SwitchStmt *SS) {
4863   BlockScopeRAII Scope(Info);
4864 
4865   // Evaluate the switch condition.
4866   APSInt Value;
4867   {
4868     if (const Stmt *Init = SS->getInit()) {
4869       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4870       if (ESR != ESR_Succeeded) {
4871         if (ESR != ESR_Failed && !Scope.destroy())
4872           ESR = ESR_Failed;
4873         return ESR;
4874       }
4875     }
4876 
4877     FullExpressionRAII CondScope(Info);
4878     if (SS->getConditionVariable() &&
4879         !EvaluateDecl(Info, SS->getConditionVariable()))
4880       return ESR_Failed;
4881     if (!EvaluateInteger(SS->getCond(), Value, Info))
4882       return ESR_Failed;
4883     if (!CondScope.destroy())
4884       return ESR_Failed;
4885   }
4886 
4887   // Find the switch case corresponding to the value of the condition.
4888   // FIXME: Cache this lookup.
4889   const SwitchCase *Found = nullptr;
4890   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4891        SC = SC->getNextSwitchCase()) {
4892     if (isa<DefaultStmt>(SC)) {
4893       Found = SC;
4894       continue;
4895     }
4896 
4897     const CaseStmt *CS = cast<CaseStmt>(SC);
4898     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4899     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4900                               : LHS;
4901     if (LHS <= Value && Value <= RHS) {
4902       Found = SC;
4903       break;
4904     }
4905   }
4906 
4907   if (!Found)
4908     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4909 
4910   // Search the switch body for the switch case and evaluate it from there.
4911   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4912   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4913     return ESR_Failed;
4914 
4915   switch (ESR) {
4916   case ESR_Break:
4917     return ESR_Succeeded;
4918   case ESR_Succeeded:
4919   case ESR_Continue:
4920   case ESR_Failed:
4921   case ESR_Returned:
4922     return ESR;
4923   case ESR_CaseNotFound:
4924     // This can only happen if the switch case is nested within a statement
4925     // expression. We have no intention of supporting that.
4926     Info.FFDiag(Found->getBeginLoc(),
4927                 diag::note_constexpr_stmt_expr_unsupported);
4928     return ESR_Failed;
4929   }
4930   llvm_unreachable("Invalid EvalStmtResult!");
4931 }
4932 
4933 // Evaluate a statement.
4934 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4935                                    const Stmt *S, const SwitchCase *Case) {
4936   if (!Info.nextStep(S))
4937     return ESR_Failed;
4938 
4939   // If we're hunting down a 'case' or 'default' label, recurse through
4940   // substatements until we hit the label.
4941   if (Case) {
4942     switch (S->getStmtClass()) {
4943     case Stmt::CompoundStmtClass:
4944       // FIXME: Precompute which substatement of a compound statement we
4945       // would jump to, and go straight there rather than performing a
4946       // linear scan each time.
4947     case Stmt::LabelStmtClass:
4948     case Stmt::AttributedStmtClass:
4949     case Stmt::DoStmtClass:
4950       break;
4951 
4952     case Stmt::CaseStmtClass:
4953     case Stmt::DefaultStmtClass:
4954       if (Case == S)
4955         Case = nullptr;
4956       break;
4957 
4958     case Stmt::IfStmtClass: {
4959       // FIXME: Precompute which side of an 'if' we would jump to, and go
4960       // straight there rather than scanning both sides.
4961       const IfStmt *IS = cast<IfStmt>(S);
4962 
4963       // Wrap the evaluation in a block scope, in case it's a DeclStmt
4964       // preceded by our switch label.
4965       BlockScopeRAII Scope(Info);
4966 
4967       // Step into the init statement in case it brings an (uninitialized)
4968       // variable into scope.
4969       if (const Stmt *Init = IS->getInit()) {
4970         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
4971         if (ESR != ESR_CaseNotFound) {
4972           assert(ESR != ESR_Succeeded);
4973           return ESR;
4974         }
4975       }
4976 
4977       // Condition variable must be initialized if it exists.
4978       // FIXME: We can skip evaluating the body if there's a condition
4979       // variable, as there can't be any case labels within it.
4980       // (The same is true for 'for' statements.)
4981 
4982       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4983       if (ESR == ESR_Failed)
4984         return ESR;
4985       if (ESR != ESR_CaseNotFound)
4986         return Scope.destroy() ? ESR : ESR_Failed;
4987       if (!IS->getElse())
4988         return ESR_CaseNotFound;
4989 
4990       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
4991       if (ESR == ESR_Failed)
4992         return ESR;
4993       if (ESR != ESR_CaseNotFound)
4994         return Scope.destroy() ? ESR : ESR_Failed;
4995       return ESR_CaseNotFound;
4996     }
4997 
4998     case Stmt::WhileStmtClass: {
4999       EvalStmtResult ESR =
5000           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5001       if (ESR != ESR_Continue)
5002         return ESR;
5003       break;
5004     }
5005 
5006     case Stmt::ForStmtClass: {
5007       const ForStmt *FS = cast<ForStmt>(S);
5008       BlockScopeRAII Scope(Info);
5009 
5010       // Step into the init statement in case it brings an (uninitialized)
5011       // variable into scope.
5012       if (const Stmt *Init = FS->getInit()) {
5013         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5014         if (ESR != ESR_CaseNotFound) {
5015           assert(ESR != ESR_Succeeded);
5016           return ESR;
5017         }
5018       }
5019 
5020       EvalStmtResult ESR =
5021           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5022       if (ESR != ESR_Continue)
5023         return ESR;
5024       if (FS->getInc()) {
5025         FullExpressionRAII IncScope(Info);
5026         if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
5027           return ESR_Failed;
5028       }
5029       break;
5030     }
5031 
5032     case Stmt::DeclStmtClass: {
5033       // Start the lifetime of any uninitialized variables we encounter. They
5034       // might be used by the selected branch of the switch.
5035       const DeclStmt *DS = cast<DeclStmt>(S);
5036       for (const auto *D : DS->decls()) {
5037         if (const auto *VD = dyn_cast<VarDecl>(D)) {
5038           if (VD->hasLocalStorage() && !VD->getInit())
5039             if (!EvaluateVarDecl(Info, VD))
5040               return ESR_Failed;
5041           // FIXME: If the variable has initialization that can't be jumped
5042           // over, bail out of any immediately-surrounding compound-statement
5043           // too. There can't be any case labels here.
5044         }
5045       }
5046       return ESR_CaseNotFound;
5047     }
5048 
5049     default:
5050       return ESR_CaseNotFound;
5051     }
5052   }
5053 
5054   switch (S->getStmtClass()) {
5055   default:
5056     if (const Expr *E = dyn_cast<Expr>(S)) {
5057       // Don't bother evaluating beyond an expression-statement which couldn't
5058       // be evaluated.
5059       // FIXME: Do we need the FullExpressionRAII object here?
5060       // VisitExprWithCleanups should create one when necessary.
5061       FullExpressionRAII Scope(Info);
5062       if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5063         return ESR_Failed;
5064       return ESR_Succeeded;
5065     }
5066 
5067     Info.FFDiag(S->getBeginLoc());
5068     return ESR_Failed;
5069 
5070   case Stmt::NullStmtClass:
5071     return ESR_Succeeded;
5072 
5073   case Stmt::DeclStmtClass: {
5074     const DeclStmt *DS = cast<DeclStmt>(S);
5075     for (const auto *D : DS->decls()) {
5076       // Each declaration initialization is its own full-expression.
5077       FullExpressionRAII Scope(Info);
5078       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5079         return ESR_Failed;
5080       if (!Scope.destroy())
5081         return ESR_Failed;
5082     }
5083     return ESR_Succeeded;
5084   }
5085 
5086   case Stmt::ReturnStmtClass: {
5087     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5088     FullExpressionRAII Scope(Info);
5089     if (RetExpr &&
5090         !(Result.Slot
5091               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5092               : Evaluate(Result.Value, Info, RetExpr)))
5093       return ESR_Failed;
5094     return Scope.destroy() ? ESR_Returned : ESR_Failed;
5095   }
5096 
5097   case Stmt::CompoundStmtClass: {
5098     BlockScopeRAII Scope(Info);
5099 
5100     const CompoundStmt *CS = cast<CompoundStmt>(S);
5101     for (const auto *BI : CS->body()) {
5102       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5103       if (ESR == ESR_Succeeded)
5104         Case = nullptr;
5105       else if (ESR != ESR_CaseNotFound) {
5106         if (ESR != ESR_Failed && !Scope.destroy())
5107           return ESR_Failed;
5108         return ESR;
5109       }
5110     }
5111     if (Case)
5112       return ESR_CaseNotFound;
5113     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5114   }
5115 
5116   case Stmt::IfStmtClass: {
5117     const IfStmt *IS = cast<IfStmt>(S);
5118 
5119     // Evaluate the condition, as either a var decl or as an expression.
5120     BlockScopeRAII Scope(Info);
5121     if (const Stmt *Init = IS->getInit()) {
5122       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5123       if (ESR != ESR_Succeeded) {
5124         if (ESR != ESR_Failed && !Scope.destroy())
5125           return ESR_Failed;
5126         return ESR;
5127       }
5128     }
5129     bool Cond;
5130     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
5131       return ESR_Failed;
5132 
5133     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5134       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5135       if (ESR != ESR_Succeeded) {
5136         if (ESR != ESR_Failed && !Scope.destroy())
5137           return ESR_Failed;
5138         return ESR;
5139       }
5140     }
5141     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5142   }
5143 
5144   case Stmt::WhileStmtClass: {
5145     const WhileStmt *WS = cast<WhileStmt>(S);
5146     while (true) {
5147       BlockScopeRAII Scope(Info);
5148       bool Continue;
5149       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5150                         Continue))
5151         return ESR_Failed;
5152       if (!Continue)
5153         break;
5154 
5155       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5156       if (ESR != ESR_Continue) {
5157         if (ESR != ESR_Failed && !Scope.destroy())
5158           return ESR_Failed;
5159         return ESR;
5160       }
5161       if (!Scope.destroy())
5162         return ESR_Failed;
5163     }
5164     return ESR_Succeeded;
5165   }
5166 
5167   case Stmt::DoStmtClass: {
5168     const DoStmt *DS = cast<DoStmt>(S);
5169     bool Continue;
5170     do {
5171       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5172       if (ESR != ESR_Continue)
5173         return ESR;
5174       Case = nullptr;
5175 
5176       FullExpressionRAII CondScope(Info);
5177       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5178           !CondScope.destroy())
5179         return ESR_Failed;
5180     } while (Continue);
5181     return ESR_Succeeded;
5182   }
5183 
5184   case Stmt::ForStmtClass: {
5185     const ForStmt *FS = cast<ForStmt>(S);
5186     BlockScopeRAII ForScope(Info);
5187     if (FS->getInit()) {
5188       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5189       if (ESR != ESR_Succeeded) {
5190         if (ESR != ESR_Failed && !ForScope.destroy())
5191           return ESR_Failed;
5192         return ESR;
5193       }
5194     }
5195     while (true) {
5196       BlockScopeRAII IterScope(Info);
5197       bool Continue = true;
5198       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5199                                          FS->getCond(), Continue))
5200         return ESR_Failed;
5201       if (!Continue)
5202         break;
5203 
5204       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5205       if (ESR != ESR_Continue) {
5206         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5207           return ESR_Failed;
5208         return ESR;
5209       }
5210 
5211       if (FS->getInc()) {
5212         FullExpressionRAII IncScope(Info);
5213         if (!EvaluateIgnoredValue(Info, FS->getInc()) || !IncScope.destroy())
5214           return ESR_Failed;
5215       }
5216 
5217       if (!IterScope.destroy())
5218         return ESR_Failed;
5219     }
5220     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5221   }
5222 
5223   case Stmt::CXXForRangeStmtClass: {
5224     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5225     BlockScopeRAII Scope(Info);
5226 
5227     // Evaluate the init-statement if present.
5228     if (FS->getInit()) {
5229       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5230       if (ESR != ESR_Succeeded) {
5231         if (ESR != ESR_Failed && !Scope.destroy())
5232           return ESR_Failed;
5233         return ESR;
5234       }
5235     }
5236 
5237     // Initialize the __range variable.
5238     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5239     if (ESR != ESR_Succeeded) {
5240       if (ESR != ESR_Failed && !Scope.destroy())
5241         return ESR_Failed;
5242       return ESR;
5243     }
5244 
5245     // Create the __begin and __end iterators.
5246     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5247     if (ESR != ESR_Succeeded) {
5248       if (ESR != ESR_Failed && !Scope.destroy())
5249         return ESR_Failed;
5250       return ESR;
5251     }
5252     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5253     if (ESR != ESR_Succeeded) {
5254       if (ESR != ESR_Failed && !Scope.destroy())
5255         return ESR_Failed;
5256       return ESR;
5257     }
5258 
5259     while (true) {
5260       // Condition: __begin != __end.
5261       {
5262         bool Continue = true;
5263         FullExpressionRAII CondExpr(Info);
5264         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5265           return ESR_Failed;
5266         if (!Continue)
5267           break;
5268       }
5269 
5270       // User's variable declaration, initialized by *__begin.
5271       BlockScopeRAII InnerScope(Info);
5272       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5273       if (ESR != ESR_Succeeded) {
5274         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5275           return ESR_Failed;
5276         return ESR;
5277       }
5278 
5279       // Loop body.
5280       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5281       if (ESR != ESR_Continue) {
5282         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5283           return ESR_Failed;
5284         return ESR;
5285       }
5286 
5287       // Increment: ++__begin
5288       if (!EvaluateIgnoredValue(Info, FS->getInc()))
5289         return ESR_Failed;
5290 
5291       if (!InnerScope.destroy())
5292         return ESR_Failed;
5293     }
5294 
5295     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5296   }
5297 
5298   case Stmt::SwitchStmtClass:
5299     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5300 
5301   case Stmt::ContinueStmtClass:
5302     return ESR_Continue;
5303 
5304   case Stmt::BreakStmtClass:
5305     return ESR_Break;
5306 
5307   case Stmt::LabelStmtClass:
5308     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5309 
5310   case Stmt::AttributedStmtClass:
5311     // As a general principle, C++11 attributes can be ignored without
5312     // any semantic impact.
5313     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5314                         Case);
5315 
5316   case Stmt::CaseStmtClass:
5317   case Stmt::DefaultStmtClass:
5318     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5319   case Stmt::CXXTryStmtClass:
5320     // Evaluate try blocks by evaluating all sub statements.
5321     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5322   }
5323 }
5324 
5325 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5326 /// default constructor. If so, we'll fold it whether or not it's marked as
5327 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5328 /// so we need special handling.
5329 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5330                                            const CXXConstructorDecl *CD,
5331                                            bool IsValueInitialization) {
5332   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5333     return false;
5334 
5335   // Value-initialization does not call a trivial default constructor, so such a
5336   // call is a core constant expression whether or not the constructor is
5337   // constexpr.
5338   if (!CD->isConstexpr() && !IsValueInitialization) {
5339     if (Info.getLangOpts().CPlusPlus11) {
5340       // FIXME: If DiagDecl is an implicitly-declared special member function,
5341       // we should be much more explicit about why it's not constexpr.
5342       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5343         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5344       Info.Note(CD->getLocation(), diag::note_declared_at);
5345     } else {
5346       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5347     }
5348   }
5349   return true;
5350 }
5351 
5352 /// CheckConstexprFunction - Check that a function can be called in a constant
5353 /// expression.
5354 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5355                                    const FunctionDecl *Declaration,
5356                                    const FunctionDecl *Definition,
5357                                    const Stmt *Body) {
5358   // Potential constant expressions can contain calls to declared, but not yet
5359   // defined, constexpr functions.
5360   if (Info.checkingPotentialConstantExpression() && !Definition &&
5361       Declaration->isConstexpr())
5362     return false;
5363 
5364   // Bail out if the function declaration itself is invalid.  We will
5365   // have produced a relevant diagnostic while parsing it, so just
5366   // note the problematic sub-expression.
5367   if (Declaration->isInvalidDecl()) {
5368     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5369     return false;
5370   }
5371 
5372   // DR1872: An instantiated virtual constexpr function can't be called in a
5373   // constant expression (prior to C++20). We can still constant-fold such a
5374   // call.
5375   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5376       cast<CXXMethodDecl>(Declaration)->isVirtual())
5377     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5378 
5379   if (Definition && Definition->isInvalidDecl()) {
5380     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5381     return false;
5382   }
5383 
5384   if (const auto *CtorDecl = dyn_cast_or_null<CXXConstructorDecl>(Definition)) {
5385     for (const auto *InitExpr : CtorDecl->inits()) {
5386       if (InitExpr->getInit() && InitExpr->getInit()->containsErrors())
5387         return false;
5388     }
5389   }
5390 
5391   // Can we evaluate this function call?
5392   if (Definition && Definition->isConstexpr() && Body)
5393     return true;
5394 
5395   if (Info.getLangOpts().CPlusPlus11) {
5396     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5397 
5398     // If this function is not constexpr because it is an inherited
5399     // non-constexpr constructor, diagnose that directly.
5400     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5401     if (CD && CD->isInheritingConstructor()) {
5402       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5403       if (!Inherited->isConstexpr())
5404         DiagDecl = CD = Inherited;
5405     }
5406 
5407     // FIXME: If DiagDecl is an implicitly-declared special member function
5408     // or an inheriting constructor, we should be much more explicit about why
5409     // it's not constexpr.
5410     if (CD && CD->isInheritingConstructor())
5411       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5412         << CD->getInheritedConstructor().getConstructor()->getParent();
5413     else
5414       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5415         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5416     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5417   } else {
5418     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5419   }
5420   return false;
5421 }
5422 
5423 namespace {
5424 struct CheckDynamicTypeHandler {
5425   AccessKinds AccessKind;
5426   typedef bool result_type;
5427   bool failed() { return false; }
5428   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5429   bool found(APSInt &Value, QualType SubobjType) { return true; }
5430   bool found(APFloat &Value, QualType SubobjType) { return true; }
5431 };
5432 } // end anonymous namespace
5433 
5434 /// Check that we can access the notional vptr of an object / determine its
5435 /// dynamic type.
5436 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5437                              AccessKinds AK, bool Polymorphic) {
5438   if (This.Designator.Invalid)
5439     return false;
5440 
5441   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5442 
5443   if (!Obj)
5444     return false;
5445 
5446   if (!Obj.Value) {
5447     // The object is not usable in constant expressions, so we can't inspect
5448     // its value to see if it's in-lifetime or what the active union members
5449     // are. We can still check for a one-past-the-end lvalue.
5450     if (This.Designator.isOnePastTheEnd() ||
5451         This.Designator.isMostDerivedAnUnsizedArray()) {
5452       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5453                          ? diag::note_constexpr_access_past_end
5454                          : diag::note_constexpr_access_unsized_array)
5455           << AK;
5456       return false;
5457     } else if (Polymorphic) {
5458       // Conservatively refuse to perform a polymorphic operation if we would
5459       // not be able to read a notional 'vptr' value.
5460       APValue Val;
5461       This.moveInto(Val);
5462       QualType StarThisType =
5463           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5464       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5465           << AK << Val.getAsString(Info.Ctx, StarThisType);
5466       return false;
5467     }
5468     return true;
5469   }
5470 
5471   CheckDynamicTypeHandler Handler{AK};
5472   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5473 }
5474 
5475 /// Check that the pointee of the 'this' pointer in a member function call is
5476 /// either within its lifetime or in its period of construction or destruction.
5477 static bool
5478 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5479                                      const LValue &This,
5480                                      const CXXMethodDecl *NamedMember) {
5481   return checkDynamicType(
5482       Info, E, This,
5483       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5484 }
5485 
5486 struct DynamicType {
5487   /// The dynamic class type of the object.
5488   const CXXRecordDecl *Type;
5489   /// The corresponding path length in the lvalue.
5490   unsigned PathLength;
5491 };
5492 
5493 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5494                                              unsigned PathLength) {
5495   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5496       Designator.Entries.size() && "invalid path length");
5497   return (PathLength == Designator.MostDerivedPathLength)
5498              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5499              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5500 }
5501 
5502 /// Determine the dynamic type of an object.
5503 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5504                                                 LValue &This, AccessKinds AK) {
5505   // If we don't have an lvalue denoting an object of class type, there is no
5506   // meaningful dynamic type. (We consider objects of non-class type to have no
5507   // dynamic type.)
5508   if (!checkDynamicType(Info, E, This, AK, true))
5509     return None;
5510 
5511   // Refuse to compute a dynamic type in the presence of virtual bases. This
5512   // shouldn't happen other than in constant-folding situations, since literal
5513   // types can't have virtual bases.
5514   //
5515   // Note that consumers of DynamicType assume that the type has no virtual
5516   // bases, and will need modifications if this restriction is relaxed.
5517   const CXXRecordDecl *Class =
5518       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5519   if (!Class || Class->getNumVBases()) {
5520     Info.FFDiag(E);
5521     return None;
5522   }
5523 
5524   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5525   // binary search here instead. But the overwhelmingly common case is that
5526   // we're not in the middle of a constructor, so it probably doesn't matter
5527   // in practice.
5528   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5529   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5530        PathLength <= Path.size(); ++PathLength) {
5531     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5532                                       Path.slice(0, PathLength))) {
5533     case ConstructionPhase::Bases:
5534     case ConstructionPhase::DestroyingBases:
5535       // We're constructing or destroying a base class. This is not the dynamic
5536       // type.
5537       break;
5538 
5539     case ConstructionPhase::None:
5540     case ConstructionPhase::AfterBases:
5541     case ConstructionPhase::AfterFields:
5542     case ConstructionPhase::Destroying:
5543       // We've finished constructing the base classes and not yet started
5544       // destroying them again, so this is the dynamic type.
5545       return DynamicType{getBaseClassType(This.Designator, PathLength),
5546                          PathLength};
5547     }
5548   }
5549 
5550   // CWG issue 1517: we're constructing a base class of the object described by
5551   // 'This', so that object has not yet begun its period of construction and
5552   // any polymorphic operation on it results in undefined behavior.
5553   Info.FFDiag(E);
5554   return None;
5555 }
5556 
5557 /// Perform virtual dispatch.
5558 static const CXXMethodDecl *HandleVirtualDispatch(
5559     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5560     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5561   Optional<DynamicType> DynType = ComputeDynamicType(
5562       Info, E, This,
5563       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5564   if (!DynType)
5565     return nullptr;
5566 
5567   // Find the final overrider. It must be declared in one of the classes on the
5568   // path from the dynamic type to the static type.
5569   // FIXME: If we ever allow literal types to have virtual base classes, that
5570   // won't be true.
5571   const CXXMethodDecl *Callee = Found;
5572   unsigned PathLength = DynType->PathLength;
5573   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5574     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5575     const CXXMethodDecl *Overrider =
5576         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5577     if (Overrider) {
5578       Callee = Overrider;
5579       break;
5580     }
5581   }
5582 
5583   // C++2a [class.abstract]p6:
5584   //   the effect of making a virtual call to a pure virtual function [...] is
5585   //   undefined
5586   if (Callee->isPure()) {
5587     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5588     Info.Note(Callee->getLocation(), diag::note_declared_at);
5589     return nullptr;
5590   }
5591 
5592   // If necessary, walk the rest of the path to determine the sequence of
5593   // covariant adjustment steps to apply.
5594   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5595                                        Found->getReturnType())) {
5596     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5597     for (unsigned CovariantPathLength = PathLength + 1;
5598          CovariantPathLength != This.Designator.Entries.size();
5599          ++CovariantPathLength) {
5600       const CXXRecordDecl *NextClass =
5601           getBaseClassType(This.Designator, CovariantPathLength);
5602       const CXXMethodDecl *Next =
5603           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5604       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5605                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5606         CovariantAdjustmentPath.push_back(Next->getReturnType());
5607     }
5608     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5609                                          CovariantAdjustmentPath.back()))
5610       CovariantAdjustmentPath.push_back(Found->getReturnType());
5611   }
5612 
5613   // Perform 'this' adjustment.
5614   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5615     return nullptr;
5616 
5617   return Callee;
5618 }
5619 
5620 /// Perform the adjustment from a value returned by a virtual function to
5621 /// a value of the statically expected type, which may be a pointer or
5622 /// reference to a base class of the returned type.
5623 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5624                                             APValue &Result,
5625                                             ArrayRef<QualType> Path) {
5626   assert(Result.isLValue() &&
5627          "unexpected kind of APValue for covariant return");
5628   if (Result.isNullPointer())
5629     return true;
5630 
5631   LValue LVal;
5632   LVal.setFrom(Info.Ctx, Result);
5633 
5634   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5635   for (unsigned I = 1; I != Path.size(); ++I) {
5636     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5637     assert(OldClass && NewClass && "unexpected kind of covariant return");
5638     if (OldClass != NewClass &&
5639         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5640       return false;
5641     OldClass = NewClass;
5642   }
5643 
5644   LVal.moveInto(Result);
5645   return true;
5646 }
5647 
5648 /// Determine whether \p Base, which is known to be a direct base class of
5649 /// \p Derived, is a public base class.
5650 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5651                               const CXXRecordDecl *Base) {
5652   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5653     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5654     if (BaseClass && declaresSameEntity(BaseClass, Base))
5655       return BaseSpec.getAccessSpecifier() == AS_public;
5656   }
5657   llvm_unreachable("Base is not a direct base of Derived");
5658 }
5659 
5660 /// Apply the given dynamic cast operation on the provided lvalue.
5661 ///
5662 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5663 /// to find a suitable target subobject.
5664 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5665                               LValue &Ptr) {
5666   // We can't do anything with a non-symbolic pointer value.
5667   SubobjectDesignator &D = Ptr.Designator;
5668   if (D.Invalid)
5669     return false;
5670 
5671   // C++ [expr.dynamic.cast]p6:
5672   //   If v is a null pointer value, the result is a null pointer value.
5673   if (Ptr.isNullPointer() && !E->isGLValue())
5674     return true;
5675 
5676   // For all the other cases, we need the pointer to point to an object within
5677   // its lifetime / period of construction / destruction, and we need to know
5678   // its dynamic type.
5679   Optional<DynamicType> DynType =
5680       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5681   if (!DynType)
5682     return false;
5683 
5684   // C++ [expr.dynamic.cast]p7:
5685   //   If T is "pointer to cv void", then the result is a pointer to the most
5686   //   derived object
5687   if (E->getType()->isVoidPointerType())
5688     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5689 
5690   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5691   assert(C && "dynamic_cast target is not void pointer nor class");
5692   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5693 
5694   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5695     // C++ [expr.dynamic.cast]p9:
5696     if (!E->isGLValue()) {
5697       //   The value of a failed cast to pointer type is the null pointer value
5698       //   of the required result type.
5699       Ptr.setNull(Info.Ctx, E->getType());
5700       return true;
5701     }
5702 
5703     //   A failed cast to reference type throws [...] std::bad_cast.
5704     unsigned DiagKind;
5705     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5706                    DynType->Type->isDerivedFrom(C)))
5707       DiagKind = 0;
5708     else if (!Paths || Paths->begin() == Paths->end())
5709       DiagKind = 1;
5710     else if (Paths->isAmbiguous(CQT))
5711       DiagKind = 2;
5712     else {
5713       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5714       DiagKind = 3;
5715     }
5716     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5717         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5718         << Info.Ctx.getRecordType(DynType->Type)
5719         << E->getType().getUnqualifiedType();
5720     return false;
5721   };
5722 
5723   // Runtime check, phase 1:
5724   //   Walk from the base subobject towards the derived object looking for the
5725   //   target type.
5726   for (int PathLength = Ptr.Designator.Entries.size();
5727        PathLength >= (int)DynType->PathLength; --PathLength) {
5728     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5729     if (declaresSameEntity(Class, C))
5730       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5731     // We can only walk across public inheritance edges.
5732     if (PathLength > (int)DynType->PathLength &&
5733         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5734                            Class))
5735       return RuntimeCheckFailed(nullptr);
5736   }
5737 
5738   // Runtime check, phase 2:
5739   //   Search the dynamic type for an unambiguous public base of type C.
5740   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5741                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5742   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5743       Paths.front().Access == AS_public) {
5744     // Downcast to the dynamic type...
5745     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5746       return false;
5747     // ... then upcast to the chosen base class subobject.
5748     for (CXXBasePathElement &Elem : Paths.front())
5749       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5750         return false;
5751     return true;
5752   }
5753 
5754   // Otherwise, the runtime check fails.
5755   return RuntimeCheckFailed(&Paths);
5756 }
5757 
5758 namespace {
5759 struct StartLifetimeOfUnionMemberHandler {
5760   EvalInfo &Info;
5761   const Expr *LHSExpr;
5762   const FieldDecl *Field;
5763   bool DuringInit;
5764   bool Failed = false;
5765   static const AccessKinds AccessKind = AK_Assign;
5766 
5767   typedef bool result_type;
5768   bool failed() { return Failed; }
5769   bool found(APValue &Subobj, QualType SubobjType) {
5770     // We are supposed to perform no initialization but begin the lifetime of
5771     // the object. We interpret that as meaning to do what default
5772     // initialization of the object would do if all constructors involved were
5773     // trivial:
5774     //  * All base, non-variant member, and array element subobjects' lifetimes
5775     //    begin
5776     //  * No variant members' lifetimes begin
5777     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5778     assert(SubobjType->isUnionType());
5779     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5780       // This union member is already active. If it's also in-lifetime, there's
5781       // nothing to do.
5782       if (Subobj.getUnionValue().hasValue())
5783         return true;
5784     } else if (DuringInit) {
5785       // We're currently in the process of initializing a different union
5786       // member.  If we carried on, that initialization would attempt to
5787       // store to an inactive union member, resulting in undefined behavior.
5788       Info.FFDiag(LHSExpr,
5789                   diag::note_constexpr_union_member_change_during_init);
5790       return false;
5791     }
5792     APValue Result;
5793     Failed = !getDefaultInitValue(Field->getType(), Result);
5794     Subobj.setUnion(Field, Result);
5795     return true;
5796   }
5797   bool found(APSInt &Value, QualType SubobjType) {
5798     llvm_unreachable("wrong value kind for union object");
5799   }
5800   bool found(APFloat &Value, QualType SubobjType) {
5801     llvm_unreachable("wrong value kind for union object");
5802   }
5803 };
5804 } // end anonymous namespace
5805 
5806 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5807 
5808 /// Handle a builtin simple-assignment or a call to a trivial assignment
5809 /// operator whose left-hand side might involve a union member access. If it
5810 /// does, implicitly start the lifetime of any accessed union elements per
5811 /// C++20 [class.union]5.
5812 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5813                                           const LValue &LHS) {
5814   if (LHS.InvalidBase || LHS.Designator.Invalid)
5815     return false;
5816 
5817   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5818   // C++ [class.union]p5:
5819   //   define the set S(E) of subexpressions of E as follows:
5820   unsigned PathLength = LHS.Designator.Entries.size();
5821   for (const Expr *E = LHSExpr; E != nullptr;) {
5822     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5823     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5824       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5825       // Note that we can't implicitly start the lifetime of a reference,
5826       // so we don't need to proceed any further if we reach one.
5827       if (!FD || FD->getType()->isReferenceType())
5828         break;
5829 
5830       //    ... and also contains A.B if B names a union member ...
5831       if (FD->getParent()->isUnion()) {
5832         //    ... of a non-class, non-array type, or of a class type with a
5833         //    trivial default constructor that is not deleted, or an array of
5834         //    such types.
5835         auto *RD =
5836             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5837         if (!RD || RD->hasTrivialDefaultConstructor())
5838           UnionPathLengths.push_back({PathLength - 1, FD});
5839       }
5840 
5841       E = ME->getBase();
5842       --PathLength;
5843       assert(declaresSameEntity(FD,
5844                                 LHS.Designator.Entries[PathLength]
5845                                     .getAsBaseOrMember().getPointer()));
5846 
5847       //   -- If E is of the form A[B] and is interpreted as a built-in array
5848       //      subscripting operator, S(E) is [S(the array operand, if any)].
5849     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5850       // Step over an ArrayToPointerDecay implicit cast.
5851       auto *Base = ASE->getBase()->IgnoreImplicit();
5852       if (!Base->getType()->isArrayType())
5853         break;
5854 
5855       E = Base;
5856       --PathLength;
5857 
5858     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5859       // Step over a derived-to-base conversion.
5860       E = ICE->getSubExpr();
5861       if (ICE->getCastKind() == CK_NoOp)
5862         continue;
5863       if (ICE->getCastKind() != CK_DerivedToBase &&
5864           ICE->getCastKind() != CK_UncheckedDerivedToBase)
5865         break;
5866       // Walk path backwards as we walk up from the base to the derived class.
5867       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5868         --PathLength;
5869         (void)Elt;
5870         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5871                                   LHS.Designator.Entries[PathLength]
5872                                       .getAsBaseOrMember().getPointer()));
5873       }
5874 
5875     //   -- Otherwise, S(E) is empty.
5876     } else {
5877       break;
5878     }
5879   }
5880 
5881   // Common case: no unions' lifetimes are started.
5882   if (UnionPathLengths.empty())
5883     return true;
5884 
5885   //   if modification of X [would access an inactive union member], an object
5886   //   of the type of X is implicitly created
5887   CompleteObject Obj =
5888       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5889   if (!Obj)
5890     return false;
5891   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5892            llvm::reverse(UnionPathLengths)) {
5893     // Form a designator for the union object.
5894     SubobjectDesignator D = LHS.Designator;
5895     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5896 
5897     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
5898                       ConstructionPhase::AfterBases;
5899     StartLifetimeOfUnionMemberHandler StartLifetime{
5900         Info, LHSExpr, LengthAndField.second, DuringInit};
5901     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5902       return false;
5903   }
5904 
5905   return true;
5906 }
5907 
5908 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
5909                             CallRef Call, EvalInfo &Info,
5910                             bool NonNull = false) {
5911   LValue LV;
5912   // Create the parameter slot and register its destruction. For a vararg
5913   // argument, create a temporary.
5914   // FIXME: For calling conventions that destroy parameters in the callee,
5915   // should we consider performing destruction when the function returns
5916   // instead?
5917   APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
5918                    : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
5919                                                        ScopeKind::Call, LV);
5920   if (!EvaluateInPlace(V, Info, LV, Arg))
5921     return false;
5922 
5923   // Passing a null pointer to an __attribute__((nonnull)) parameter results in
5924   // undefined behavior, so is non-constant.
5925   if (NonNull && V.isLValue() && V.isNullPointer()) {
5926     Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
5927     return false;
5928   }
5929 
5930   return true;
5931 }
5932 
5933 /// Evaluate the arguments to a function call.
5934 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
5935                          EvalInfo &Info, const FunctionDecl *Callee,
5936                          bool RightToLeft = false) {
5937   bool Success = true;
5938   llvm::SmallBitVector ForbiddenNullArgs;
5939   if (Callee->hasAttr<NonNullAttr>()) {
5940     ForbiddenNullArgs.resize(Args.size());
5941     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5942       if (!Attr->args_size()) {
5943         ForbiddenNullArgs.set();
5944         break;
5945       } else
5946         for (auto Idx : Attr->args()) {
5947           unsigned ASTIdx = Idx.getASTIndex();
5948           if (ASTIdx >= Args.size())
5949             continue;
5950           ForbiddenNullArgs[ASTIdx] = 1;
5951         }
5952     }
5953   }
5954   for (unsigned I = 0; I < Args.size(); I++) {
5955     unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
5956     const ParmVarDecl *PVD =
5957         Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
5958     bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
5959     if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
5960       // If we're checking for a potential constant expression, evaluate all
5961       // initializers even if some of them fail.
5962       if (!Info.noteFailure())
5963         return false;
5964       Success = false;
5965     }
5966   }
5967   return Success;
5968 }
5969 
5970 /// Perform a trivial copy from Param, which is the parameter of a copy or move
5971 /// constructor or assignment operator.
5972 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
5973                               const Expr *E, APValue &Result,
5974                               bool CopyObjectRepresentation) {
5975   // Find the reference argument.
5976   CallStackFrame *Frame = Info.CurrentCall;
5977   APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
5978   if (!RefValue) {
5979     Info.FFDiag(E);
5980     return false;
5981   }
5982 
5983   // Copy out the contents of the RHS object.
5984   LValue RefLValue;
5985   RefLValue.setFrom(Info.Ctx, *RefValue);
5986   return handleLValueToRValueConversion(
5987       Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
5988       CopyObjectRepresentation);
5989 }
5990 
5991 /// Evaluate a function call.
5992 static bool HandleFunctionCall(SourceLocation CallLoc,
5993                                const FunctionDecl *Callee, const LValue *This,
5994                                ArrayRef<const Expr *> Args, CallRef Call,
5995                                const Stmt *Body, EvalInfo &Info,
5996                                APValue &Result, const LValue *ResultSlot) {
5997   if (!Info.CheckCallLimit(CallLoc))
5998     return false;
5999 
6000   CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
6001 
6002   // For a trivial copy or move assignment, perform an APValue copy. This is
6003   // essential for unions, where the operations performed by the assignment
6004   // operator cannot be represented as statements.
6005   //
6006   // Skip this for non-union classes with no fields; in that case, the defaulted
6007   // copy/move does not actually read the object.
6008   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6009   if (MD && MD->isDefaulted() &&
6010       (MD->getParent()->isUnion() ||
6011        (MD->isTrivial() &&
6012         isReadByLvalueToRvalueConversion(MD->getParent())))) {
6013     assert(This &&
6014            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6015     APValue RHSValue;
6016     if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6017                            MD->getParent()->isUnion()))
6018       return false;
6019     if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() &&
6020         !HandleUnionActiveMemberChange(Info, Args[0], *This))
6021       return false;
6022     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6023                           RHSValue))
6024       return false;
6025     This->moveInto(Result);
6026     return true;
6027   } else if (MD && isLambdaCallOperator(MD)) {
6028     // We're in a lambda; determine the lambda capture field maps unless we're
6029     // just constexpr checking a lambda's call operator. constexpr checking is
6030     // done before the captures have been added to the closure object (unless
6031     // we're inferring constexpr-ness), so we don't have access to them in this
6032     // case. But since we don't need the captures to constexpr check, we can
6033     // just ignore them.
6034     if (!Info.checkingPotentialConstantExpression())
6035       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6036                                         Frame.LambdaThisCaptureField);
6037   }
6038 
6039   StmtResult Ret = {Result, ResultSlot};
6040   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6041   if (ESR == ESR_Succeeded) {
6042     if (Callee->getReturnType()->isVoidType())
6043       return true;
6044     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6045   }
6046   return ESR == ESR_Returned;
6047 }
6048 
6049 /// Evaluate a constructor call.
6050 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6051                                   CallRef Call,
6052                                   const CXXConstructorDecl *Definition,
6053                                   EvalInfo &Info, APValue &Result) {
6054   SourceLocation CallLoc = E->getExprLoc();
6055   if (!Info.CheckCallLimit(CallLoc))
6056     return false;
6057 
6058   const CXXRecordDecl *RD = Definition->getParent();
6059   if (RD->getNumVBases()) {
6060     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6061     return false;
6062   }
6063 
6064   EvalInfo::EvaluatingConstructorRAII EvalObj(
6065       Info,
6066       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6067       RD->getNumBases());
6068   CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
6069 
6070   // FIXME: Creating an APValue just to hold a nonexistent return value is
6071   // wasteful.
6072   APValue RetVal;
6073   StmtResult Ret = {RetVal, nullptr};
6074 
6075   // If it's a delegating constructor, delegate.
6076   if (Definition->isDelegatingConstructor()) {
6077     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6078     {
6079       FullExpressionRAII InitScope(Info);
6080       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6081           !InitScope.destroy())
6082         return false;
6083     }
6084     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6085   }
6086 
6087   // For a trivial copy or move constructor, perform an APValue copy. This is
6088   // essential for unions (or classes with anonymous union members), where the
6089   // operations performed by the constructor cannot be represented by
6090   // ctor-initializers.
6091   //
6092   // Skip this for empty non-union classes; we should not perform an
6093   // lvalue-to-rvalue conversion on them because their copy constructor does not
6094   // actually read them.
6095   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6096       (Definition->getParent()->isUnion() ||
6097        (Definition->isTrivial() &&
6098         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6099     return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6100                              Definition->getParent()->isUnion());
6101   }
6102 
6103   // Reserve space for the struct members.
6104   if (!Result.hasValue()) {
6105     if (!RD->isUnion())
6106       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6107                        std::distance(RD->field_begin(), RD->field_end()));
6108     else
6109       // A union starts with no active member.
6110       Result = APValue((const FieldDecl*)nullptr);
6111   }
6112 
6113   if (RD->isInvalidDecl()) return false;
6114   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6115 
6116   // A scope for temporaries lifetime-extended by reference members.
6117   BlockScopeRAII LifetimeExtendedScope(Info);
6118 
6119   bool Success = true;
6120   unsigned BasesSeen = 0;
6121 #ifndef NDEBUG
6122   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6123 #endif
6124   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6125   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6126     // We might be initializing the same field again if this is an indirect
6127     // field initialization.
6128     if (FieldIt == RD->field_end() ||
6129         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6130       assert(Indirect && "fields out of order?");
6131       return;
6132     }
6133 
6134     // Default-initialize any fields with no explicit initializer.
6135     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6136       assert(FieldIt != RD->field_end() && "missing field?");
6137       if (!FieldIt->isUnnamedBitfield())
6138         Success &= getDefaultInitValue(
6139             FieldIt->getType(),
6140             Result.getStructField(FieldIt->getFieldIndex()));
6141     }
6142     ++FieldIt;
6143   };
6144   for (const auto *I : Definition->inits()) {
6145     LValue Subobject = This;
6146     LValue SubobjectParent = This;
6147     APValue *Value = &Result;
6148 
6149     // Determine the subobject to initialize.
6150     FieldDecl *FD = nullptr;
6151     if (I->isBaseInitializer()) {
6152       QualType BaseType(I->getBaseClass(), 0);
6153 #ifndef NDEBUG
6154       // Non-virtual base classes are initialized in the order in the class
6155       // definition. We have already checked for virtual base classes.
6156       assert(!BaseIt->isVirtual() && "virtual base for literal type");
6157       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6158              "base class initializers not in expected order");
6159       ++BaseIt;
6160 #endif
6161       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6162                                   BaseType->getAsCXXRecordDecl(), &Layout))
6163         return false;
6164       Value = &Result.getStructBase(BasesSeen++);
6165     } else if ((FD = I->getMember())) {
6166       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6167         return false;
6168       if (RD->isUnion()) {
6169         Result = APValue(FD);
6170         Value = &Result.getUnionValue();
6171       } else {
6172         SkipToField(FD, false);
6173         Value = &Result.getStructField(FD->getFieldIndex());
6174       }
6175     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6176       // Walk the indirect field decl's chain to find the object to initialize,
6177       // and make sure we've initialized every step along it.
6178       auto IndirectFieldChain = IFD->chain();
6179       for (auto *C : IndirectFieldChain) {
6180         FD = cast<FieldDecl>(C);
6181         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6182         // Switch the union field if it differs. This happens if we had
6183         // preceding zero-initialization, and we're now initializing a union
6184         // subobject other than the first.
6185         // FIXME: In this case, the values of the other subobjects are
6186         // specified, since zero-initialization sets all padding bits to zero.
6187         if (!Value->hasValue() ||
6188             (Value->isUnion() && Value->getUnionField() != FD)) {
6189           if (CD->isUnion())
6190             *Value = APValue(FD);
6191           else
6192             // FIXME: This immediately starts the lifetime of all members of
6193             // an anonymous struct. It would be preferable to strictly start
6194             // member lifetime in initialization order.
6195             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6196         }
6197         // Store Subobject as its parent before updating it for the last element
6198         // in the chain.
6199         if (C == IndirectFieldChain.back())
6200           SubobjectParent = Subobject;
6201         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6202           return false;
6203         if (CD->isUnion())
6204           Value = &Value->getUnionValue();
6205         else {
6206           if (C == IndirectFieldChain.front() && !RD->isUnion())
6207             SkipToField(FD, true);
6208           Value = &Value->getStructField(FD->getFieldIndex());
6209         }
6210       }
6211     } else {
6212       llvm_unreachable("unknown base initializer kind");
6213     }
6214 
6215     // Need to override This for implicit field initializers as in this case
6216     // This refers to innermost anonymous struct/union containing initializer,
6217     // not to currently constructed class.
6218     const Expr *Init = I->getInit();
6219     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6220                                   isa<CXXDefaultInitExpr>(Init));
6221     FullExpressionRAII InitScope(Info);
6222     if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6223         (FD && FD->isBitField() &&
6224          !truncateBitfieldValue(Info, Init, *Value, FD))) {
6225       // If we're checking for a potential constant expression, evaluate all
6226       // initializers even if some of them fail.
6227       if (!Info.noteFailure())
6228         return false;
6229       Success = false;
6230     }
6231 
6232     // This is the point at which the dynamic type of the object becomes this
6233     // class type.
6234     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6235       EvalObj.finishedConstructingBases();
6236   }
6237 
6238   // Default-initialize any remaining fields.
6239   if (!RD->isUnion()) {
6240     for (; FieldIt != RD->field_end(); ++FieldIt) {
6241       if (!FieldIt->isUnnamedBitfield())
6242         Success &= getDefaultInitValue(
6243             FieldIt->getType(),
6244             Result.getStructField(FieldIt->getFieldIndex()));
6245     }
6246   }
6247 
6248   EvalObj.finishedConstructingFields();
6249 
6250   return Success &&
6251          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6252          LifetimeExtendedScope.destroy();
6253 }
6254 
6255 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6256                                   ArrayRef<const Expr*> Args,
6257                                   const CXXConstructorDecl *Definition,
6258                                   EvalInfo &Info, APValue &Result) {
6259   CallScopeRAII CallScope(Info);
6260   CallRef Call = Info.CurrentCall->createCall(Definition);
6261   if (!EvaluateArgs(Args, Call, Info, Definition))
6262     return false;
6263 
6264   return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6265          CallScope.destroy();
6266 }
6267 
6268 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6269                                   const LValue &This, APValue &Value,
6270                                   QualType T) {
6271   // Objects can only be destroyed while they're within their lifetimes.
6272   // FIXME: We have no representation for whether an object of type nullptr_t
6273   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6274   // as indeterminate instead?
6275   if (Value.isAbsent() && !T->isNullPtrType()) {
6276     APValue Printable;
6277     This.moveInto(Printable);
6278     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6279       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6280     return false;
6281   }
6282 
6283   // Invent an expression for location purposes.
6284   // FIXME: We shouldn't need to do this.
6285   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue);
6286 
6287   // For arrays, destroy elements right-to-left.
6288   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6289     uint64_t Size = CAT->getSize().getZExtValue();
6290     QualType ElemT = CAT->getElementType();
6291 
6292     LValue ElemLV = This;
6293     ElemLV.addArray(Info, &LocE, CAT);
6294     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6295       return false;
6296 
6297     // Ensure that we have actual array elements available to destroy; the
6298     // destructors might mutate the value, so we can't run them on the array
6299     // filler.
6300     if (Size && Size > Value.getArrayInitializedElts())
6301       expandArray(Value, Value.getArraySize() - 1);
6302 
6303     for (; Size != 0; --Size) {
6304       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6305       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6306           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6307         return false;
6308     }
6309 
6310     // End the lifetime of this array now.
6311     Value = APValue();
6312     return true;
6313   }
6314 
6315   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6316   if (!RD) {
6317     if (T.isDestructedType()) {
6318       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6319       return false;
6320     }
6321 
6322     Value = APValue();
6323     return true;
6324   }
6325 
6326   if (RD->getNumVBases()) {
6327     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6328     return false;
6329   }
6330 
6331   const CXXDestructorDecl *DD = RD->getDestructor();
6332   if (!DD && !RD->hasTrivialDestructor()) {
6333     Info.FFDiag(CallLoc);
6334     return false;
6335   }
6336 
6337   if (!DD || DD->isTrivial() ||
6338       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6339     // A trivial destructor just ends the lifetime of the object. Check for
6340     // this case before checking for a body, because we might not bother
6341     // building a body for a trivial destructor. Note that it doesn't matter
6342     // whether the destructor is constexpr in this case; all trivial
6343     // destructors are constexpr.
6344     //
6345     // If an anonymous union would be destroyed, some enclosing destructor must
6346     // have been explicitly defined, and the anonymous union destruction should
6347     // have no effect.
6348     Value = APValue();
6349     return true;
6350   }
6351 
6352   if (!Info.CheckCallLimit(CallLoc))
6353     return false;
6354 
6355   const FunctionDecl *Definition = nullptr;
6356   const Stmt *Body = DD->getBody(Definition);
6357 
6358   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6359     return false;
6360 
6361   CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
6362 
6363   // We're now in the period of destruction of this object.
6364   unsigned BasesLeft = RD->getNumBases();
6365   EvalInfo::EvaluatingDestructorRAII EvalObj(
6366       Info,
6367       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6368   if (!EvalObj.DidInsert) {
6369     // C++2a [class.dtor]p19:
6370     //   the behavior is undefined if the destructor is invoked for an object
6371     //   whose lifetime has ended
6372     // (Note that formally the lifetime ends when the period of destruction
6373     // begins, even though certain uses of the object remain valid until the
6374     // period of destruction ends.)
6375     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6376     return false;
6377   }
6378 
6379   // FIXME: Creating an APValue just to hold a nonexistent return value is
6380   // wasteful.
6381   APValue RetVal;
6382   StmtResult Ret = {RetVal, nullptr};
6383   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6384     return false;
6385 
6386   // A union destructor does not implicitly destroy its members.
6387   if (RD->isUnion())
6388     return true;
6389 
6390   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6391 
6392   // We don't have a good way to iterate fields in reverse, so collect all the
6393   // fields first and then walk them backwards.
6394   SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
6395   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6396     if (FD->isUnnamedBitfield())
6397       continue;
6398 
6399     LValue Subobject = This;
6400     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6401       return false;
6402 
6403     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6404     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6405                                FD->getType()))
6406       return false;
6407   }
6408 
6409   if (BasesLeft != 0)
6410     EvalObj.startedDestroyingBases();
6411 
6412   // Destroy base classes in reverse order.
6413   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6414     --BasesLeft;
6415 
6416     QualType BaseType = Base.getType();
6417     LValue Subobject = This;
6418     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6419                                 BaseType->getAsCXXRecordDecl(), &Layout))
6420       return false;
6421 
6422     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6423     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6424                                BaseType))
6425       return false;
6426   }
6427   assert(BasesLeft == 0 && "NumBases was wrong?");
6428 
6429   // The period of destruction ends now. The object is gone.
6430   Value = APValue();
6431   return true;
6432 }
6433 
6434 namespace {
6435 struct DestroyObjectHandler {
6436   EvalInfo &Info;
6437   const Expr *E;
6438   const LValue &This;
6439   const AccessKinds AccessKind;
6440 
6441   typedef bool result_type;
6442   bool failed() { return false; }
6443   bool found(APValue &Subobj, QualType SubobjType) {
6444     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6445                                  SubobjType);
6446   }
6447   bool found(APSInt &Value, QualType SubobjType) {
6448     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6449     return false;
6450   }
6451   bool found(APFloat &Value, QualType SubobjType) {
6452     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6453     return false;
6454   }
6455 };
6456 }
6457 
6458 /// Perform a destructor or pseudo-destructor call on the given object, which
6459 /// might in general not be a complete object.
6460 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6461                               const LValue &This, QualType ThisType) {
6462   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6463   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6464   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6465 }
6466 
6467 /// Destroy and end the lifetime of the given complete object.
6468 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6469                               APValue::LValueBase LVBase, APValue &Value,
6470                               QualType T) {
6471   // If we've had an unmodeled side-effect, we can't rely on mutable state
6472   // (such as the object we're about to destroy) being correct.
6473   if (Info.EvalStatus.HasSideEffects)
6474     return false;
6475 
6476   LValue LV;
6477   LV.set({LVBase});
6478   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6479 }
6480 
6481 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6482 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6483                                   LValue &Result) {
6484   if (Info.checkingPotentialConstantExpression() ||
6485       Info.SpeculativeEvaluationDepth)
6486     return false;
6487 
6488   // This is permitted only within a call to std::allocator<T>::allocate.
6489   auto Caller = Info.getStdAllocatorCaller("allocate");
6490   if (!Caller) {
6491     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6492                                      ? diag::note_constexpr_new_untyped
6493                                      : diag::note_constexpr_new);
6494     return false;
6495   }
6496 
6497   QualType ElemType = Caller.ElemType;
6498   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6499     Info.FFDiag(E->getExprLoc(),
6500                 diag::note_constexpr_new_not_complete_object_type)
6501         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6502     return false;
6503   }
6504 
6505   APSInt ByteSize;
6506   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6507     return false;
6508   bool IsNothrow = false;
6509   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6510     EvaluateIgnoredValue(Info, E->getArg(I));
6511     IsNothrow |= E->getType()->isNothrowT();
6512   }
6513 
6514   CharUnits ElemSize;
6515   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6516     return false;
6517   APInt Size, Remainder;
6518   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6519   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6520   if (Remainder != 0) {
6521     // This likely indicates a bug in the implementation of 'std::allocator'.
6522     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6523         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6524     return false;
6525   }
6526 
6527   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6528     if (IsNothrow) {
6529       Result.setNull(Info.Ctx, E->getType());
6530       return true;
6531     }
6532 
6533     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6534     return false;
6535   }
6536 
6537   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6538                                                      ArrayType::Normal, 0);
6539   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6540   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6541   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6542   return true;
6543 }
6544 
6545 static bool hasVirtualDestructor(QualType T) {
6546   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6547     if (CXXDestructorDecl *DD = RD->getDestructor())
6548       return DD->isVirtual();
6549   return false;
6550 }
6551 
6552 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6553   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6554     if (CXXDestructorDecl *DD = RD->getDestructor())
6555       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6556   return nullptr;
6557 }
6558 
6559 /// Check that the given object is a suitable pointer to a heap allocation that
6560 /// still exists and is of the right kind for the purpose of a deletion.
6561 ///
6562 /// On success, returns the heap allocation to deallocate. On failure, produces
6563 /// a diagnostic and returns None.
6564 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6565                                             const LValue &Pointer,
6566                                             DynAlloc::Kind DeallocKind) {
6567   auto PointerAsString = [&] {
6568     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6569   };
6570 
6571   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6572   if (!DA) {
6573     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6574         << PointerAsString();
6575     if (Pointer.Base)
6576       NoteLValueLocation(Info, Pointer.Base);
6577     return None;
6578   }
6579 
6580   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6581   if (!Alloc) {
6582     Info.FFDiag(E, diag::note_constexpr_double_delete);
6583     return None;
6584   }
6585 
6586   QualType AllocType = Pointer.Base.getDynamicAllocType();
6587   if (DeallocKind != (*Alloc)->getKind()) {
6588     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6589         << DeallocKind << (*Alloc)->getKind() << AllocType;
6590     NoteLValueLocation(Info, Pointer.Base);
6591     return None;
6592   }
6593 
6594   bool Subobject = false;
6595   if (DeallocKind == DynAlloc::New) {
6596     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6597                 Pointer.Designator.isOnePastTheEnd();
6598   } else {
6599     Subobject = Pointer.Designator.Entries.size() != 1 ||
6600                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6601   }
6602   if (Subobject) {
6603     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6604         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6605     return None;
6606   }
6607 
6608   return Alloc;
6609 }
6610 
6611 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6612 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6613   if (Info.checkingPotentialConstantExpression() ||
6614       Info.SpeculativeEvaluationDepth)
6615     return false;
6616 
6617   // This is permitted only within a call to std::allocator<T>::deallocate.
6618   if (!Info.getStdAllocatorCaller("deallocate")) {
6619     Info.FFDiag(E->getExprLoc());
6620     return true;
6621   }
6622 
6623   LValue Pointer;
6624   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6625     return false;
6626   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6627     EvaluateIgnoredValue(Info, E->getArg(I));
6628 
6629   if (Pointer.Designator.Invalid)
6630     return false;
6631 
6632   // Deleting a null pointer has no effect.
6633   if (Pointer.isNullPointer())
6634     return true;
6635 
6636   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6637     return false;
6638 
6639   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6640   return true;
6641 }
6642 
6643 //===----------------------------------------------------------------------===//
6644 // Generic Evaluation
6645 //===----------------------------------------------------------------------===//
6646 namespace {
6647 
6648 class BitCastBuffer {
6649   // FIXME: We're going to need bit-level granularity when we support
6650   // bit-fields.
6651   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6652   // we don't support a host or target where that is the case. Still, we should
6653   // use a more generic type in case we ever do.
6654   SmallVector<Optional<unsigned char>, 32> Bytes;
6655 
6656   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6657                 "Need at least 8 bit unsigned char");
6658 
6659   bool TargetIsLittleEndian;
6660 
6661 public:
6662   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6663       : Bytes(Width.getQuantity()),
6664         TargetIsLittleEndian(TargetIsLittleEndian) {}
6665 
6666   LLVM_NODISCARD
6667   bool readObject(CharUnits Offset, CharUnits Width,
6668                   SmallVectorImpl<unsigned char> &Output) const {
6669     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6670       // If a byte of an integer is uninitialized, then the whole integer is
6671       // uninitalized.
6672       if (!Bytes[I.getQuantity()])
6673         return false;
6674       Output.push_back(*Bytes[I.getQuantity()]);
6675     }
6676     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6677       std::reverse(Output.begin(), Output.end());
6678     return true;
6679   }
6680 
6681   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6682     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6683       std::reverse(Input.begin(), Input.end());
6684 
6685     size_t Index = 0;
6686     for (unsigned char Byte : Input) {
6687       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6688       Bytes[Offset.getQuantity() + Index] = Byte;
6689       ++Index;
6690     }
6691   }
6692 
6693   size_t size() { return Bytes.size(); }
6694 };
6695 
6696 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6697 /// target would represent the value at runtime.
6698 class APValueToBufferConverter {
6699   EvalInfo &Info;
6700   BitCastBuffer Buffer;
6701   const CastExpr *BCE;
6702 
6703   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6704                            const CastExpr *BCE)
6705       : Info(Info),
6706         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6707         BCE(BCE) {}
6708 
6709   bool visit(const APValue &Val, QualType Ty) {
6710     return visit(Val, Ty, CharUnits::fromQuantity(0));
6711   }
6712 
6713   // Write out Val with type Ty into Buffer starting at Offset.
6714   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6715     assert((size_t)Offset.getQuantity() <= Buffer.size());
6716 
6717     // As a special case, nullptr_t has an indeterminate value.
6718     if (Ty->isNullPtrType())
6719       return true;
6720 
6721     // Dig through Src to find the byte at SrcOffset.
6722     switch (Val.getKind()) {
6723     case APValue::Indeterminate:
6724     case APValue::None:
6725       return true;
6726 
6727     case APValue::Int:
6728       return visitInt(Val.getInt(), Ty, Offset);
6729     case APValue::Float:
6730       return visitFloat(Val.getFloat(), Ty, Offset);
6731     case APValue::Array:
6732       return visitArray(Val, Ty, Offset);
6733     case APValue::Struct:
6734       return visitRecord(Val, Ty, Offset);
6735 
6736     case APValue::ComplexInt:
6737     case APValue::ComplexFloat:
6738     case APValue::Vector:
6739     case APValue::FixedPoint:
6740       // FIXME: We should support these.
6741 
6742     case APValue::Union:
6743     case APValue::MemberPointer:
6744     case APValue::AddrLabelDiff: {
6745       Info.FFDiag(BCE->getBeginLoc(),
6746                   diag::note_constexpr_bit_cast_unsupported_type)
6747           << Ty;
6748       return false;
6749     }
6750 
6751     case APValue::LValue:
6752       llvm_unreachable("LValue subobject in bit_cast?");
6753     }
6754     llvm_unreachable("Unhandled APValue::ValueKind");
6755   }
6756 
6757   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6758     const RecordDecl *RD = Ty->getAsRecordDecl();
6759     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6760 
6761     // Visit the base classes.
6762     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6763       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6764         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6765         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6766 
6767         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6768                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6769           return false;
6770       }
6771     }
6772 
6773     // Visit the fields.
6774     unsigned FieldIdx = 0;
6775     for (FieldDecl *FD : RD->fields()) {
6776       if (FD->isBitField()) {
6777         Info.FFDiag(BCE->getBeginLoc(),
6778                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6779         return false;
6780       }
6781 
6782       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6783 
6784       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6785              "only bit-fields can have sub-char alignment");
6786       CharUnits FieldOffset =
6787           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6788       QualType FieldTy = FD->getType();
6789       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6790         return false;
6791       ++FieldIdx;
6792     }
6793 
6794     return true;
6795   }
6796 
6797   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6798     const auto *CAT =
6799         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6800     if (!CAT)
6801       return false;
6802 
6803     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6804     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6805     unsigned ArraySize = Val.getArraySize();
6806     // First, initialize the initialized elements.
6807     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6808       const APValue &SubObj = Val.getArrayInitializedElt(I);
6809       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6810         return false;
6811     }
6812 
6813     // Next, initialize the rest of the array using the filler.
6814     if (Val.hasArrayFiller()) {
6815       const APValue &Filler = Val.getArrayFiller();
6816       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6817         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6818           return false;
6819       }
6820     }
6821 
6822     return true;
6823   }
6824 
6825   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6826     APSInt AdjustedVal = Val;
6827     unsigned Width = AdjustedVal.getBitWidth();
6828     if (Ty->isBooleanType()) {
6829       Width = Info.Ctx.getTypeSize(Ty);
6830       AdjustedVal = AdjustedVal.extend(Width);
6831     }
6832 
6833     SmallVector<unsigned char, 8> Bytes(Width / 8);
6834     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
6835     Buffer.writeObject(Offset, Bytes);
6836     return true;
6837   }
6838 
6839   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6840     APSInt AsInt(Val.bitcastToAPInt());
6841     return visitInt(AsInt, Ty, Offset);
6842   }
6843 
6844 public:
6845   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6846                                          const CastExpr *BCE) {
6847     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6848     APValueToBufferConverter Converter(Info, DstSize, BCE);
6849     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6850       return None;
6851     return Converter.Buffer;
6852   }
6853 };
6854 
6855 /// Write an BitCastBuffer into an APValue.
6856 class BufferToAPValueConverter {
6857   EvalInfo &Info;
6858   const BitCastBuffer &Buffer;
6859   const CastExpr *BCE;
6860 
6861   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6862                            const CastExpr *BCE)
6863       : Info(Info), Buffer(Buffer), BCE(BCE) {}
6864 
6865   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6866   // with an invalid type, so anything left is a deficiency on our part (FIXME).
6867   // Ideally this will be unreachable.
6868   llvm::NoneType unsupportedType(QualType Ty) {
6869     Info.FFDiag(BCE->getBeginLoc(),
6870                 diag::note_constexpr_bit_cast_unsupported_type)
6871         << Ty;
6872     return None;
6873   }
6874 
6875   llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) {
6876     Info.FFDiag(BCE->getBeginLoc(),
6877                 diag::note_constexpr_bit_cast_unrepresentable_value)
6878         << Ty << Val.toString(/*Radix=*/10);
6879     return None;
6880   }
6881 
6882   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6883                           const EnumType *EnumSugar = nullptr) {
6884     if (T->isNullPtrType()) {
6885       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6886       return APValue((Expr *)nullptr,
6887                      /*Offset=*/CharUnits::fromQuantity(NullValue),
6888                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6889     }
6890 
6891     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6892 
6893     // Work around floating point types that contain unused padding bytes. This
6894     // is really just `long double` on x86, which is the only fundamental type
6895     // with padding bytes.
6896     if (T->isRealFloatingType()) {
6897       const llvm::fltSemantics &Semantics =
6898           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6899       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
6900       assert(NumBits % 8 == 0);
6901       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
6902       if (NumBytes != SizeOf)
6903         SizeOf = NumBytes;
6904     }
6905 
6906     SmallVector<uint8_t, 8> Bytes;
6907     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
6908       // If this is std::byte or unsigned char, then its okay to store an
6909       // indeterminate value.
6910       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
6911       bool IsUChar =
6912           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
6913                          T->isSpecificBuiltinType(BuiltinType::Char_U));
6914       if (!IsStdByte && !IsUChar) {
6915         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
6916         Info.FFDiag(BCE->getExprLoc(),
6917                     diag::note_constexpr_bit_cast_indet_dest)
6918             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
6919         return None;
6920       }
6921 
6922       return APValue::IndeterminateValue();
6923     }
6924 
6925     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
6926     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
6927 
6928     if (T->isIntegralOrEnumerationType()) {
6929       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
6930 
6931       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
6932       if (IntWidth != Val.getBitWidth()) {
6933         APSInt Truncated = Val.trunc(IntWidth);
6934         if (Truncated.extend(Val.getBitWidth()) != Val)
6935           return unrepresentableValue(QualType(T, 0), Val);
6936         Val = Truncated;
6937       }
6938 
6939       return APValue(Val);
6940     }
6941 
6942     if (T->isRealFloatingType()) {
6943       const llvm::fltSemantics &Semantics =
6944           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6945       return APValue(APFloat(Semantics, Val));
6946     }
6947 
6948     return unsupportedType(QualType(T, 0));
6949   }
6950 
6951   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
6952     const RecordDecl *RD = RTy->getAsRecordDecl();
6953     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6954 
6955     unsigned NumBases = 0;
6956     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6957       NumBases = CXXRD->getNumBases();
6958 
6959     APValue ResultVal(APValue::UninitStruct(), NumBases,
6960                       std::distance(RD->field_begin(), RD->field_end()));
6961 
6962     // Visit the base classes.
6963     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6964       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6965         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6966         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6967         if (BaseDecl->isEmpty() ||
6968             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
6969           continue;
6970 
6971         Optional<APValue> SubObj = visitType(
6972             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
6973         if (!SubObj)
6974           return None;
6975         ResultVal.getStructBase(I) = *SubObj;
6976       }
6977     }
6978 
6979     // Visit the fields.
6980     unsigned FieldIdx = 0;
6981     for (FieldDecl *FD : RD->fields()) {
6982       // FIXME: We don't currently support bit-fields. A lot of the logic for
6983       // this is in CodeGen, so we need to factor it around.
6984       if (FD->isBitField()) {
6985         Info.FFDiag(BCE->getBeginLoc(),
6986                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6987         return None;
6988       }
6989 
6990       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6991       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
6992 
6993       CharUnits FieldOffset =
6994           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
6995           Offset;
6996       QualType FieldTy = FD->getType();
6997       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
6998       if (!SubObj)
6999         return None;
7000       ResultVal.getStructField(FieldIdx) = *SubObj;
7001       ++FieldIdx;
7002     }
7003 
7004     return ResultVal;
7005   }
7006 
7007   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7008     QualType RepresentationType = Ty->getDecl()->getIntegerType();
7009     assert(!RepresentationType.isNull() &&
7010            "enum forward decl should be caught by Sema");
7011     const auto *AsBuiltin =
7012         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7013     // Recurse into the underlying type. Treat std::byte transparently as
7014     // unsigned char.
7015     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7016   }
7017 
7018   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7019     size_t Size = Ty->getSize().getLimitedValue();
7020     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7021 
7022     APValue ArrayValue(APValue::UninitArray(), Size, Size);
7023     for (size_t I = 0; I != Size; ++I) {
7024       Optional<APValue> ElementValue =
7025           visitType(Ty->getElementType(), Offset + I * ElementWidth);
7026       if (!ElementValue)
7027         return None;
7028       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7029     }
7030 
7031     return ArrayValue;
7032   }
7033 
7034   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7035     return unsupportedType(QualType(Ty, 0));
7036   }
7037 
7038   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7039     QualType Can = Ty.getCanonicalType();
7040 
7041     switch (Can->getTypeClass()) {
7042 #define TYPE(Class, Base)                                                      \
7043   case Type::Class:                                                            \
7044     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7045 #define ABSTRACT_TYPE(Class, Base)
7046 #define NON_CANONICAL_TYPE(Class, Base)                                        \
7047   case Type::Class:                                                            \
7048     llvm_unreachable("non-canonical type should be impossible!");
7049 #define DEPENDENT_TYPE(Class, Base)                                            \
7050   case Type::Class:                                                            \
7051     llvm_unreachable(                                                          \
7052         "dependent types aren't supported in the constant evaluator!");
7053 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7054   case Type::Class:                                                            \
7055     llvm_unreachable("either dependent or not canonical!");
7056 #include "clang/AST/TypeNodes.inc"
7057     }
7058     llvm_unreachable("Unhandled Type::TypeClass");
7059   }
7060 
7061 public:
7062   // Pull out a full value of type DstType.
7063   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7064                                    const CastExpr *BCE) {
7065     BufferToAPValueConverter Converter(Info, Buffer, BCE);
7066     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7067   }
7068 };
7069 
7070 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7071                                                  QualType Ty, EvalInfo *Info,
7072                                                  const ASTContext &Ctx,
7073                                                  bool CheckingDest) {
7074   Ty = Ty.getCanonicalType();
7075 
7076   auto diag = [&](int Reason) {
7077     if (Info)
7078       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7079           << CheckingDest << (Reason == 4) << Reason;
7080     return false;
7081   };
7082   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7083     if (Info)
7084       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7085           << NoteTy << Construct << Ty;
7086     return false;
7087   };
7088 
7089   if (Ty->isUnionType())
7090     return diag(0);
7091   if (Ty->isPointerType())
7092     return diag(1);
7093   if (Ty->isMemberPointerType())
7094     return diag(2);
7095   if (Ty.isVolatileQualified())
7096     return diag(3);
7097 
7098   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7099     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7100       for (CXXBaseSpecifier &BS : CXXRD->bases())
7101         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7102                                                   CheckingDest))
7103           return note(1, BS.getType(), BS.getBeginLoc());
7104     }
7105     for (FieldDecl *FD : Record->fields()) {
7106       if (FD->getType()->isReferenceType())
7107         return diag(4);
7108       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7109                                                 CheckingDest))
7110         return note(0, FD->getType(), FD->getBeginLoc());
7111     }
7112   }
7113 
7114   if (Ty->isArrayType() &&
7115       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7116                                             Info, Ctx, CheckingDest))
7117     return false;
7118 
7119   return true;
7120 }
7121 
7122 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7123                                              const ASTContext &Ctx,
7124                                              const CastExpr *BCE) {
7125   bool DestOK = checkBitCastConstexprEligibilityType(
7126       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7127   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7128                                 BCE->getBeginLoc(),
7129                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
7130   return SourceOK;
7131 }
7132 
7133 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7134                                         APValue &SourceValue,
7135                                         const CastExpr *BCE) {
7136   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7137          "no host or target supports non 8-bit chars");
7138   assert(SourceValue.isLValue() &&
7139          "LValueToRValueBitcast requires an lvalue operand!");
7140 
7141   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7142     return false;
7143 
7144   LValue SourceLValue;
7145   APValue SourceRValue;
7146   SourceLValue.setFrom(Info.Ctx, SourceValue);
7147   if (!handleLValueToRValueConversion(
7148           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7149           SourceRValue, /*WantObjectRepresentation=*/true))
7150     return false;
7151 
7152   // Read out SourceValue into a char buffer.
7153   Optional<BitCastBuffer> Buffer =
7154       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7155   if (!Buffer)
7156     return false;
7157 
7158   // Write out the buffer into a new APValue.
7159   Optional<APValue> MaybeDestValue =
7160       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7161   if (!MaybeDestValue)
7162     return false;
7163 
7164   DestValue = std::move(*MaybeDestValue);
7165   return true;
7166 }
7167 
7168 template <class Derived>
7169 class ExprEvaluatorBase
7170   : public ConstStmtVisitor<Derived, bool> {
7171 private:
7172   Derived &getDerived() { return static_cast<Derived&>(*this); }
7173   bool DerivedSuccess(const APValue &V, const Expr *E) {
7174     return getDerived().Success(V, E);
7175   }
7176   bool DerivedZeroInitialization(const Expr *E) {
7177     return getDerived().ZeroInitialization(E);
7178   }
7179 
7180   // Check whether a conditional operator with a non-constant condition is a
7181   // potential constant expression. If neither arm is a potential constant
7182   // expression, then the conditional operator is not either.
7183   template<typename ConditionalOperator>
7184   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7185     assert(Info.checkingPotentialConstantExpression());
7186 
7187     // Speculatively evaluate both arms.
7188     SmallVector<PartialDiagnosticAt, 8> Diag;
7189     {
7190       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7191       StmtVisitorTy::Visit(E->getFalseExpr());
7192       if (Diag.empty())
7193         return;
7194     }
7195 
7196     {
7197       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7198       Diag.clear();
7199       StmtVisitorTy::Visit(E->getTrueExpr());
7200       if (Diag.empty())
7201         return;
7202     }
7203 
7204     Error(E, diag::note_constexpr_conditional_never_const);
7205   }
7206 
7207 
7208   template<typename ConditionalOperator>
7209   bool HandleConditionalOperator(const ConditionalOperator *E) {
7210     bool BoolResult;
7211     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7212       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7213         CheckPotentialConstantConditional(E);
7214         return false;
7215       }
7216       if (Info.noteFailure()) {
7217         StmtVisitorTy::Visit(E->getTrueExpr());
7218         StmtVisitorTy::Visit(E->getFalseExpr());
7219       }
7220       return false;
7221     }
7222 
7223     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7224     return StmtVisitorTy::Visit(EvalExpr);
7225   }
7226 
7227 protected:
7228   EvalInfo &Info;
7229   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7230   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7231 
7232   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7233     return Info.CCEDiag(E, D);
7234   }
7235 
7236   bool ZeroInitialization(const Expr *E) { return Error(E); }
7237 
7238 public:
7239   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7240 
7241   EvalInfo &getEvalInfo() { return Info; }
7242 
7243   /// Report an evaluation error. This should only be called when an error is
7244   /// first discovered. When propagating an error, just return false.
7245   bool Error(const Expr *E, diag::kind D) {
7246     Info.FFDiag(E, D);
7247     return false;
7248   }
7249   bool Error(const Expr *E) {
7250     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7251   }
7252 
7253   bool VisitStmt(const Stmt *) {
7254     llvm_unreachable("Expression evaluator should not be called on stmts");
7255   }
7256   bool VisitExpr(const Expr *E) {
7257     return Error(E);
7258   }
7259 
7260   bool VisitConstantExpr(const ConstantExpr *E) {
7261     if (E->hasAPValueResult())
7262       return DerivedSuccess(E->getAPValueResult(), E);
7263 
7264     return StmtVisitorTy::Visit(E->getSubExpr());
7265   }
7266 
7267   bool VisitParenExpr(const ParenExpr *E)
7268     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7269   bool VisitUnaryExtension(const UnaryOperator *E)
7270     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7271   bool VisitUnaryPlus(const UnaryOperator *E)
7272     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7273   bool VisitChooseExpr(const ChooseExpr *E)
7274     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7275   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7276     { return StmtVisitorTy::Visit(E->getResultExpr()); }
7277   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7278     { return StmtVisitorTy::Visit(E->getReplacement()); }
7279   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7280     TempVersionRAII RAII(*Info.CurrentCall);
7281     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7282     return StmtVisitorTy::Visit(E->getExpr());
7283   }
7284   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7285     TempVersionRAII RAII(*Info.CurrentCall);
7286     // The initializer may not have been parsed yet, or might be erroneous.
7287     if (!E->getExpr())
7288       return Error(E);
7289     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7290     return StmtVisitorTy::Visit(E->getExpr());
7291   }
7292 
7293   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7294     FullExpressionRAII Scope(Info);
7295     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7296   }
7297 
7298   // Temporaries are registered when created, so we don't care about
7299   // CXXBindTemporaryExpr.
7300   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7301     return StmtVisitorTy::Visit(E->getSubExpr());
7302   }
7303 
7304   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7305     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7306     return static_cast<Derived*>(this)->VisitCastExpr(E);
7307   }
7308   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7309     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7310       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7311     return static_cast<Derived*>(this)->VisitCastExpr(E);
7312   }
7313   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7314     return static_cast<Derived*>(this)->VisitCastExpr(E);
7315   }
7316 
7317   bool VisitBinaryOperator(const BinaryOperator *E) {
7318     switch (E->getOpcode()) {
7319     default:
7320       return Error(E);
7321 
7322     case BO_Comma:
7323       VisitIgnoredValue(E->getLHS());
7324       return StmtVisitorTy::Visit(E->getRHS());
7325 
7326     case BO_PtrMemD:
7327     case BO_PtrMemI: {
7328       LValue Obj;
7329       if (!HandleMemberPointerAccess(Info, E, Obj))
7330         return false;
7331       APValue Result;
7332       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7333         return false;
7334       return DerivedSuccess(Result, E);
7335     }
7336     }
7337   }
7338 
7339   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7340     return StmtVisitorTy::Visit(E->getSemanticForm());
7341   }
7342 
7343   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7344     // Evaluate and cache the common expression. We treat it as a temporary,
7345     // even though it's not quite the same thing.
7346     LValue CommonLV;
7347     if (!Evaluate(Info.CurrentCall->createTemporary(
7348                       E->getOpaqueValue(),
7349                       getStorageType(Info.Ctx, E->getOpaqueValue()),
7350                       ScopeKind::FullExpression, CommonLV),
7351                   Info, E->getCommon()))
7352       return false;
7353 
7354     return HandleConditionalOperator(E);
7355   }
7356 
7357   bool VisitConditionalOperator(const ConditionalOperator *E) {
7358     bool IsBcpCall = false;
7359     // If the condition (ignoring parens) is a __builtin_constant_p call,
7360     // the result is a constant expression if it can be folded without
7361     // side-effects. This is an important GNU extension. See GCC PR38377
7362     // for discussion.
7363     if (const CallExpr *CallCE =
7364           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7365       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7366         IsBcpCall = true;
7367 
7368     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7369     // constant expression; we can't check whether it's potentially foldable.
7370     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7371     // it would return 'false' in this mode.
7372     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7373       return false;
7374 
7375     FoldConstant Fold(Info, IsBcpCall);
7376     if (!HandleConditionalOperator(E)) {
7377       Fold.keepDiagnostics();
7378       return false;
7379     }
7380 
7381     return true;
7382   }
7383 
7384   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7385     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7386       return DerivedSuccess(*Value, E);
7387 
7388     const Expr *Source = E->getSourceExpr();
7389     if (!Source)
7390       return Error(E);
7391     if (Source == E) { // sanity checking.
7392       assert(0 && "OpaqueValueExpr recursively refers to itself");
7393       return Error(E);
7394     }
7395     return StmtVisitorTy::Visit(Source);
7396   }
7397 
7398   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7399     for (const Expr *SemE : E->semantics()) {
7400       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7401         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7402         // result expression: there could be two different LValues that would
7403         // refer to the same object in that case, and we can't model that.
7404         if (SemE == E->getResultExpr())
7405           return Error(E);
7406 
7407         // Unique OVEs get evaluated if and when we encounter them when
7408         // emitting the rest of the semantic form, rather than eagerly.
7409         if (OVE->isUnique())
7410           continue;
7411 
7412         LValue LV;
7413         if (!Evaluate(Info.CurrentCall->createTemporary(
7414                           OVE, getStorageType(Info.Ctx, OVE),
7415                           ScopeKind::FullExpression, LV),
7416                       Info, OVE->getSourceExpr()))
7417           return false;
7418       } else if (SemE == E->getResultExpr()) {
7419         if (!StmtVisitorTy::Visit(SemE))
7420           return false;
7421       } else {
7422         if (!EvaluateIgnoredValue(Info, SemE))
7423           return false;
7424       }
7425     }
7426     return true;
7427   }
7428 
7429   bool VisitCallExpr(const CallExpr *E) {
7430     APValue Result;
7431     if (!handleCallExpr(E, Result, nullptr))
7432       return false;
7433     return DerivedSuccess(Result, E);
7434   }
7435 
7436   bool handleCallExpr(const CallExpr *E, APValue &Result,
7437                      const LValue *ResultSlot) {
7438     CallScopeRAII CallScope(Info);
7439 
7440     const Expr *Callee = E->getCallee()->IgnoreParens();
7441     QualType CalleeType = Callee->getType();
7442 
7443     const FunctionDecl *FD = nullptr;
7444     LValue *This = nullptr, ThisVal;
7445     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7446     bool HasQualifier = false;
7447 
7448     CallRef Call;
7449 
7450     // Extract function decl and 'this' pointer from the callee.
7451     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7452       const CXXMethodDecl *Member = nullptr;
7453       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7454         // Explicit bound member calls, such as x.f() or p->g();
7455         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7456           return false;
7457         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7458         if (!Member)
7459           return Error(Callee);
7460         This = &ThisVal;
7461         HasQualifier = ME->hasQualifier();
7462       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7463         // Indirect bound member calls ('.*' or '->*').
7464         const ValueDecl *D =
7465             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7466         if (!D)
7467           return false;
7468         Member = dyn_cast<CXXMethodDecl>(D);
7469         if (!Member)
7470           return Error(Callee);
7471         This = &ThisVal;
7472       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7473         if (!Info.getLangOpts().CPlusPlus20)
7474           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7475         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7476                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7477       } else
7478         return Error(Callee);
7479       FD = Member;
7480     } else if (CalleeType->isFunctionPointerType()) {
7481       LValue CalleeLV;
7482       if (!EvaluatePointer(Callee, CalleeLV, Info))
7483         return false;
7484 
7485       if (!CalleeLV.getLValueOffset().isZero())
7486         return Error(Callee);
7487       FD = dyn_cast_or_null<FunctionDecl>(
7488           CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7489       if (!FD)
7490         return Error(Callee);
7491       // Don't call function pointers which have been cast to some other type.
7492       // Per DR (no number yet), the caller and callee can differ in noexcept.
7493       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7494         CalleeType->getPointeeType(), FD->getType())) {
7495         return Error(E);
7496       }
7497 
7498       // For an (overloaded) assignment expression, evaluate the RHS before the
7499       // LHS.
7500       auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7501       if (OCE && OCE->isAssignmentOp()) {
7502         assert(Args.size() == 2 && "wrong number of arguments in assignment");
7503         Call = Info.CurrentCall->createCall(FD);
7504         if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7505                           Info, FD, /*RightToLeft=*/true))
7506           return false;
7507       }
7508 
7509       // Overloaded operator calls to member functions are represented as normal
7510       // calls with '*this' as the first argument.
7511       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7512       if (MD && !MD->isStatic()) {
7513         // FIXME: When selecting an implicit conversion for an overloaded
7514         // operator delete, we sometimes try to evaluate calls to conversion
7515         // operators without a 'this' parameter!
7516         if (Args.empty())
7517           return Error(E);
7518 
7519         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7520           return false;
7521         This = &ThisVal;
7522         Args = Args.slice(1);
7523       } else if (MD && MD->isLambdaStaticInvoker()) {
7524         // Map the static invoker for the lambda back to the call operator.
7525         // Conveniently, we don't have to slice out the 'this' argument (as is
7526         // being done for the non-static case), since a static member function
7527         // doesn't have an implicit argument passed in.
7528         const CXXRecordDecl *ClosureClass = MD->getParent();
7529         assert(
7530             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7531             "Number of captures must be zero for conversion to function-ptr");
7532 
7533         const CXXMethodDecl *LambdaCallOp =
7534             ClosureClass->getLambdaCallOperator();
7535 
7536         // Set 'FD', the function that will be called below, to the call
7537         // operator.  If the closure object represents a generic lambda, find
7538         // the corresponding specialization of the call operator.
7539 
7540         if (ClosureClass->isGenericLambda()) {
7541           assert(MD->isFunctionTemplateSpecialization() &&
7542                  "A generic lambda's static-invoker function must be a "
7543                  "template specialization");
7544           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7545           FunctionTemplateDecl *CallOpTemplate =
7546               LambdaCallOp->getDescribedFunctionTemplate();
7547           void *InsertPos = nullptr;
7548           FunctionDecl *CorrespondingCallOpSpecialization =
7549               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7550           assert(CorrespondingCallOpSpecialization &&
7551                  "We must always have a function call operator specialization "
7552                  "that corresponds to our static invoker specialization");
7553           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7554         } else
7555           FD = LambdaCallOp;
7556       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7557         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7558             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7559           LValue Ptr;
7560           if (!HandleOperatorNewCall(Info, E, Ptr))
7561             return false;
7562           Ptr.moveInto(Result);
7563           return CallScope.destroy();
7564         } else {
7565           return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7566         }
7567       }
7568     } else
7569       return Error(E);
7570 
7571     // Evaluate the arguments now if we've not already done so.
7572     if (!Call) {
7573       Call = Info.CurrentCall->createCall(FD);
7574       if (!EvaluateArgs(Args, Call, Info, FD))
7575         return false;
7576     }
7577 
7578     SmallVector<QualType, 4> CovariantAdjustmentPath;
7579     if (This) {
7580       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7581       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7582         // Perform virtual dispatch, if necessary.
7583         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7584                                    CovariantAdjustmentPath);
7585         if (!FD)
7586           return false;
7587       } else {
7588         // Check that the 'this' pointer points to an object of the right type.
7589         // FIXME: If this is an assignment operator call, we may need to change
7590         // the active union member before we check this.
7591         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7592           return false;
7593       }
7594     }
7595 
7596     // Destructor calls are different enough that they have their own codepath.
7597     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7598       assert(This && "no 'this' pointer for destructor call");
7599       return HandleDestruction(Info, E, *This,
7600                                Info.Ctx.getRecordType(DD->getParent())) &&
7601              CallScope.destroy();
7602     }
7603 
7604     const FunctionDecl *Definition = nullptr;
7605     Stmt *Body = FD->getBody(Definition);
7606 
7607     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7608         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
7609                             Body, Info, Result, ResultSlot))
7610       return false;
7611 
7612     if (!CovariantAdjustmentPath.empty() &&
7613         !HandleCovariantReturnAdjustment(Info, E, Result,
7614                                          CovariantAdjustmentPath))
7615       return false;
7616 
7617     return CallScope.destroy();
7618   }
7619 
7620   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7621     return StmtVisitorTy::Visit(E->getInitializer());
7622   }
7623   bool VisitInitListExpr(const InitListExpr *E) {
7624     if (E->getNumInits() == 0)
7625       return DerivedZeroInitialization(E);
7626     if (E->getNumInits() == 1)
7627       return StmtVisitorTy::Visit(E->getInit(0));
7628     return Error(E);
7629   }
7630   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7631     return DerivedZeroInitialization(E);
7632   }
7633   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7634     return DerivedZeroInitialization(E);
7635   }
7636   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7637     return DerivedZeroInitialization(E);
7638   }
7639 
7640   /// A member expression where the object is a prvalue is itself a prvalue.
7641   bool VisitMemberExpr(const MemberExpr *E) {
7642     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7643            "missing temporary materialization conversion");
7644     assert(!E->isArrow() && "missing call to bound member function?");
7645 
7646     APValue Val;
7647     if (!Evaluate(Val, Info, E->getBase()))
7648       return false;
7649 
7650     QualType BaseTy = E->getBase()->getType();
7651 
7652     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7653     if (!FD) return Error(E);
7654     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7655     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7656            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7657 
7658     // Note: there is no lvalue base here. But this case should only ever
7659     // happen in C or in C++98, where we cannot be evaluating a constexpr
7660     // constructor, which is the only case the base matters.
7661     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7662     SubobjectDesignator Designator(BaseTy);
7663     Designator.addDeclUnchecked(FD);
7664 
7665     APValue Result;
7666     return extractSubobject(Info, E, Obj, Designator, Result) &&
7667            DerivedSuccess(Result, E);
7668   }
7669 
7670   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7671     APValue Val;
7672     if (!Evaluate(Val, Info, E->getBase()))
7673       return false;
7674 
7675     if (Val.isVector()) {
7676       SmallVector<uint32_t, 4> Indices;
7677       E->getEncodedElementAccess(Indices);
7678       if (Indices.size() == 1) {
7679         // Return scalar.
7680         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7681       } else {
7682         // Construct new APValue vector.
7683         SmallVector<APValue, 4> Elts;
7684         for (unsigned I = 0; I < Indices.size(); ++I) {
7685           Elts.push_back(Val.getVectorElt(Indices[I]));
7686         }
7687         APValue VecResult(Elts.data(), Indices.size());
7688         return DerivedSuccess(VecResult, E);
7689       }
7690     }
7691 
7692     return false;
7693   }
7694 
7695   bool VisitCastExpr(const CastExpr *E) {
7696     switch (E->getCastKind()) {
7697     default:
7698       break;
7699 
7700     case CK_AtomicToNonAtomic: {
7701       APValue AtomicVal;
7702       // This does not need to be done in place even for class/array types:
7703       // atomic-to-non-atomic conversion implies copying the object
7704       // representation.
7705       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7706         return false;
7707       return DerivedSuccess(AtomicVal, E);
7708     }
7709 
7710     case CK_NoOp:
7711     case CK_UserDefinedConversion:
7712       return StmtVisitorTy::Visit(E->getSubExpr());
7713 
7714     case CK_LValueToRValue: {
7715       LValue LVal;
7716       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7717         return false;
7718       APValue RVal;
7719       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7720       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7721                                           LVal, RVal))
7722         return false;
7723       return DerivedSuccess(RVal, E);
7724     }
7725     case CK_LValueToRValueBitCast: {
7726       APValue DestValue, SourceValue;
7727       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7728         return false;
7729       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7730         return false;
7731       return DerivedSuccess(DestValue, E);
7732     }
7733 
7734     case CK_AddressSpaceConversion: {
7735       APValue Value;
7736       if (!Evaluate(Value, Info, E->getSubExpr()))
7737         return false;
7738       return DerivedSuccess(Value, E);
7739     }
7740     }
7741 
7742     return Error(E);
7743   }
7744 
7745   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7746     return VisitUnaryPostIncDec(UO);
7747   }
7748   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7749     return VisitUnaryPostIncDec(UO);
7750   }
7751   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7752     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7753       return Error(UO);
7754 
7755     LValue LVal;
7756     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7757       return false;
7758     APValue RVal;
7759     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7760                       UO->isIncrementOp(), &RVal))
7761       return false;
7762     return DerivedSuccess(RVal, UO);
7763   }
7764 
7765   bool VisitStmtExpr(const StmtExpr *E) {
7766     // We will have checked the full-expressions inside the statement expression
7767     // when they were completed, and don't need to check them again now.
7768     if (Info.checkingForUndefinedBehavior())
7769       return Error(E);
7770 
7771     const CompoundStmt *CS = E->getSubStmt();
7772     if (CS->body_empty())
7773       return true;
7774 
7775     BlockScopeRAII Scope(Info);
7776     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7777                                            BE = CS->body_end();
7778          /**/; ++BI) {
7779       if (BI + 1 == BE) {
7780         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7781         if (!FinalExpr) {
7782           Info.FFDiag((*BI)->getBeginLoc(),
7783                       diag::note_constexpr_stmt_expr_unsupported);
7784           return false;
7785         }
7786         return this->Visit(FinalExpr) && Scope.destroy();
7787       }
7788 
7789       APValue ReturnValue;
7790       StmtResult Result = { ReturnValue, nullptr };
7791       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7792       if (ESR != ESR_Succeeded) {
7793         // FIXME: If the statement-expression terminated due to 'return',
7794         // 'break', or 'continue', it would be nice to propagate that to
7795         // the outer statement evaluation rather than bailing out.
7796         if (ESR != ESR_Failed)
7797           Info.FFDiag((*BI)->getBeginLoc(),
7798                       diag::note_constexpr_stmt_expr_unsupported);
7799         return false;
7800       }
7801     }
7802 
7803     llvm_unreachable("Return from function from the loop above.");
7804   }
7805 
7806   /// Visit a value which is evaluated, but whose value is ignored.
7807   void VisitIgnoredValue(const Expr *E) {
7808     EvaluateIgnoredValue(Info, E);
7809   }
7810 
7811   /// Potentially visit a MemberExpr's base expression.
7812   void VisitIgnoredBaseExpression(const Expr *E) {
7813     // While MSVC doesn't evaluate the base expression, it does diagnose the
7814     // presence of side-effecting behavior.
7815     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7816       return;
7817     VisitIgnoredValue(E);
7818   }
7819 };
7820 
7821 } // namespace
7822 
7823 //===----------------------------------------------------------------------===//
7824 // Common base class for lvalue and temporary evaluation.
7825 //===----------------------------------------------------------------------===//
7826 namespace {
7827 template<class Derived>
7828 class LValueExprEvaluatorBase
7829   : public ExprEvaluatorBase<Derived> {
7830 protected:
7831   LValue &Result;
7832   bool InvalidBaseOK;
7833   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7834   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7835 
7836   bool Success(APValue::LValueBase B) {
7837     Result.set(B);
7838     return true;
7839   }
7840 
7841   bool evaluatePointer(const Expr *E, LValue &Result) {
7842     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7843   }
7844 
7845 public:
7846   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7847       : ExprEvaluatorBaseTy(Info), Result(Result),
7848         InvalidBaseOK(InvalidBaseOK) {}
7849 
7850   bool Success(const APValue &V, const Expr *E) {
7851     Result.setFrom(this->Info.Ctx, V);
7852     return true;
7853   }
7854 
7855   bool VisitMemberExpr(const MemberExpr *E) {
7856     // Handle non-static data members.
7857     QualType BaseTy;
7858     bool EvalOK;
7859     if (E->isArrow()) {
7860       EvalOK = evaluatePointer(E->getBase(), Result);
7861       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
7862     } else if (E->getBase()->isRValue()) {
7863       assert(E->getBase()->getType()->isRecordType());
7864       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
7865       BaseTy = E->getBase()->getType();
7866     } else {
7867       EvalOK = this->Visit(E->getBase());
7868       BaseTy = E->getBase()->getType();
7869     }
7870     if (!EvalOK) {
7871       if (!InvalidBaseOK)
7872         return false;
7873       Result.setInvalid(E);
7874       return true;
7875     }
7876 
7877     const ValueDecl *MD = E->getMemberDecl();
7878     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
7879       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7880              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7881       (void)BaseTy;
7882       if (!HandleLValueMember(this->Info, E, Result, FD))
7883         return false;
7884     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
7885       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
7886         return false;
7887     } else
7888       return this->Error(E);
7889 
7890     if (MD->getType()->isReferenceType()) {
7891       APValue RefValue;
7892       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
7893                                           RefValue))
7894         return false;
7895       return Success(RefValue, E);
7896     }
7897     return true;
7898   }
7899 
7900   bool VisitBinaryOperator(const BinaryOperator *E) {
7901     switch (E->getOpcode()) {
7902     default:
7903       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7904 
7905     case BO_PtrMemD:
7906     case BO_PtrMemI:
7907       return HandleMemberPointerAccess(this->Info, E, Result);
7908     }
7909   }
7910 
7911   bool VisitCastExpr(const CastExpr *E) {
7912     switch (E->getCastKind()) {
7913     default:
7914       return ExprEvaluatorBaseTy::VisitCastExpr(E);
7915 
7916     case CK_DerivedToBase:
7917     case CK_UncheckedDerivedToBase:
7918       if (!this->Visit(E->getSubExpr()))
7919         return false;
7920 
7921       // Now figure out the necessary offset to add to the base LV to get from
7922       // the derived class to the base class.
7923       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
7924                                   Result);
7925     }
7926   }
7927 };
7928 }
7929 
7930 //===----------------------------------------------------------------------===//
7931 // LValue Evaluation
7932 //
7933 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
7934 // function designators (in C), decl references to void objects (in C), and
7935 // temporaries (if building with -Wno-address-of-temporary).
7936 //
7937 // LValue evaluation produces values comprising a base expression of one of the
7938 // following types:
7939 // - Declarations
7940 //  * VarDecl
7941 //  * FunctionDecl
7942 // - Literals
7943 //  * CompoundLiteralExpr in C (and in global scope in C++)
7944 //  * StringLiteral
7945 //  * PredefinedExpr
7946 //  * ObjCStringLiteralExpr
7947 //  * ObjCEncodeExpr
7948 //  * AddrLabelExpr
7949 //  * BlockExpr
7950 //  * CallExpr for a MakeStringConstant builtin
7951 // - typeid(T) expressions, as TypeInfoLValues
7952 // - Locals and temporaries
7953 //  * MaterializeTemporaryExpr
7954 //  * Any Expr, with a CallIndex indicating the function in which the temporary
7955 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
7956 //    from the AST (FIXME).
7957 //  * A MaterializeTemporaryExpr that has static storage duration, with no
7958 //    CallIndex, for a lifetime-extended temporary.
7959 //  * The ConstantExpr that is currently being evaluated during evaluation of an
7960 //    immediate invocation.
7961 // plus an offset in bytes.
7962 //===----------------------------------------------------------------------===//
7963 namespace {
7964 class LValueExprEvaluator
7965   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
7966 public:
7967   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
7968     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
7969 
7970   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
7971   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
7972 
7973   bool VisitDeclRefExpr(const DeclRefExpr *E);
7974   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
7975   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
7976   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
7977   bool VisitMemberExpr(const MemberExpr *E);
7978   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
7979   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
7980   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
7981   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
7982   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
7983   bool VisitUnaryDeref(const UnaryOperator *E);
7984   bool VisitUnaryReal(const UnaryOperator *E);
7985   bool VisitUnaryImag(const UnaryOperator *E);
7986   bool VisitUnaryPreInc(const UnaryOperator *UO) {
7987     return VisitUnaryPreIncDec(UO);
7988   }
7989   bool VisitUnaryPreDec(const UnaryOperator *UO) {
7990     return VisitUnaryPreIncDec(UO);
7991   }
7992   bool VisitBinAssign(const BinaryOperator *BO);
7993   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
7994 
7995   bool VisitCastExpr(const CastExpr *E) {
7996     switch (E->getCastKind()) {
7997     default:
7998       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
7999 
8000     case CK_LValueBitCast:
8001       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8002       if (!Visit(E->getSubExpr()))
8003         return false;
8004       Result.Designator.setInvalid();
8005       return true;
8006 
8007     case CK_BaseToDerived:
8008       if (!Visit(E->getSubExpr()))
8009         return false;
8010       return HandleBaseToDerivedCast(Info, E, Result);
8011 
8012     case CK_Dynamic:
8013       if (!Visit(E->getSubExpr()))
8014         return false;
8015       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8016     }
8017   }
8018 };
8019 } // end anonymous namespace
8020 
8021 /// Evaluate an expression as an lvalue. This can be legitimately called on
8022 /// expressions which are not glvalues, in three cases:
8023 ///  * function designators in C, and
8024 ///  * "extern void" objects
8025 ///  * @selector() expressions in Objective-C
8026 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8027                            bool InvalidBaseOK) {
8028   assert(E->isGLValue() || E->getType()->isFunctionType() ||
8029          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
8030   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8031 }
8032 
8033 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8034   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
8035     return Success(FD);
8036   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
8037     return VisitVarDecl(E, VD);
8038   if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
8039     return Visit(BD->getBinding());
8040   if (const MSGuidDecl *GD = dyn_cast<MSGuidDecl>(E->getDecl()))
8041     return Success(GD);
8042   return Error(E);
8043 }
8044 
8045 
8046 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8047 
8048   // If we are within a lambda's call operator, check whether the 'VD' referred
8049   // to within 'E' actually represents a lambda-capture that maps to a
8050   // data-member/field within the closure object, and if so, evaluate to the
8051   // field or what the field refers to.
8052   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8053       isa<DeclRefExpr>(E) &&
8054       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8055     // We don't always have a complete capture-map when checking or inferring if
8056     // the function call operator meets the requirements of a constexpr function
8057     // - but we don't need to evaluate the captures to determine constexprness
8058     // (dcl.constexpr C++17).
8059     if (Info.checkingPotentialConstantExpression())
8060       return false;
8061 
8062     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8063       // Start with 'Result' referring to the complete closure object...
8064       Result = *Info.CurrentCall->This;
8065       // ... then update it to refer to the field of the closure object
8066       // that represents the capture.
8067       if (!HandleLValueMember(Info, E, Result, FD))
8068         return false;
8069       // And if the field is of reference type, update 'Result' to refer to what
8070       // the field refers to.
8071       if (FD->getType()->isReferenceType()) {
8072         APValue RVal;
8073         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8074                                             RVal))
8075           return false;
8076         Result.setFrom(Info.Ctx, RVal);
8077       }
8078       return true;
8079     }
8080   }
8081 
8082   CallStackFrame *Frame = nullptr;
8083   unsigned Version = 0;
8084   if (VD->hasLocalStorage()) {
8085     // Only if a local variable was declared in the function currently being
8086     // evaluated, do we expect to be able to find its value in the current
8087     // frame. (Otherwise it was likely declared in an enclosing context and
8088     // could either have a valid evaluatable value (for e.g. a constexpr
8089     // variable) or be ill-formed (and trigger an appropriate evaluation
8090     // diagnostic)).
8091     CallStackFrame *CurrFrame = Info.CurrentCall;
8092     if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8093       // Function parameters are stored in some caller's frame. (Usually the
8094       // immediate caller, but for an inherited constructor they may be more
8095       // distant.)
8096       if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8097         if (CurrFrame->Arguments) {
8098           VD = CurrFrame->Arguments.getOrigParam(PVD);
8099           Frame =
8100               Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8101           Version = CurrFrame->Arguments.Version;
8102         }
8103       } else {
8104         Frame = CurrFrame;
8105         Version = CurrFrame->getCurrentTemporaryVersion(VD);
8106       }
8107     }
8108   }
8109 
8110   if (!VD->getType()->isReferenceType()) {
8111     if (Frame) {
8112       Result.set({VD, Frame->Index, Version});
8113       return true;
8114     }
8115     return Success(VD);
8116   }
8117 
8118   if (!Info.getLangOpts().CPlusPlus11) {
8119     Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8120         << VD << VD->getType();
8121     Info.Note(VD->getLocation(), diag::note_declared_at);
8122   }
8123 
8124   APValue *V;
8125   if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8126     return false;
8127   if (!V->hasValue()) {
8128     // FIXME: Is it possible for V to be indeterminate here? If so, we should
8129     // adjust the diagnostic to say that.
8130     if (!Info.checkingPotentialConstantExpression())
8131       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8132     return false;
8133   }
8134   return Success(*V, E);
8135 }
8136 
8137 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8138     const MaterializeTemporaryExpr *E) {
8139   // Walk through the expression to find the materialized temporary itself.
8140   SmallVector<const Expr *, 2> CommaLHSs;
8141   SmallVector<SubobjectAdjustment, 2> Adjustments;
8142   const Expr *Inner =
8143       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8144 
8145   // If we passed any comma operators, evaluate their LHSs.
8146   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
8147     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
8148       return false;
8149 
8150   // A materialized temporary with static storage duration can appear within the
8151   // result of a constant expression evaluation, so we need to preserve its
8152   // value for use outside this evaluation.
8153   APValue *Value;
8154   if (E->getStorageDuration() == SD_Static) {
8155     // FIXME: What about SD_Thread?
8156     Value = E->getOrCreateValue(true);
8157     *Value = APValue();
8158     Result.set(E);
8159   } else {
8160     Value = &Info.CurrentCall->createTemporary(
8161         E, E->getType(),
8162         E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8163                                                      : ScopeKind::Block,
8164         Result);
8165   }
8166 
8167   QualType Type = Inner->getType();
8168 
8169   // Materialize the temporary itself.
8170   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8171     *Value = APValue();
8172     return false;
8173   }
8174 
8175   // Adjust our lvalue to refer to the desired subobject.
8176   for (unsigned I = Adjustments.size(); I != 0; /**/) {
8177     --I;
8178     switch (Adjustments[I].Kind) {
8179     case SubobjectAdjustment::DerivedToBaseAdjustment:
8180       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8181                                 Type, Result))
8182         return false;
8183       Type = Adjustments[I].DerivedToBase.BasePath->getType();
8184       break;
8185 
8186     case SubobjectAdjustment::FieldAdjustment:
8187       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8188         return false;
8189       Type = Adjustments[I].Field->getType();
8190       break;
8191 
8192     case SubobjectAdjustment::MemberPointerAdjustment:
8193       if (!HandleMemberPointerAccess(this->Info, Type, Result,
8194                                      Adjustments[I].Ptr.RHS))
8195         return false;
8196       Type = Adjustments[I].Ptr.MPT->getPointeeType();
8197       break;
8198     }
8199   }
8200 
8201   return true;
8202 }
8203 
8204 bool
8205 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8206   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8207          "lvalue compound literal in c++?");
8208   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8209   // only see this when folding in C, so there's no standard to follow here.
8210   return Success(E);
8211 }
8212 
8213 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8214   TypeInfoLValue TypeInfo;
8215 
8216   if (!E->isPotentiallyEvaluated()) {
8217     if (E->isTypeOperand())
8218       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8219     else
8220       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8221   } else {
8222     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8223       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8224         << E->getExprOperand()->getType()
8225         << E->getExprOperand()->getSourceRange();
8226     }
8227 
8228     if (!Visit(E->getExprOperand()))
8229       return false;
8230 
8231     Optional<DynamicType> DynType =
8232         ComputeDynamicType(Info, E, Result, AK_TypeId);
8233     if (!DynType)
8234       return false;
8235 
8236     TypeInfo =
8237         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8238   }
8239 
8240   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8241 }
8242 
8243 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8244   return Success(E->getGuidDecl());
8245 }
8246 
8247 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8248   // Handle static data members.
8249   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8250     VisitIgnoredBaseExpression(E->getBase());
8251     return VisitVarDecl(E, VD);
8252   }
8253 
8254   // Handle static member functions.
8255   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8256     if (MD->isStatic()) {
8257       VisitIgnoredBaseExpression(E->getBase());
8258       return Success(MD);
8259     }
8260   }
8261 
8262   // Handle non-static data members.
8263   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8264 }
8265 
8266 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8267   // FIXME: Deal with vectors as array subscript bases.
8268   if (E->getBase()->getType()->isVectorType())
8269     return Error(E);
8270 
8271   APSInt Index;
8272   bool Success = true;
8273 
8274   // C++17's rules require us to evaluate the LHS first, regardless of which
8275   // side is the base.
8276   for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8277     if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8278                                 : !EvaluateInteger(SubExpr, Index, Info)) {
8279       if (!Info.noteFailure())
8280         return false;
8281       Success = false;
8282     }
8283   }
8284 
8285   return Success &&
8286          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8287 }
8288 
8289 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8290   return evaluatePointer(E->getSubExpr(), Result);
8291 }
8292 
8293 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8294   if (!Visit(E->getSubExpr()))
8295     return false;
8296   // __real is a no-op on scalar lvalues.
8297   if (E->getSubExpr()->getType()->isAnyComplexType())
8298     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8299   return true;
8300 }
8301 
8302 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8303   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8304          "lvalue __imag__ on scalar?");
8305   if (!Visit(E->getSubExpr()))
8306     return false;
8307   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8308   return true;
8309 }
8310 
8311 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8312   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8313     return Error(UO);
8314 
8315   if (!this->Visit(UO->getSubExpr()))
8316     return false;
8317 
8318   return handleIncDec(
8319       this->Info, UO, Result, UO->getSubExpr()->getType(),
8320       UO->isIncrementOp(), nullptr);
8321 }
8322 
8323 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8324     const CompoundAssignOperator *CAO) {
8325   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8326     return Error(CAO);
8327 
8328   bool Success = true;
8329 
8330   // C++17 onwards require that we evaluate the RHS first.
8331   APValue RHS;
8332   if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8333     if (!Info.noteFailure())
8334       return false;
8335     Success = false;
8336   }
8337 
8338   // The overall lvalue result is the result of evaluating the LHS.
8339   if (!this->Visit(CAO->getLHS()) || !Success)
8340     return false;
8341 
8342   return handleCompoundAssignment(
8343       this->Info, CAO,
8344       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8345       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8346 }
8347 
8348 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8349   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8350     return Error(E);
8351 
8352   bool Success = true;
8353 
8354   // C++17 onwards require that we evaluate the RHS first.
8355   APValue NewVal;
8356   if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8357     if (!Info.noteFailure())
8358       return false;
8359     Success = false;
8360   }
8361 
8362   if (!this->Visit(E->getLHS()) || !Success)
8363     return false;
8364 
8365   if (Info.getLangOpts().CPlusPlus20 &&
8366       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8367     return false;
8368 
8369   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8370                           NewVal);
8371 }
8372 
8373 //===----------------------------------------------------------------------===//
8374 // Pointer Evaluation
8375 //===----------------------------------------------------------------------===//
8376 
8377 /// Attempts to compute the number of bytes available at the pointer
8378 /// returned by a function with the alloc_size attribute. Returns true if we
8379 /// were successful. Places an unsigned number into `Result`.
8380 ///
8381 /// This expects the given CallExpr to be a call to a function with an
8382 /// alloc_size attribute.
8383 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8384                                             const CallExpr *Call,
8385                                             llvm::APInt &Result) {
8386   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8387 
8388   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8389   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8390   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8391   if (Call->getNumArgs() <= SizeArgNo)
8392     return false;
8393 
8394   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8395     Expr::EvalResult ExprResult;
8396     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8397       return false;
8398     Into = ExprResult.Val.getInt();
8399     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8400       return false;
8401     Into = Into.zextOrSelf(BitsInSizeT);
8402     return true;
8403   };
8404 
8405   APSInt SizeOfElem;
8406   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8407     return false;
8408 
8409   if (!AllocSize->getNumElemsParam().isValid()) {
8410     Result = std::move(SizeOfElem);
8411     return true;
8412   }
8413 
8414   APSInt NumberOfElems;
8415   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8416   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8417     return false;
8418 
8419   bool Overflow;
8420   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8421   if (Overflow)
8422     return false;
8423 
8424   Result = std::move(BytesAvailable);
8425   return true;
8426 }
8427 
8428 /// Convenience function. LVal's base must be a call to an alloc_size
8429 /// function.
8430 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8431                                             const LValue &LVal,
8432                                             llvm::APInt &Result) {
8433   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8434          "Can't get the size of a non alloc_size function");
8435   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8436   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8437   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8438 }
8439 
8440 /// Attempts to evaluate the given LValueBase as the result of a call to
8441 /// a function with the alloc_size attribute. If it was possible to do so, this
8442 /// function will return true, make Result's Base point to said function call,
8443 /// and mark Result's Base as invalid.
8444 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8445                                       LValue &Result) {
8446   if (Base.isNull())
8447     return false;
8448 
8449   // Because we do no form of static analysis, we only support const variables.
8450   //
8451   // Additionally, we can't support parameters, nor can we support static
8452   // variables (in the latter case, use-before-assign isn't UB; in the former,
8453   // we have no clue what they'll be assigned to).
8454   const auto *VD =
8455       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8456   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8457     return false;
8458 
8459   const Expr *Init = VD->getAnyInitializer();
8460   if (!Init)
8461     return false;
8462 
8463   const Expr *E = Init->IgnoreParens();
8464   if (!tryUnwrapAllocSizeCall(E))
8465     return false;
8466 
8467   // Store E instead of E unwrapped so that the type of the LValue's base is
8468   // what the user wanted.
8469   Result.setInvalid(E);
8470 
8471   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8472   Result.addUnsizedArray(Info, E, Pointee);
8473   return true;
8474 }
8475 
8476 namespace {
8477 class PointerExprEvaluator
8478   : public ExprEvaluatorBase<PointerExprEvaluator> {
8479   LValue &Result;
8480   bool InvalidBaseOK;
8481 
8482   bool Success(const Expr *E) {
8483     Result.set(E);
8484     return true;
8485   }
8486 
8487   bool evaluateLValue(const Expr *E, LValue &Result) {
8488     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8489   }
8490 
8491   bool evaluatePointer(const Expr *E, LValue &Result) {
8492     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8493   }
8494 
8495   bool visitNonBuiltinCallExpr(const CallExpr *E);
8496 public:
8497 
8498   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8499       : ExprEvaluatorBaseTy(info), Result(Result),
8500         InvalidBaseOK(InvalidBaseOK) {}
8501 
8502   bool Success(const APValue &V, const Expr *E) {
8503     Result.setFrom(Info.Ctx, V);
8504     return true;
8505   }
8506   bool ZeroInitialization(const Expr *E) {
8507     Result.setNull(Info.Ctx, E->getType());
8508     return true;
8509   }
8510 
8511   bool VisitBinaryOperator(const BinaryOperator *E);
8512   bool VisitCastExpr(const CastExpr* E);
8513   bool VisitUnaryAddrOf(const UnaryOperator *E);
8514   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8515       { return Success(E); }
8516   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8517     if (E->isExpressibleAsConstantInitializer())
8518       return Success(E);
8519     if (Info.noteFailure())
8520       EvaluateIgnoredValue(Info, E->getSubExpr());
8521     return Error(E);
8522   }
8523   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8524       { return Success(E); }
8525   bool VisitCallExpr(const CallExpr *E);
8526   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8527   bool VisitBlockExpr(const BlockExpr *E) {
8528     if (!E->getBlockDecl()->hasCaptures())
8529       return Success(E);
8530     return Error(E);
8531   }
8532   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8533     // Can't look at 'this' when checking a potential constant expression.
8534     if (Info.checkingPotentialConstantExpression())
8535       return false;
8536     if (!Info.CurrentCall->This) {
8537       if (Info.getLangOpts().CPlusPlus11)
8538         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8539       else
8540         Info.FFDiag(E);
8541       return false;
8542     }
8543     Result = *Info.CurrentCall->This;
8544     // If we are inside a lambda's call operator, the 'this' expression refers
8545     // to the enclosing '*this' object (either by value or reference) which is
8546     // either copied into the closure object's field that represents the '*this'
8547     // or refers to '*this'.
8548     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8549       // Ensure we actually have captured 'this'. (an error will have
8550       // been previously reported if not).
8551       if (!Info.CurrentCall->LambdaThisCaptureField)
8552         return false;
8553 
8554       // Update 'Result' to refer to the data member/field of the closure object
8555       // that represents the '*this' capture.
8556       if (!HandleLValueMember(Info, E, Result,
8557                              Info.CurrentCall->LambdaThisCaptureField))
8558         return false;
8559       // If we captured '*this' by reference, replace the field with its referent.
8560       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8561               ->isPointerType()) {
8562         APValue RVal;
8563         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8564                                             RVal))
8565           return false;
8566 
8567         Result.setFrom(Info.Ctx, RVal);
8568       }
8569     }
8570     return true;
8571   }
8572 
8573   bool VisitCXXNewExpr(const CXXNewExpr *E);
8574 
8575   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8576     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
8577     APValue LValResult = E->EvaluateInContext(
8578         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8579     Result.setFrom(Info.Ctx, LValResult);
8580     return true;
8581   }
8582 
8583   // FIXME: Missing: @protocol, @selector
8584 };
8585 } // end anonymous namespace
8586 
8587 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8588                             bool InvalidBaseOK) {
8589   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
8590   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8591 }
8592 
8593 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8594   if (E->getOpcode() != BO_Add &&
8595       E->getOpcode() != BO_Sub)
8596     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8597 
8598   const Expr *PExp = E->getLHS();
8599   const Expr *IExp = E->getRHS();
8600   if (IExp->getType()->isPointerType())
8601     std::swap(PExp, IExp);
8602 
8603   bool EvalPtrOK = evaluatePointer(PExp, Result);
8604   if (!EvalPtrOK && !Info.noteFailure())
8605     return false;
8606 
8607   llvm::APSInt Offset;
8608   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8609     return false;
8610 
8611   if (E->getOpcode() == BO_Sub)
8612     negateAsSigned(Offset);
8613 
8614   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8615   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8616 }
8617 
8618 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8619   return evaluateLValue(E->getSubExpr(), Result);
8620 }
8621 
8622 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8623   const Expr *SubExpr = E->getSubExpr();
8624 
8625   switch (E->getCastKind()) {
8626   default:
8627     break;
8628   case CK_BitCast:
8629   case CK_CPointerToObjCPointerCast:
8630   case CK_BlockPointerToObjCPointerCast:
8631   case CK_AnyPointerToBlockPointerCast:
8632   case CK_AddressSpaceConversion:
8633     if (!Visit(SubExpr))
8634       return false;
8635     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8636     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8637     // also static_casts, but we disallow them as a resolution to DR1312.
8638     if (!E->getType()->isVoidPointerType()) {
8639       if (!Result.InvalidBase && !Result.Designator.Invalid &&
8640           !Result.IsNullPtr &&
8641           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8642                                           E->getType()->getPointeeType()) &&
8643           Info.getStdAllocatorCaller("allocate")) {
8644         // Inside a call to std::allocator::allocate and friends, we permit
8645         // casting from void* back to cv1 T* for a pointer that points to a
8646         // cv2 T.
8647       } else {
8648         Result.Designator.setInvalid();
8649         if (SubExpr->getType()->isVoidPointerType())
8650           CCEDiag(E, diag::note_constexpr_invalid_cast)
8651             << 3 << SubExpr->getType();
8652         else
8653           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8654       }
8655     }
8656     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8657       ZeroInitialization(E);
8658     return true;
8659 
8660   case CK_DerivedToBase:
8661   case CK_UncheckedDerivedToBase:
8662     if (!evaluatePointer(E->getSubExpr(), Result))
8663       return false;
8664     if (!Result.Base && Result.Offset.isZero())
8665       return true;
8666 
8667     // Now figure out the necessary offset to add to the base LV to get from
8668     // the derived class to the base class.
8669     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8670                                   castAs<PointerType>()->getPointeeType(),
8671                                 Result);
8672 
8673   case CK_BaseToDerived:
8674     if (!Visit(E->getSubExpr()))
8675       return false;
8676     if (!Result.Base && Result.Offset.isZero())
8677       return true;
8678     return HandleBaseToDerivedCast(Info, E, Result);
8679 
8680   case CK_Dynamic:
8681     if (!Visit(E->getSubExpr()))
8682       return false;
8683     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8684 
8685   case CK_NullToPointer:
8686     VisitIgnoredValue(E->getSubExpr());
8687     return ZeroInitialization(E);
8688 
8689   case CK_IntegralToPointer: {
8690     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8691 
8692     APValue Value;
8693     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8694       break;
8695 
8696     if (Value.isInt()) {
8697       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8698       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8699       Result.Base = (Expr*)nullptr;
8700       Result.InvalidBase = false;
8701       Result.Offset = CharUnits::fromQuantity(N);
8702       Result.Designator.setInvalid();
8703       Result.IsNullPtr = false;
8704       return true;
8705     } else {
8706       // Cast is of an lvalue, no need to change value.
8707       Result.setFrom(Info.Ctx, Value);
8708       return true;
8709     }
8710   }
8711 
8712   case CK_ArrayToPointerDecay: {
8713     if (SubExpr->isGLValue()) {
8714       if (!evaluateLValue(SubExpr, Result))
8715         return false;
8716     } else {
8717       APValue &Value = Info.CurrentCall->createTemporary(
8718           SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
8719       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8720         return false;
8721     }
8722     // The result is a pointer to the first element of the array.
8723     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8724     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8725       Result.addArray(Info, E, CAT);
8726     else
8727       Result.addUnsizedArray(Info, E, AT->getElementType());
8728     return true;
8729   }
8730 
8731   case CK_FunctionToPointerDecay:
8732     return evaluateLValue(SubExpr, Result);
8733 
8734   case CK_LValueToRValue: {
8735     LValue LVal;
8736     if (!evaluateLValue(E->getSubExpr(), LVal))
8737       return false;
8738 
8739     APValue RVal;
8740     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8741     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8742                                         LVal, RVal))
8743       return InvalidBaseOK &&
8744              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8745     return Success(RVal, E);
8746   }
8747   }
8748 
8749   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8750 }
8751 
8752 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8753                                 UnaryExprOrTypeTrait ExprKind) {
8754   // C++ [expr.alignof]p3:
8755   //     When alignof is applied to a reference type, the result is the
8756   //     alignment of the referenced type.
8757   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8758     T = Ref->getPointeeType();
8759 
8760   if (T.getQualifiers().hasUnaligned())
8761     return CharUnits::One();
8762 
8763   const bool AlignOfReturnsPreferred =
8764       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8765 
8766   // __alignof is defined to return the preferred alignment.
8767   // Before 8, clang returned the preferred alignment for alignof and _Alignof
8768   // as well.
8769   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8770     return Info.Ctx.toCharUnitsFromBits(
8771       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8772   // alignof and _Alignof are defined to return the ABI alignment.
8773   else if (ExprKind == UETT_AlignOf)
8774     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8775   else
8776     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8777 }
8778 
8779 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8780                                 UnaryExprOrTypeTrait ExprKind) {
8781   E = E->IgnoreParens();
8782 
8783   // The kinds of expressions that we have special-case logic here for
8784   // should be kept up to date with the special checks for those
8785   // expressions in Sema.
8786 
8787   // alignof decl is always accepted, even if it doesn't make sense: we default
8788   // to 1 in those cases.
8789   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8790     return Info.Ctx.getDeclAlign(DRE->getDecl(),
8791                                  /*RefAsPointee*/true);
8792 
8793   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8794     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8795                                  /*RefAsPointee*/true);
8796 
8797   return GetAlignOfType(Info, E->getType(), ExprKind);
8798 }
8799 
8800 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
8801   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
8802     return Info.Ctx.getDeclAlign(VD);
8803   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
8804     return GetAlignOfExpr(Info, E, UETT_AlignOf);
8805   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
8806 }
8807 
8808 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
8809 /// __builtin_is_aligned and __builtin_assume_aligned.
8810 static bool getAlignmentArgument(const Expr *E, QualType ForType,
8811                                  EvalInfo &Info, APSInt &Alignment) {
8812   if (!EvaluateInteger(E, Alignment, Info))
8813     return false;
8814   if (Alignment < 0 || !Alignment.isPowerOf2()) {
8815     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
8816     return false;
8817   }
8818   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
8819   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
8820   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
8821     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
8822         << MaxValue << ForType << Alignment;
8823     return false;
8824   }
8825   // Ensure both alignment and source value have the same bit width so that we
8826   // don't assert when computing the resulting value.
8827   APSInt ExtAlignment =
8828       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
8829   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
8830          "Alignment should not be changed by ext/trunc");
8831   Alignment = ExtAlignment;
8832   assert(Alignment.getBitWidth() == SrcWidth);
8833   return true;
8834 }
8835 
8836 // To be clear: this happily visits unsupported builtins. Better name welcomed.
8837 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8838   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8839     return true;
8840 
8841   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
8842     return false;
8843 
8844   Result.setInvalid(E);
8845   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
8846   Result.addUnsizedArray(Info, E, PointeeTy);
8847   return true;
8848 }
8849 
8850 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
8851   if (IsStringLiteralCall(E))
8852     return Success(E);
8853 
8854   if (unsigned BuiltinOp = E->getBuiltinCallee())
8855     return VisitBuiltinCallExpr(E, BuiltinOp);
8856 
8857   return visitNonBuiltinCallExpr(E);
8858 }
8859 
8860 // Determine if T is a character type for which we guarantee that
8861 // sizeof(T) == 1.
8862 static bool isOneByteCharacterType(QualType T) {
8863   return T->isCharType() || T->isChar8Type();
8864 }
8865 
8866 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8867                                                 unsigned BuiltinOp) {
8868   switch (BuiltinOp) {
8869   case Builtin::BI__builtin_addressof:
8870     return evaluateLValue(E->getArg(0), Result);
8871   case Builtin::BI__builtin_assume_aligned: {
8872     // We need to be very careful here because: if the pointer does not have the
8873     // asserted alignment, then the behavior is undefined, and undefined
8874     // behavior is non-constant.
8875     if (!evaluatePointer(E->getArg(0), Result))
8876       return false;
8877 
8878     LValue OffsetResult(Result);
8879     APSInt Alignment;
8880     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8881                               Alignment))
8882       return false;
8883     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
8884 
8885     if (E->getNumArgs() > 2) {
8886       APSInt Offset;
8887       if (!EvaluateInteger(E->getArg(2), Offset, Info))
8888         return false;
8889 
8890       int64_t AdditionalOffset = -Offset.getZExtValue();
8891       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
8892     }
8893 
8894     // If there is a base object, then it must have the correct alignment.
8895     if (OffsetResult.Base) {
8896       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
8897 
8898       if (BaseAlignment < Align) {
8899         Result.Designator.setInvalid();
8900         // FIXME: Add support to Diagnostic for long / long long.
8901         CCEDiag(E->getArg(0),
8902                 diag::note_constexpr_baa_insufficient_alignment) << 0
8903           << (unsigned)BaseAlignment.getQuantity()
8904           << (unsigned)Align.getQuantity();
8905         return false;
8906       }
8907     }
8908 
8909     // The offset must also have the correct alignment.
8910     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
8911       Result.Designator.setInvalid();
8912 
8913       (OffsetResult.Base
8914            ? CCEDiag(E->getArg(0),
8915                      diag::note_constexpr_baa_insufficient_alignment) << 1
8916            : CCEDiag(E->getArg(0),
8917                      diag::note_constexpr_baa_value_insufficient_alignment))
8918         << (int)OffsetResult.Offset.getQuantity()
8919         << (unsigned)Align.getQuantity();
8920       return false;
8921     }
8922 
8923     return true;
8924   }
8925   case Builtin::BI__builtin_align_up:
8926   case Builtin::BI__builtin_align_down: {
8927     if (!evaluatePointer(E->getArg(0), Result))
8928       return false;
8929     APSInt Alignment;
8930     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8931                               Alignment))
8932       return false;
8933     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
8934     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
8935     // For align_up/align_down, we can return the same value if the alignment
8936     // is known to be greater or equal to the requested value.
8937     if (PtrAlign.getQuantity() >= Alignment)
8938       return true;
8939 
8940     // The alignment could be greater than the minimum at run-time, so we cannot
8941     // infer much about the resulting pointer value. One case is possible:
8942     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
8943     // can infer the correct index if the requested alignment is smaller than
8944     // the base alignment so we can perform the computation on the offset.
8945     if (BaseAlignment.getQuantity() >= Alignment) {
8946       assert(Alignment.getBitWidth() <= 64 &&
8947              "Cannot handle > 64-bit address-space");
8948       uint64_t Alignment64 = Alignment.getZExtValue();
8949       CharUnits NewOffset = CharUnits::fromQuantity(
8950           BuiltinOp == Builtin::BI__builtin_align_down
8951               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
8952               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
8953       Result.adjustOffset(NewOffset - Result.Offset);
8954       // TODO: diagnose out-of-bounds values/only allow for arrays?
8955       return true;
8956     }
8957     // Otherwise, we cannot constant-evaluate the result.
8958     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
8959         << Alignment;
8960     return false;
8961   }
8962   case Builtin::BI__builtin_operator_new:
8963     return HandleOperatorNewCall(Info, E, Result);
8964   case Builtin::BI__builtin_launder:
8965     return evaluatePointer(E->getArg(0), Result);
8966   case Builtin::BIstrchr:
8967   case Builtin::BIwcschr:
8968   case Builtin::BImemchr:
8969   case Builtin::BIwmemchr:
8970     if (Info.getLangOpts().CPlusPlus11)
8971       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8972         << /*isConstexpr*/0 << /*isConstructor*/0
8973         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8974     else
8975       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8976     LLVM_FALLTHROUGH;
8977   case Builtin::BI__builtin_strchr:
8978   case Builtin::BI__builtin_wcschr:
8979   case Builtin::BI__builtin_memchr:
8980   case Builtin::BI__builtin_char_memchr:
8981   case Builtin::BI__builtin_wmemchr: {
8982     if (!Visit(E->getArg(0)))
8983       return false;
8984     APSInt Desired;
8985     if (!EvaluateInteger(E->getArg(1), Desired, Info))
8986       return false;
8987     uint64_t MaxLength = uint64_t(-1);
8988     if (BuiltinOp != Builtin::BIstrchr &&
8989         BuiltinOp != Builtin::BIwcschr &&
8990         BuiltinOp != Builtin::BI__builtin_strchr &&
8991         BuiltinOp != Builtin::BI__builtin_wcschr) {
8992       APSInt N;
8993       if (!EvaluateInteger(E->getArg(2), N, Info))
8994         return false;
8995       MaxLength = N.getExtValue();
8996     }
8997     // We cannot find the value if there are no candidates to match against.
8998     if (MaxLength == 0u)
8999       return ZeroInitialization(E);
9000     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9001         Result.Designator.Invalid)
9002       return false;
9003     QualType CharTy = Result.Designator.getType(Info.Ctx);
9004     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9005                      BuiltinOp == Builtin::BI__builtin_memchr;
9006     assert(IsRawByte ||
9007            Info.Ctx.hasSameUnqualifiedType(
9008                CharTy, E->getArg(0)->getType()->getPointeeType()));
9009     // Pointers to const void may point to objects of incomplete type.
9010     if (IsRawByte && CharTy->isIncompleteType()) {
9011       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9012       return false;
9013     }
9014     // Give up on byte-oriented matching against multibyte elements.
9015     // FIXME: We can compare the bytes in the correct order.
9016     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9017       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9018           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
9019           << CharTy;
9020       return false;
9021     }
9022     // Figure out what value we're actually looking for (after converting to
9023     // the corresponding unsigned type if necessary).
9024     uint64_t DesiredVal;
9025     bool StopAtNull = false;
9026     switch (BuiltinOp) {
9027     case Builtin::BIstrchr:
9028     case Builtin::BI__builtin_strchr:
9029       // strchr compares directly to the passed integer, and therefore
9030       // always fails if given an int that is not a char.
9031       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9032                                                   E->getArg(1)->getType(),
9033                                                   Desired),
9034                                Desired))
9035         return ZeroInitialization(E);
9036       StopAtNull = true;
9037       LLVM_FALLTHROUGH;
9038     case Builtin::BImemchr:
9039     case Builtin::BI__builtin_memchr:
9040     case Builtin::BI__builtin_char_memchr:
9041       // memchr compares by converting both sides to unsigned char. That's also
9042       // correct for strchr if we get this far (to cope with plain char being
9043       // unsigned in the strchr case).
9044       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9045       break;
9046 
9047     case Builtin::BIwcschr:
9048     case Builtin::BI__builtin_wcschr:
9049       StopAtNull = true;
9050       LLVM_FALLTHROUGH;
9051     case Builtin::BIwmemchr:
9052     case Builtin::BI__builtin_wmemchr:
9053       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9054       DesiredVal = Desired.getZExtValue();
9055       break;
9056     }
9057 
9058     for (; MaxLength; --MaxLength) {
9059       APValue Char;
9060       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9061           !Char.isInt())
9062         return false;
9063       if (Char.getInt().getZExtValue() == DesiredVal)
9064         return true;
9065       if (StopAtNull && !Char.getInt())
9066         break;
9067       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9068         return false;
9069     }
9070     // Not found: return nullptr.
9071     return ZeroInitialization(E);
9072   }
9073 
9074   case Builtin::BImemcpy:
9075   case Builtin::BImemmove:
9076   case Builtin::BIwmemcpy:
9077   case Builtin::BIwmemmove:
9078     if (Info.getLangOpts().CPlusPlus11)
9079       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9080         << /*isConstexpr*/0 << /*isConstructor*/0
9081         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9082     else
9083       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9084     LLVM_FALLTHROUGH;
9085   case Builtin::BI__builtin_memcpy:
9086   case Builtin::BI__builtin_memmove:
9087   case Builtin::BI__builtin_wmemcpy:
9088   case Builtin::BI__builtin_wmemmove: {
9089     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9090                  BuiltinOp == Builtin::BIwmemmove ||
9091                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9092                  BuiltinOp == Builtin::BI__builtin_wmemmove;
9093     bool Move = BuiltinOp == Builtin::BImemmove ||
9094                 BuiltinOp == Builtin::BIwmemmove ||
9095                 BuiltinOp == Builtin::BI__builtin_memmove ||
9096                 BuiltinOp == Builtin::BI__builtin_wmemmove;
9097 
9098     // The result of mem* is the first argument.
9099     if (!Visit(E->getArg(0)))
9100       return false;
9101     LValue Dest = Result;
9102 
9103     LValue Src;
9104     if (!EvaluatePointer(E->getArg(1), Src, Info))
9105       return false;
9106 
9107     APSInt N;
9108     if (!EvaluateInteger(E->getArg(2), N, Info))
9109       return false;
9110     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9111 
9112     // If the size is zero, we treat this as always being a valid no-op.
9113     // (Even if one of the src and dest pointers is null.)
9114     if (!N)
9115       return true;
9116 
9117     // Otherwise, if either of the operands is null, we can't proceed. Don't
9118     // try to determine the type of the copied objects, because there aren't
9119     // any.
9120     if (!Src.Base || !Dest.Base) {
9121       APValue Val;
9122       (!Src.Base ? Src : Dest).moveInto(Val);
9123       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9124           << Move << WChar << !!Src.Base
9125           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9126       return false;
9127     }
9128     if (Src.Designator.Invalid || Dest.Designator.Invalid)
9129       return false;
9130 
9131     // We require that Src and Dest are both pointers to arrays of
9132     // trivially-copyable type. (For the wide version, the designator will be
9133     // invalid if the designated object is not a wchar_t.)
9134     QualType T = Dest.Designator.getType(Info.Ctx);
9135     QualType SrcT = Src.Designator.getType(Info.Ctx);
9136     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9137       // FIXME: Consider using our bit_cast implementation to support this.
9138       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9139       return false;
9140     }
9141     if (T->isIncompleteType()) {
9142       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9143       return false;
9144     }
9145     if (!T.isTriviallyCopyableType(Info.Ctx)) {
9146       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9147       return false;
9148     }
9149 
9150     // Figure out how many T's we're copying.
9151     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9152     if (!WChar) {
9153       uint64_t Remainder;
9154       llvm::APInt OrigN = N;
9155       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9156       if (Remainder) {
9157         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9158             << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
9159             << (unsigned)TSize;
9160         return false;
9161       }
9162     }
9163 
9164     // Check that the copying will remain within the arrays, just so that we
9165     // can give a more meaningful diagnostic. This implicitly also checks that
9166     // N fits into 64 bits.
9167     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9168     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9169     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9170       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9171           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9172           << N.toString(10, /*Signed*/false);
9173       return false;
9174     }
9175     uint64_t NElems = N.getZExtValue();
9176     uint64_t NBytes = NElems * TSize;
9177 
9178     // Check for overlap.
9179     int Direction = 1;
9180     if (HasSameBase(Src, Dest)) {
9181       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9182       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9183       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9184         // Dest is inside the source region.
9185         if (!Move) {
9186           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9187           return false;
9188         }
9189         // For memmove and friends, copy backwards.
9190         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9191             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9192           return false;
9193         Direction = -1;
9194       } else if (!Move && SrcOffset >= DestOffset &&
9195                  SrcOffset - DestOffset < NBytes) {
9196         // Src is inside the destination region for memcpy: invalid.
9197         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9198         return false;
9199       }
9200     }
9201 
9202     while (true) {
9203       APValue Val;
9204       // FIXME: Set WantObjectRepresentation to true if we're copying a
9205       // char-like type?
9206       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9207           !handleAssignment(Info, E, Dest, T, Val))
9208         return false;
9209       // Do not iterate past the last element; if we're copying backwards, that
9210       // might take us off the start of the array.
9211       if (--NElems == 0)
9212         return true;
9213       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9214           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9215         return false;
9216     }
9217   }
9218 
9219   default:
9220     break;
9221   }
9222 
9223   return visitNonBuiltinCallExpr(E);
9224 }
9225 
9226 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9227                                      APValue &Result, const InitListExpr *ILE,
9228                                      QualType AllocType);
9229 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9230                                           APValue &Result,
9231                                           const CXXConstructExpr *CCE,
9232                                           QualType AllocType);
9233 
9234 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9235   if (!Info.getLangOpts().CPlusPlus20)
9236     Info.CCEDiag(E, diag::note_constexpr_new);
9237 
9238   // We cannot speculatively evaluate a delete expression.
9239   if (Info.SpeculativeEvaluationDepth)
9240     return false;
9241 
9242   FunctionDecl *OperatorNew = E->getOperatorNew();
9243 
9244   bool IsNothrow = false;
9245   bool IsPlacement = false;
9246   if (OperatorNew->isReservedGlobalPlacementOperator() &&
9247       Info.CurrentCall->isStdFunction() && !E->isArray()) {
9248     // FIXME Support array placement new.
9249     assert(E->getNumPlacementArgs() == 1);
9250     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9251       return false;
9252     if (Result.Designator.Invalid)
9253       return false;
9254     IsPlacement = true;
9255   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9256     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9257         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9258     return false;
9259   } else if (E->getNumPlacementArgs()) {
9260     // The only new-placement list we support is of the form (std::nothrow).
9261     //
9262     // FIXME: There is no restriction on this, but it's not clear that any
9263     // other form makes any sense. We get here for cases such as:
9264     //
9265     //   new (std::align_val_t{N}) X(int)
9266     //
9267     // (which should presumably be valid only if N is a multiple of
9268     // alignof(int), and in any case can't be deallocated unless N is
9269     // alignof(X) and X has new-extended alignment).
9270     if (E->getNumPlacementArgs() != 1 ||
9271         !E->getPlacementArg(0)->getType()->isNothrowT())
9272       return Error(E, diag::note_constexpr_new_placement);
9273 
9274     LValue Nothrow;
9275     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9276       return false;
9277     IsNothrow = true;
9278   }
9279 
9280   const Expr *Init = E->getInitializer();
9281   const InitListExpr *ResizedArrayILE = nullptr;
9282   const CXXConstructExpr *ResizedArrayCCE = nullptr;
9283   bool ValueInit = false;
9284 
9285   QualType AllocType = E->getAllocatedType();
9286   if (Optional<const Expr*> ArraySize = E->getArraySize()) {
9287     const Expr *Stripped = *ArraySize;
9288     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9289          Stripped = ICE->getSubExpr())
9290       if (ICE->getCastKind() != CK_NoOp &&
9291           ICE->getCastKind() != CK_IntegralCast)
9292         break;
9293 
9294     llvm::APSInt ArrayBound;
9295     if (!EvaluateInteger(Stripped, ArrayBound, Info))
9296       return false;
9297 
9298     // C++ [expr.new]p9:
9299     //   The expression is erroneous if:
9300     //   -- [...] its value before converting to size_t [or] applying the
9301     //      second standard conversion sequence is less than zero
9302     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9303       if (IsNothrow)
9304         return ZeroInitialization(E);
9305 
9306       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9307           << ArrayBound << (*ArraySize)->getSourceRange();
9308       return false;
9309     }
9310 
9311     //   -- its value is such that the size of the allocated object would
9312     //      exceed the implementation-defined limit
9313     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9314                                                 ArrayBound) >
9315         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9316       if (IsNothrow)
9317         return ZeroInitialization(E);
9318 
9319       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9320         << ArrayBound << (*ArraySize)->getSourceRange();
9321       return false;
9322     }
9323 
9324     //   -- the new-initializer is a braced-init-list and the number of
9325     //      array elements for which initializers are provided [...]
9326     //      exceeds the number of elements to initialize
9327     if (!Init) {
9328       // No initialization is performed.
9329     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9330                isa<ImplicitValueInitExpr>(Init)) {
9331       ValueInit = true;
9332     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9333       ResizedArrayCCE = CCE;
9334     } else {
9335       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9336       assert(CAT && "unexpected type for array initializer");
9337 
9338       unsigned Bits =
9339           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9340       llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
9341       llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
9342       if (InitBound.ugt(AllocBound)) {
9343         if (IsNothrow)
9344           return ZeroInitialization(E);
9345 
9346         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9347             << AllocBound.toString(10, /*Signed=*/false)
9348             << InitBound.toString(10, /*Signed=*/false)
9349             << (*ArraySize)->getSourceRange();
9350         return false;
9351       }
9352 
9353       // If the sizes differ, we must have an initializer list, and we need
9354       // special handling for this case when we initialize.
9355       if (InitBound != AllocBound)
9356         ResizedArrayILE = cast<InitListExpr>(Init);
9357     }
9358 
9359     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9360                                               ArrayType::Normal, 0);
9361   } else {
9362     assert(!AllocType->isArrayType() &&
9363            "array allocation with non-array new");
9364   }
9365 
9366   APValue *Val;
9367   if (IsPlacement) {
9368     AccessKinds AK = AK_Construct;
9369     struct FindObjectHandler {
9370       EvalInfo &Info;
9371       const Expr *E;
9372       QualType AllocType;
9373       const AccessKinds AccessKind;
9374       APValue *Value;
9375 
9376       typedef bool result_type;
9377       bool failed() { return false; }
9378       bool found(APValue &Subobj, QualType SubobjType) {
9379         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9380         // old name of the object to be used to name the new object.
9381         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9382           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9383             SubobjType << AllocType;
9384           return false;
9385         }
9386         Value = &Subobj;
9387         return true;
9388       }
9389       bool found(APSInt &Value, QualType SubobjType) {
9390         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9391         return false;
9392       }
9393       bool found(APFloat &Value, QualType SubobjType) {
9394         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9395         return false;
9396       }
9397     } Handler = {Info, E, AllocType, AK, nullptr};
9398 
9399     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9400     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9401       return false;
9402 
9403     Val = Handler.Value;
9404 
9405     // [basic.life]p1:
9406     //   The lifetime of an object o of type T ends when [...] the storage
9407     //   which the object occupies is [...] reused by an object that is not
9408     //   nested within o (6.6.2).
9409     *Val = APValue();
9410   } else {
9411     // Perform the allocation and obtain a pointer to the resulting object.
9412     Val = Info.createHeapAlloc(E, AllocType, Result);
9413     if (!Val)
9414       return false;
9415   }
9416 
9417   if (ValueInit) {
9418     ImplicitValueInitExpr VIE(AllocType);
9419     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9420       return false;
9421   } else if (ResizedArrayILE) {
9422     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9423                                   AllocType))
9424       return false;
9425   } else if (ResizedArrayCCE) {
9426     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9427                                        AllocType))
9428       return false;
9429   } else if (Init) {
9430     if (!EvaluateInPlace(*Val, Info, Result, Init))
9431       return false;
9432   } else if (!getDefaultInitValue(AllocType, *Val)) {
9433     return false;
9434   }
9435 
9436   // Array new returns a pointer to the first element, not a pointer to the
9437   // array.
9438   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9439     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9440 
9441   return true;
9442 }
9443 //===----------------------------------------------------------------------===//
9444 // Member Pointer Evaluation
9445 //===----------------------------------------------------------------------===//
9446 
9447 namespace {
9448 class MemberPointerExprEvaluator
9449   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9450   MemberPtr &Result;
9451 
9452   bool Success(const ValueDecl *D) {
9453     Result = MemberPtr(D);
9454     return true;
9455   }
9456 public:
9457 
9458   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9459     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9460 
9461   bool Success(const APValue &V, const Expr *E) {
9462     Result.setFrom(V);
9463     return true;
9464   }
9465   bool ZeroInitialization(const Expr *E) {
9466     return Success((const ValueDecl*)nullptr);
9467   }
9468 
9469   bool VisitCastExpr(const CastExpr *E);
9470   bool VisitUnaryAddrOf(const UnaryOperator *E);
9471 };
9472 } // end anonymous namespace
9473 
9474 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9475                                   EvalInfo &Info) {
9476   assert(E->isRValue() && E->getType()->isMemberPointerType());
9477   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9478 }
9479 
9480 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9481   switch (E->getCastKind()) {
9482   default:
9483     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9484 
9485   case CK_NullToMemberPointer:
9486     VisitIgnoredValue(E->getSubExpr());
9487     return ZeroInitialization(E);
9488 
9489   case CK_BaseToDerivedMemberPointer: {
9490     if (!Visit(E->getSubExpr()))
9491       return false;
9492     if (E->path_empty())
9493       return true;
9494     // Base-to-derived member pointer casts store the path in derived-to-base
9495     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9496     // the wrong end of the derived->base arc, so stagger the path by one class.
9497     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9498     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9499          PathI != PathE; ++PathI) {
9500       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9501       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9502       if (!Result.castToDerived(Derived))
9503         return Error(E);
9504     }
9505     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9506     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9507       return Error(E);
9508     return true;
9509   }
9510 
9511   case CK_DerivedToBaseMemberPointer:
9512     if (!Visit(E->getSubExpr()))
9513       return false;
9514     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9515          PathE = E->path_end(); PathI != PathE; ++PathI) {
9516       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9517       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9518       if (!Result.castToBase(Base))
9519         return Error(E);
9520     }
9521     return true;
9522   }
9523 }
9524 
9525 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9526   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9527   // member can be formed.
9528   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9529 }
9530 
9531 //===----------------------------------------------------------------------===//
9532 // Record Evaluation
9533 //===----------------------------------------------------------------------===//
9534 
9535 namespace {
9536   class RecordExprEvaluator
9537   : public ExprEvaluatorBase<RecordExprEvaluator> {
9538     const LValue &This;
9539     APValue &Result;
9540   public:
9541 
9542     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9543       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9544 
9545     bool Success(const APValue &V, const Expr *E) {
9546       Result = V;
9547       return true;
9548     }
9549     bool ZeroInitialization(const Expr *E) {
9550       return ZeroInitialization(E, E->getType());
9551     }
9552     bool ZeroInitialization(const Expr *E, QualType T);
9553 
9554     bool VisitCallExpr(const CallExpr *E) {
9555       return handleCallExpr(E, Result, &This);
9556     }
9557     bool VisitCastExpr(const CastExpr *E);
9558     bool VisitInitListExpr(const InitListExpr *E);
9559     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9560       return VisitCXXConstructExpr(E, E->getType());
9561     }
9562     bool VisitLambdaExpr(const LambdaExpr *E);
9563     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9564     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9565     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9566     bool VisitBinCmp(const BinaryOperator *E);
9567   };
9568 }
9569 
9570 /// Perform zero-initialization on an object of non-union class type.
9571 /// C++11 [dcl.init]p5:
9572 ///  To zero-initialize an object or reference of type T means:
9573 ///    [...]
9574 ///    -- if T is a (possibly cv-qualified) non-union class type,
9575 ///       each non-static data member and each base-class subobject is
9576 ///       zero-initialized
9577 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9578                                           const RecordDecl *RD,
9579                                           const LValue &This, APValue &Result) {
9580   assert(!RD->isUnion() && "Expected non-union class type");
9581   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9582   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9583                    std::distance(RD->field_begin(), RD->field_end()));
9584 
9585   if (RD->isInvalidDecl()) return false;
9586   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9587 
9588   if (CD) {
9589     unsigned Index = 0;
9590     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9591            End = CD->bases_end(); I != End; ++I, ++Index) {
9592       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9593       LValue Subobject = This;
9594       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9595         return false;
9596       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9597                                          Result.getStructBase(Index)))
9598         return false;
9599     }
9600   }
9601 
9602   for (const auto *I : RD->fields()) {
9603     // -- if T is a reference type, no initialization is performed.
9604     if (I->getType()->isReferenceType())
9605       continue;
9606 
9607     LValue Subobject = This;
9608     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9609       return false;
9610 
9611     ImplicitValueInitExpr VIE(I->getType());
9612     if (!EvaluateInPlace(
9613           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9614       return false;
9615   }
9616 
9617   return true;
9618 }
9619 
9620 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9621   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9622   if (RD->isInvalidDecl()) return false;
9623   if (RD->isUnion()) {
9624     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9625     // object's first non-static named data member is zero-initialized
9626     RecordDecl::field_iterator I = RD->field_begin();
9627     if (I == RD->field_end()) {
9628       Result = APValue((const FieldDecl*)nullptr);
9629       return true;
9630     }
9631 
9632     LValue Subobject = This;
9633     if (!HandleLValueMember(Info, E, Subobject, *I))
9634       return false;
9635     Result = APValue(*I);
9636     ImplicitValueInitExpr VIE(I->getType());
9637     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9638   }
9639 
9640   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9641     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9642     return false;
9643   }
9644 
9645   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9646 }
9647 
9648 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9649   switch (E->getCastKind()) {
9650   default:
9651     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9652 
9653   case CK_ConstructorConversion:
9654     return Visit(E->getSubExpr());
9655 
9656   case CK_DerivedToBase:
9657   case CK_UncheckedDerivedToBase: {
9658     APValue DerivedObject;
9659     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9660       return false;
9661     if (!DerivedObject.isStruct())
9662       return Error(E->getSubExpr());
9663 
9664     // Derived-to-base rvalue conversion: just slice off the derived part.
9665     APValue *Value = &DerivedObject;
9666     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9667     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9668          PathE = E->path_end(); PathI != PathE; ++PathI) {
9669       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9670       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9671       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9672       RD = Base;
9673     }
9674     Result = *Value;
9675     return true;
9676   }
9677   }
9678 }
9679 
9680 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9681   if (E->isTransparent())
9682     return Visit(E->getInit(0));
9683 
9684   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9685   if (RD->isInvalidDecl()) return false;
9686   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9687   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9688 
9689   EvalInfo::EvaluatingConstructorRAII EvalObj(
9690       Info,
9691       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9692       CXXRD && CXXRD->getNumBases());
9693 
9694   if (RD->isUnion()) {
9695     const FieldDecl *Field = E->getInitializedFieldInUnion();
9696     Result = APValue(Field);
9697     if (!Field)
9698       return true;
9699 
9700     // If the initializer list for a union does not contain any elements, the
9701     // first element of the union is value-initialized.
9702     // FIXME: The element should be initialized from an initializer list.
9703     //        Is this difference ever observable for initializer lists which
9704     //        we don't build?
9705     ImplicitValueInitExpr VIE(Field->getType());
9706     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9707 
9708     LValue Subobject = This;
9709     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9710       return false;
9711 
9712     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9713     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9714                                   isa<CXXDefaultInitExpr>(InitExpr));
9715 
9716     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
9717   }
9718 
9719   if (!Result.hasValue())
9720     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9721                      std::distance(RD->field_begin(), RD->field_end()));
9722   unsigned ElementNo = 0;
9723   bool Success = true;
9724 
9725   // Initialize base classes.
9726   if (CXXRD && CXXRD->getNumBases()) {
9727     for (const auto &Base : CXXRD->bases()) {
9728       assert(ElementNo < E->getNumInits() && "missing init for base class");
9729       const Expr *Init = E->getInit(ElementNo);
9730 
9731       LValue Subobject = This;
9732       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9733         return false;
9734 
9735       APValue &FieldVal = Result.getStructBase(ElementNo);
9736       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9737         if (!Info.noteFailure())
9738           return false;
9739         Success = false;
9740       }
9741       ++ElementNo;
9742     }
9743 
9744     EvalObj.finishedConstructingBases();
9745   }
9746 
9747   // Initialize members.
9748   for (const auto *Field : RD->fields()) {
9749     // Anonymous bit-fields are not considered members of the class for
9750     // purposes of aggregate initialization.
9751     if (Field->isUnnamedBitfield())
9752       continue;
9753 
9754     LValue Subobject = This;
9755 
9756     bool HaveInit = ElementNo < E->getNumInits();
9757 
9758     // FIXME: Diagnostics here should point to the end of the initializer
9759     // list, not the start.
9760     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9761                             Subobject, Field, &Layout))
9762       return false;
9763 
9764     // Perform an implicit value-initialization for members beyond the end of
9765     // the initializer list.
9766     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9767     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9768 
9769     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9770     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9771                                   isa<CXXDefaultInitExpr>(Init));
9772 
9773     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9774     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9775         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9776                                                        FieldVal, Field))) {
9777       if (!Info.noteFailure())
9778         return false;
9779       Success = false;
9780     }
9781   }
9782 
9783   EvalObj.finishedConstructingFields();
9784 
9785   return Success;
9786 }
9787 
9788 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9789                                                 QualType T) {
9790   // Note that E's type is not necessarily the type of our class here; we might
9791   // be initializing an array element instead.
9792   const CXXConstructorDecl *FD = E->getConstructor();
9793   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9794 
9795   bool ZeroInit = E->requiresZeroInitialization();
9796   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
9797     // If we've already performed zero-initialization, we're already done.
9798     if (Result.hasValue())
9799       return true;
9800 
9801     if (ZeroInit)
9802       return ZeroInitialization(E, T);
9803 
9804     return getDefaultInitValue(T, Result);
9805   }
9806 
9807   const FunctionDecl *Definition = nullptr;
9808   auto Body = FD->getBody(Definition);
9809 
9810   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9811     return false;
9812 
9813   // Avoid materializing a temporary for an elidable copy/move constructor.
9814   if (E->isElidable() && !ZeroInit)
9815     if (const MaterializeTemporaryExpr *ME
9816           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
9817       return Visit(ME->getSubExpr());
9818 
9819   if (ZeroInit && !ZeroInitialization(E, T))
9820     return false;
9821 
9822   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
9823   return HandleConstructorCall(E, This, Args,
9824                                cast<CXXConstructorDecl>(Definition), Info,
9825                                Result);
9826 }
9827 
9828 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9829     const CXXInheritedCtorInitExpr *E) {
9830   if (!Info.CurrentCall) {
9831     assert(Info.checkingPotentialConstantExpression());
9832     return false;
9833   }
9834 
9835   const CXXConstructorDecl *FD = E->getConstructor();
9836   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9837     return false;
9838 
9839   const FunctionDecl *Definition = nullptr;
9840   auto Body = FD->getBody(Definition);
9841 
9842   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9843     return false;
9844 
9845   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
9846                                cast<CXXConstructorDecl>(Definition), Info,
9847                                Result);
9848 }
9849 
9850 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
9851     const CXXStdInitializerListExpr *E) {
9852   const ConstantArrayType *ArrayType =
9853       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
9854 
9855   LValue Array;
9856   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
9857     return false;
9858 
9859   // Get a pointer to the first element of the array.
9860   Array.addArray(Info, E, ArrayType);
9861 
9862   auto InvalidType = [&] {
9863     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
9864       << E->getType();
9865     return false;
9866   };
9867 
9868   // FIXME: Perform the checks on the field types in SemaInit.
9869   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
9870   RecordDecl::field_iterator Field = Record->field_begin();
9871   if (Field == Record->field_end())
9872     return InvalidType();
9873 
9874   // Start pointer.
9875   if (!Field->getType()->isPointerType() ||
9876       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9877                             ArrayType->getElementType()))
9878     return InvalidType();
9879 
9880   // FIXME: What if the initializer_list type has base classes, etc?
9881   Result = APValue(APValue::UninitStruct(), 0, 2);
9882   Array.moveInto(Result.getStructField(0));
9883 
9884   if (++Field == Record->field_end())
9885     return InvalidType();
9886 
9887   if (Field->getType()->isPointerType() &&
9888       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9889                            ArrayType->getElementType())) {
9890     // End pointer.
9891     if (!HandleLValueArrayAdjustment(Info, E, Array,
9892                                      ArrayType->getElementType(),
9893                                      ArrayType->getSize().getZExtValue()))
9894       return false;
9895     Array.moveInto(Result.getStructField(1));
9896   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
9897     // Length.
9898     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
9899   else
9900     return InvalidType();
9901 
9902   if (++Field != Record->field_end())
9903     return InvalidType();
9904 
9905   return true;
9906 }
9907 
9908 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
9909   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
9910   if (ClosureClass->isInvalidDecl())
9911     return false;
9912 
9913   const size_t NumFields =
9914       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
9915 
9916   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
9917                                             E->capture_init_end()) &&
9918          "The number of lambda capture initializers should equal the number of "
9919          "fields within the closure type");
9920 
9921   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
9922   // Iterate through all the lambda's closure object's fields and initialize
9923   // them.
9924   auto *CaptureInitIt = E->capture_init_begin();
9925   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
9926   bool Success = true;
9927   for (const auto *Field : ClosureClass->fields()) {
9928     assert(CaptureInitIt != E->capture_init_end());
9929     // Get the initializer for this field
9930     Expr *const CurFieldInit = *CaptureInitIt++;
9931 
9932     // If there is no initializer, either this is a VLA or an error has
9933     // occurred.
9934     if (!CurFieldInit)
9935       return Error(E);
9936 
9937     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9938     if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
9939       if (!Info.keepEvaluatingAfterFailure())
9940         return false;
9941       Success = false;
9942     }
9943     ++CaptureIt;
9944   }
9945   return Success;
9946 }
9947 
9948 static bool EvaluateRecord(const Expr *E, const LValue &This,
9949                            APValue &Result, EvalInfo &Info) {
9950   assert(E->isRValue() && E->getType()->isRecordType() &&
9951          "can't evaluate expression as a record rvalue");
9952   return RecordExprEvaluator(Info, This, Result).Visit(E);
9953 }
9954 
9955 //===----------------------------------------------------------------------===//
9956 // Temporary Evaluation
9957 //
9958 // Temporaries are represented in the AST as rvalues, but generally behave like
9959 // lvalues. The full-object of which the temporary is a subobject is implicitly
9960 // materialized so that a reference can bind to it.
9961 //===----------------------------------------------------------------------===//
9962 namespace {
9963 class TemporaryExprEvaluator
9964   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
9965 public:
9966   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
9967     LValueExprEvaluatorBaseTy(Info, Result, false) {}
9968 
9969   /// Visit an expression which constructs the value of this temporary.
9970   bool VisitConstructExpr(const Expr *E) {
9971     APValue &Value = Info.CurrentCall->createTemporary(
9972         E, E->getType(), ScopeKind::FullExpression, Result);
9973     return EvaluateInPlace(Value, Info, Result, E);
9974   }
9975 
9976   bool VisitCastExpr(const CastExpr *E) {
9977     switch (E->getCastKind()) {
9978     default:
9979       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
9980 
9981     case CK_ConstructorConversion:
9982       return VisitConstructExpr(E->getSubExpr());
9983     }
9984   }
9985   bool VisitInitListExpr(const InitListExpr *E) {
9986     return VisitConstructExpr(E);
9987   }
9988   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9989     return VisitConstructExpr(E);
9990   }
9991   bool VisitCallExpr(const CallExpr *E) {
9992     return VisitConstructExpr(E);
9993   }
9994   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
9995     return VisitConstructExpr(E);
9996   }
9997   bool VisitLambdaExpr(const LambdaExpr *E) {
9998     return VisitConstructExpr(E);
9999   }
10000 };
10001 } // end anonymous namespace
10002 
10003 /// Evaluate an expression of record type as a temporary.
10004 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10005   assert(E->isRValue() && E->getType()->isRecordType());
10006   return TemporaryExprEvaluator(Info, Result).Visit(E);
10007 }
10008 
10009 //===----------------------------------------------------------------------===//
10010 // Vector Evaluation
10011 //===----------------------------------------------------------------------===//
10012 
10013 namespace {
10014   class VectorExprEvaluator
10015   : public ExprEvaluatorBase<VectorExprEvaluator> {
10016     APValue &Result;
10017   public:
10018 
10019     VectorExprEvaluator(EvalInfo &info, APValue &Result)
10020       : ExprEvaluatorBaseTy(info), Result(Result) {}
10021 
10022     bool Success(ArrayRef<APValue> V, const Expr *E) {
10023       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10024       // FIXME: remove this APValue copy.
10025       Result = APValue(V.data(), V.size());
10026       return true;
10027     }
10028     bool Success(const APValue &V, const Expr *E) {
10029       assert(V.isVector());
10030       Result = V;
10031       return true;
10032     }
10033     bool ZeroInitialization(const Expr *E);
10034 
10035     bool VisitUnaryReal(const UnaryOperator *E)
10036       { return Visit(E->getSubExpr()); }
10037     bool VisitCastExpr(const CastExpr* E);
10038     bool VisitInitListExpr(const InitListExpr *E);
10039     bool VisitUnaryImag(const UnaryOperator *E);
10040     bool VisitBinaryOperator(const BinaryOperator *E);
10041     // FIXME: Missing: unary -, unary ~, conditional operator (for GNU
10042     //                 conditional select), shufflevector, ExtVectorElementExpr
10043   };
10044 } // end anonymous namespace
10045 
10046 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10047   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
10048   return VectorExprEvaluator(Info, Result).Visit(E);
10049 }
10050 
10051 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10052   const VectorType *VTy = E->getType()->castAs<VectorType>();
10053   unsigned NElts = VTy->getNumElements();
10054 
10055   const Expr *SE = E->getSubExpr();
10056   QualType SETy = SE->getType();
10057 
10058   switch (E->getCastKind()) {
10059   case CK_VectorSplat: {
10060     APValue Val = APValue();
10061     if (SETy->isIntegerType()) {
10062       APSInt IntResult;
10063       if (!EvaluateInteger(SE, IntResult, Info))
10064         return false;
10065       Val = APValue(std::move(IntResult));
10066     } else if (SETy->isRealFloatingType()) {
10067       APFloat FloatResult(0.0);
10068       if (!EvaluateFloat(SE, FloatResult, Info))
10069         return false;
10070       Val = APValue(std::move(FloatResult));
10071     } else {
10072       return Error(E);
10073     }
10074 
10075     // Splat and create vector APValue.
10076     SmallVector<APValue, 4> Elts(NElts, Val);
10077     return Success(Elts, E);
10078   }
10079   case CK_BitCast: {
10080     // Evaluate the operand into an APInt we can extract from.
10081     llvm::APInt SValInt;
10082     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10083       return false;
10084     // Extract the elements
10085     QualType EltTy = VTy->getElementType();
10086     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10087     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10088     SmallVector<APValue, 4> Elts;
10089     if (EltTy->isRealFloatingType()) {
10090       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10091       unsigned FloatEltSize = EltSize;
10092       if (&Sem == &APFloat::x87DoubleExtended())
10093         FloatEltSize = 80;
10094       for (unsigned i = 0; i < NElts; i++) {
10095         llvm::APInt Elt;
10096         if (BigEndian)
10097           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
10098         else
10099           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
10100         Elts.push_back(APValue(APFloat(Sem, Elt)));
10101       }
10102     } else if (EltTy->isIntegerType()) {
10103       for (unsigned i = 0; i < NElts; i++) {
10104         llvm::APInt Elt;
10105         if (BigEndian)
10106           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10107         else
10108           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10109         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
10110       }
10111     } else {
10112       return Error(E);
10113     }
10114     return Success(Elts, E);
10115   }
10116   default:
10117     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10118   }
10119 }
10120 
10121 bool
10122 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10123   const VectorType *VT = E->getType()->castAs<VectorType>();
10124   unsigned NumInits = E->getNumInits();
10125   unsigned NumElements = VT->getNumElements();
10126 
10127   QualType EltTy = VT->getElementType();
10128   SmallVector<APValue, 4> Elements;
10129 
10130   // The number of initializers can be less than the number of
10131   // vector elements. For OpenCL, this can be due to nested vector
10132   // initialization. For GCC compatibility, missing trailing elements
10133   // should be initialized with zeroes.
10134   unsigned CountInits = 0, CountElts = 0;
10135   while (CountElts < NumElements) {
10136     // Handle nested vector initialization.
10137     if (CountInits < NumInits
10138         && E->getInit(CountInits)->getType()->isVectorType()) {
10139       APValue v;
10140       if (!EvaluateVector(E->getInit(CountInits), v, Info))
10141         return Error(E);
10142       unsigned vlen = v.getVectorLength();
10143       for (unsigned j = 0; j < vlen; j++)
10144         Elements.push_back(v.getVectorElt(j));
10145       CountElts += vlen;
10146     } else if (EltTy->isIntegerType()) {
10147       llvm::APSInt sInt(32);
10148       if (CountInits < NumInits) {
10149         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10150           return false;
10151       } else // trailing integer zero.
10152         sInt = Info.Ctx.MakeIntValue(0, EltTy);
10153       Elements.push_back(APValue(sInt));
10154       CountElts++;
10155     } else {
10156       llvm::APFloat f(0.0);
10157       if (CountInits < NumInits) {
10158         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10159           return false;
10160       } else // trailing float zero.
10161         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10162       Elements.push_back(APValue(f));
10163       CountElts++;
10164     }
10165     CountInits++;
10166   }
10167   return Success(Elements, E);
10168 }
10169 
10170 bool
10171 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10172   const auto *VT = E->getType()->castAs<VectorType>();
10173   QualType EltTy = VT->getElementType();
10174   APValue ZeroElement;
10175   if (EltTy->isIntegerType())
10176     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10177   else
10178     ZeroElement =
10179         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10180 
10181   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10182   return Success(Elements, E);
10183 }
10184 
10185 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10186   VisitIgnoredValue(E->getSubExpr());
10187   return ZeroInitialization(E);
10188 }
10189 
10190 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10191   BinaryOperatorKind Op = E->getOpcode();
10192   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10193          "Operation not supported on vector types");
10194 
10195   if (Op == BO_Comma)
10196     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10197 
10198   Expr *LHS = E->getLHS();
10199   Expr *RHS = E->getRHS();
10200 
10201   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10202          "Must both be vector types");
10203   // Checking JUST the types are the same would be fine, except shifts don't
10204   // need to have their types be the same (since you always shift by an int).
10205   assert(LHS->getType()->getAs<VectorType>()->getNumElements() ==
10206              E->getType()->getAs<VectorType>()->getNumElements() &&
10207          RHS->getType()->getAs<VectorType>()->getNumElements() ==
10208              E->getType()->getAs<VectorType>()->getNumElements() &&
10209          "All operands must be the same size.");
10210 
10211   APValue LHSValue;
10212   APValue RHSValue;
10213   bool LHSOK = Evaluate(LHSValue, Info, LHS);
10214   if (!LHSOK && !Info.noteFailure())
10215     return false;
10216   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10217     return false;
10218 
10219   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10220     return false;
10221 
10222   return Success(LHSValue, E);
10223 }
10224 
10225 //===----------------------------------------------------------------------===//
10226 // Array Evaluation
10227 //===----------------------------------------------------------------------===//
10228 
10229 namespace {
10230   class ArrayExprEvaluator
10231   : public ExprEvaluatorBase<ArrayExprEvaluator> {
10232     const LValue &This;
10233     APValue &Result;
10234   public:
10235 
10236     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10237       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10238 
10239     bool Success(const APValue &V, const Expr *E) {
10240       assert(V.isArray() && "expected array");
10241       Result = V;
10242       return true;
10243     }
10244 
10245     bool ZeroInitialization(const Expr *E) {
10246       const ConstantArrayType *CAT =
10247           Info.Ctx.getAsConstantArrayType(E->getType());
10248       if (!CAT) {
10249         if (E->getType()->isIncompleteArrayType()) {
10250           // We can be asked to zero-initialize a flexible array member; this
10251           // is represented as an ImplicitValueInitExpr of incomplete array
10252           // type. In this case, the array has zero elements.
10253           Result = APValue(APValue::UninitArray(), 0, 0);
10254           return true;
10255         }
10256         // FIXME: We could handle VLAs here.
10257         return Error(E);
10258       }
10259 
10260       Result = APValue(APValue::UninitArray(), 0,
10261                        CAT->getSize().getZExtValue());
10262       if (!Result.hasArrayFiller()) return true;
10263 
10264       // Zero-initialize all elements.
10265       LValue Subobject = This;
10266       Subobject.addArray(Info, E, CAT);
10267       ImplicitValueInitExpr VIE(CAT->getElementType());
10268       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10269     }
10270 
10271     bool VisitCallExpr(const CallExpr *E) {
10272       return handleCallExpr(E, Result, &This);
10273     }
10274     bool VisitInitListExpr(const InitListExpr *E,
10275                            QualType AllocType = QualType());
10276     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10277     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10278     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10279                                const LValue &Subobject,
10280                                APValue *Value, QualType Type);
10281     bool VisitStringLiteral(const StringLiteral *E,
10282                             QualType AllocType = QualType()) {
10283       expandStringLiteral(Info, E, Result, AllocType);
10284       return true;
10285     }
10286   };
10287 } // end anonymous namespace
10288 
10289 static bool EvaluateArray(const Expr *E, const LValue &This,
10290                           APValue &Result, EvalInfo &Info) {
10291   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
10292   return ArrayExprEvaluator(Info, This, Result).Visit(E);
10293 }
10294 
10295 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10296                                      APValue &Result, const InitListExpr *ILE,
10297                                      QualType AllocType) {
10298   assert(ILE->isRValue() && ILE->getType()->isArrayType() &&
10299          "not an array rvalue");
10300   return ArrayExprEvaluator(Info, This, Result)
10301       .VisitInitListExpr(ILE, AllocType);
10302 }
10303 
10304 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10305                                           APValue &Result,
10306                                           const CXXConstructExpr *CCE,
10307                                           QualType AllocType) {
10308   assert(CCE->isRValue() && CCE->getType()->isArrayType() &&
10309          "not an array rvalue");
10310   return ArrayExprEvaluator(Info, This, Result)
10311       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10312 }
10313 
10314 // Return true iff the given array filler may depend on the element index.
10315 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10316   // For now, just allow non-class value-initialization and initialization
10317   // lists comprised of them.
10318   if (isa<ImplicitValueInitExpr>(FillerExpr))
10319     return false;
10320   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10321     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10322       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10323         return true;
10324     }
10325     return false;
10326   }
10327   return true;
10328 }
10329 
10330 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10331                                            QualType AllocType) {
10332   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10333       AllocType.isNull() ? E->getType() : AllocType);
10334   if (!CAT)
10335     return Error(E);
10336 
10337   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10338   // an appropriately-typed string literal enclosed in braces.
10339   if (E->isStringLiteralInit()) {
10340     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
10341     // FIXME: Support ObjCEncodeExpr here once we support it in
10342     // ArrayExprEvaluator generally.
10343     if (!SL)
10344       return Error(E);
10345     return VisitStringLiteral(SL, AllocType);
10346   }
10347 
10348   bool Success = true;
10349 
10350   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10351          "zero-initialized array shouldn't have any initialized elts");
10352   APValue Filler;
10353   if (Result.isArray() && Result.hasArrayFiller())
10354     Filler = Result.getArrayFiller();
10355 
10356   unsigned NumEltsToInit = E->getNumInits();
10357   unsigned NumElts = CAT->getSize().getZExtValue();
10358   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
10359 
10360   // If the initializer might depend on the array index, run it for each
10361   // array element.
10362   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
10363     NumEltsToInit = NumElts;
10364 
10365   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10366                           << NumEltsToInit << ".\n");
10367 
10368   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10369 
10370   // If the array was previously zero-initialized, preserve the
10371   // zero-initialized values.
10372   if (Filler.hasValue()) {
10373     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10374       Result.getArrayInitializedElt(I) = Filler;
10375     if (Result.hasArrayFiller())
10376       Result.getArrayFiller() = Filler;
10377   }
10378 
10379   LValue Subobject = This;
10380   Subobject.addArray(Info, E, CAT);
10381   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10382     const Expr *Init =
10383         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
10384     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10385                          Info, Subobject, Init) ||
10386         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10387                                      CAT->getElementType(), 1)) {
10388       if (!Info.noteFailure())
10389         return false;
10390       Success = false;
10391     }
10392   }
10393 
10394   if (!Result.hasArrayFiller())
10395     return Success;
10396 
10397   // If we get here, we have a trivial filler, which we can just evaluate
10398   // once and splat over the rest of the array elements.
10399   assert(FillerExpr && "no array filler for incomplete init list");
10400   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10401                          FillerExpr) && Success;
10402 }
10403 
10404 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10405   LValue CommonLV;
10406   if (E->getCommonExpr() &&
10407       !Evaluate(Info.CurrentCall->createTemporary(
10408                     E->getCommonExpr(),
10409                     getStorageType(Info.Ctx, E->getCommonExpr()),
10410                     ScopeKind::FullExpression, CommonLV),
10411                 Info, E->getCommonExpr()->getSourceExpr()))
10412     return false;
10413 
10414   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10415 
10416   uint64_t Elements = CAT->getSize().getZExtValue();
10417   Result = APValue(APValue::UninitArray(), Elements, Elements);
10418 
10419   LValue Subobject = This;
10420   Subobject.addArray(Info, E, CAT);
10421 
10422   bool Success = true;
10423   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10424     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10425                          Info, Subobject, E->getSubExpr()) ||
10426         !HandleLValueArrayAdjustment(Info, E, Subobject,
10427                                      CAT->getElementType(), 1)) {
10428       if (!Info.noteFailure())
10429         return false;
10430       Success = false;
10431     }
10432   }
10433 
10434   return Success;
10435 }
10436 
10437 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10438   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10439 }
10440 
10441 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10442                                                const LValue &Subobject,
10443                                                APValue *Value,
10444                                                QualType Type) {
10445   bool HadZeroInit = Value->hasValue();
10446 
10447   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10448     unsigned N = CAT->getSize().getZExtValue();
10449 
10450     // Preserve the array filler if we had prior zero-initialization.
10451     APValue Filler =
10452       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10453                                              : APValue();
10454 
10455     *Value = APValue(APValue::UninitArray(), N, N);
10456 
10457     if (HadZeroInit)
10458       for (unsigned I = 0; I != N; ++I)
10459         Value->getArrayInitializedElt(I) = Filler;
10460 
10461     // Initialize the elements.
10462     LValue ArrayElt = Subobject;
10463     ArrayElt.addArray(Info, E, CAT);
10464     for (unsigned I = 0; I != N; ++I)
10465       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
10466                                  CAT->getElementType()) ||
10467           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10468                                        CAT->getElementType(), 1))
10469         return false;
10470 
10471     return true;
10472   }
10473 
10474   if (!Type->isRecordType())
10475     return Error(E);
10476 
10477   return RecordExprEvaluator(Info, Subobject, *Value)
10478              .VisitCXXConstructExpr(E, Type);
10479 }
10480 
10481 //===----------------------------------------------------------------------===//
10482 // Integer Evaluation
10483 //
10484 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10485 // types and back in constant folding. Integer values are thus represented
10486 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10487 //===----------------------------------------------------------------------===//
10488 
10489 namespace {
10490 class IntExprEvaluator
10491         : public ExprEvaluatorBase<IntExprEvaluator> {
10492   APValue &Result;
10493 public:
10494   IntExprEvaluator(EvalInfo &info, APValue &result)
10495       : ExprEvaluatorBaseTy(info), Result(result) {}
10496 
10497   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10498     assert(E->getType()->isIntegralOrEnumerationType() &&
10499            "Invalid evaluation result.");
10500     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10501            "Invalid evaluation result.");
10502     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10503            "Invalid evaluation result.");
10504     Result = APValue(SI);
10505     return true;
10506   }
10507   bool Success(const llvm::APSInt &SI, const Expr *E) {
10508     return Success(SI, E, Result);
10509   }
10510 
10511   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10512     assert(E->getType()->isIntegralOrEnumerationType() &&
10513            "Invalid evaluation result.");
10514     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10515            "Invalid evaluation result.");
10516     Result = APValue(APSInt(I));
10517     Result.getInt().setIsUnsigned(
10518                             E->getType()->isUnsignedIntegerOrEnumerationType());
10519     return true;
10520   }
10521   bool Success(const llvm::APInt &I, const Expr *E) {
10522     return Success(I, E, Result);
10523   }
10524 
10525   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10526     assert(E->getType()->isIntegralOrEnumerationType() &&
10527            "Invalid evaluation result.");
10528     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10529     return true;
10530   }
10531   bool Success(uint64_t Value, const Expr *E) {
10532     return Success(Value, E, Result);
10533   }
10534 
10535   bool Success(CharUnits Size, const Expr *E) {
10536     return Success(Size.getQuantity(), E);
10537   }
10538 
10539   bool Success(const APValue &V, const Expr *E) {
10540     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10541       Result = V;
10542       return true;
10543     }
10544     return Success(V.getInt(), E);
10545   }
10546 
10547   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10548 
10549   //===--------------------------------------------------------------------===//
10550   //                            Visitor Methods
10551   //===--------------------------------------------------------------------===//
10552 
10553   bool VisitIntegerLiteral(const IntegerLiteral *E) {
10554     return Success(E->getValue(), E);
10555   }
10556   bool VisitCharacterLiteral(const CharacterLiteral *E) {
10557     return Success(E->getValue(), E);
10558   }
10559 
10560   bool CheckReferencedDecl(const Expr *E, const Decl *D);
10561   bool VisitDeclRefExpr(const DeclRefExpr *E) {
10562     if (CheckReferencedDecl(E, E->getDecl()))
10563       return true;
10564 
10565     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
10566   }
10567   bool VisitMemberExpr(const MemberExpr *E) {
10568     if (CheckReferencedDecl(E, E->getMemberDecl())) {
10569       VisitIgnoredBaseExpression(E->getBase());
10570       return true;
10571     }
10572 
10573     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
10574   }
10575 
10576   bool VisitCallExpr(const CallExpr *E);
10577   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10578   bool VisitBinaryOperator(const BinaryOperator *E);
10579   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
10580   bool VisitUnaryOperator(const UnaryOperator *E);
10581 
10582   bool VisitCastExpr(const CastExpr* E);
10583   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
10584 
10585   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
10586     return Success(E->getValue(), E);
10587   }
10588 
10589   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
10590     return Success(E->getValue(), E);
10591   }
10592 
10593   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
10594     if (Info.ArrayInitIndex == uint64_t(-1)) {
10595       // We were asked to evaluate this subexpression independent of the
10596       // enclosing ArrayInitLoopExpr. We can't do that.
10597       Info.FFDiag(E);
10598       return false;
10599     }
10600     return Success(Info.ArrayInitIndex, E);
10601   }
10602 
10603   // Note, GNU defines __null as an integer, not a pointer.
10604   bool VisitGNUNullExpr(const GNUNullExpr *E) {
10605     return ZeroInitialization(E);
10606   }
10607 
10608   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
10609     return Success(E->getValue(), E);
10610   }
10611 
10612   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
10613     return Success(E->getValue(), E);
10614   }
10615 
10616   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
10617     return Success(E->getValue(), E);
10618   }
10619 
10620   bool VisitUnaryReal(const UnaryOperator *E);
10621   bool VisitUnaryImag(const UnaryOperator *E);
10622 
10623   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
10624   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
10625   bool VisitSourceLocExpr(const SourceLocExpr *E);
10626   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
10627   bool VisitRequiresExpr(const RequiresExpr *E);
10628   // FIXME: Missing: array subscript of vector, member of vector
10629 };
10630 
10631 class FixedPointExprEvaluator
10632     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
10633   APValue &Result;
10634 
10635  public:
10636   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
10637       : ExprEvaluatorBaseTy(info), Result(result) {}
10638 
10639   bool Success(const llvm::APInt &I, const Expr *E) {
10640     return Success(
10641         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10642   }
10643 
10644   bool Success(uint64_t Value, const Expr *E) {
10645     return Success(
10646         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10647   }
10648 
10649   bool Success(const APValue &V, const Expr *E) {
10650     return Success(V.getFixedPoint(), E);
10651   }
10652 
10653   bool Success(const APFixedPoint &V, const Expr *E) {
10654     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
10655     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10656            "Invalid evaluation result.");
10657     Result = APValue(V);
10658     return true;
10659   }
10660 
10661   //===--------------------------------------------------------------------===//
10662   //                            Visitor Methods
10663   //===--------------------------------------------------------------------===//
10664 
10665   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
10666     return Success(E->getValue(), E);
10667   }
10668 
10669   bool VisitCastExpr(const CastExpr *E);
10670   bool VisitUnaryOperator(const UnaryOperator *E);
10671   bool VisitBinaryOperator(const BinaryOperator *E);
10672 };
10673 } // end anonymous namespace
10674 
10675 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
10676 /// produce either the integer value or a pointer.
10677 ///
10678 /// GCC has a heinous extension which folds casts between pointer types and
10679 /// pointer-sized integral types. We support this by allowing the evaluation of
10680 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
10681 /// Some simple arithmetic on such values is supported (they are treated much
10682 /// like char*).
10683 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
10684                                     EvalInfo &Info) {
10685   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
10686   return IntExprEvaluator(Info, Result).Visit(E);
10687 }
10688 
10689 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
10690   APValue Val;
10691   if (!EvaluateIntegerOrLValue(E, Val, Info))
10692     return false;
10693   if (!Val.isInt()) {
10694     // FIXME: It would be better to produce the diagnostic for casting
10695     //        a pointer to an integer.
10696     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10697     return false;
10698   }
10699   Result = Val.getInt();
10700   return true;
10701 }
10702 
10703 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
10704   APValue Evaluated = E->EvaluateInContext(
10705       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10706   return Success(Evaluated, E);
10707 }
10708 
10709 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
10710                                EvalInfo &Info) {
10711   if (E->getType()->isFixedPointType()) {
10712     APValue Val;
10713     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
10714       return false;
10715     if (!Val.isFixedPoint())
10716       return false;
10717 
10718     Result = Val.getFixedPoint();
10719     return true;
10720   }
10721   return false;
10722 }
10723 
10724 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
10725                                         EvalInfo &Info) {
10726   if (E->getType()->isIntegerType()) {
10727     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
10728     APSInt Val;
10729     if (!EvaluateInteger(E, Val, Info))
10730       return false;
10731     Result = APFixedPoint(Val, FXSema);
10732     return true;
10733   } else if (E->getType()->isFixedPointType()) {
10734     return EvaluateFixedPoint(E, Result, Info);
10735   }
10736   return false;
10737 }
10738 
10739 /// Check whether the given declaration can be directly converted to an integral
10740 /// rvalue. If not, no diagnostic is produced; there are other things we can
10741 /// try.
10742 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
10743   // Enums are integer constant exprs.
10744   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
10745     // Check for signedness/width mismatches between E type and ECD value.
10746     bool SameSign = (ECD->getInitVal().isSigned()
10747                      == E->getType()->isSignedIntegerOrEnumerationType());
10748     bool SameWidth = (ECD->getInitVal().getBitWidth()
10749                       == Info.Ctx.getIntWidth(E->getType()));
10750     if (SameSign && SameWidth)
10751       return Success(ECD->getInitVal(), E);
10752     else {
10753       // Get rid of mismatch (otherwise Success assertions will fail)
10754       // by computing a new value matching the type of E.
10755       llvm::APSInt Val = ECD->getInitVal();
10756       if (!SameSign)
10757         Val.setIsSigned(!ECD->getInitVal().isSigned());
10758       if (!SameWidth)
10759         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
10760       return Success(Val, E);
10761     }
10762   }
10763   return false;
10764 }
10765 
10766 /// Values returned by __builtin_classify_type, chosen to match the values
10767 /// produced by GCC's builtin.
10768 enum class GCCTypeClass {
10769   None = -1,
10770   Void = 0,
10771   Integer = 1,
10772   // GCC reserves 2 for character types, but instead classifies them as
10773   // integers.
10774   Enum = 3,
10775   Bool = 4,
10776   Pointer = 5,
10777   // GCC reserves 6 for references, but appears to never use it (because
10778   // expressions never have reference type, presumably).
10779   PointerToDataMember = 7,
10780   RealFloat = 8,
10781   Complex = 9,
10782   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
10783   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
10784   // GCC claims to reserve 11 for pointers to member functions, but *actually*
10785   // uses 12 for that purpose, same as for a class or struct. Maybe it
10786   // internally implements a pointer to member as a struct?  Who knows.
10787   PointerToMemberFunction = 12, // Not a bug, see above.
10788   ClassOrStruct = 12,
10789   Union = 13,
10790   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
10791   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
10792   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
10793   // literals.
10794 };
10795 
10796 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10797 /// as GCC.
10798 static GCCTypeClass
10799 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
10800   assert(!T->isDependentType() && "unexpected dependent type");
10801 
10802   QualType CanTy = T.getCanonicalType();
10803   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
10804 
10805   switch (CanTy->getTypeClass()) {
10806 #define TYPE(ID, BASE)
10807 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
10808 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
10809 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
10810 #include "clang/AST/TypeNodes.inc"
10811   case Type::Auto:
10812   case Type::DeducedTemplateSpecialization:
10813       llvm_unreachable("unexpected non-canonical or dependent type");
10814 
10815   case Type::Builtin:
10816     switch (BT->getKind()) {
10817 #define BUILTIN_TYPE(ID, SINGLETON_ID)
10818 #define SIGNED_TYPE(ID, SINGLETON_ID) \
10819     case BuiltinType::ID: return GCCTypeClass::Integer;
10820 #define FLOATING_TYPE(ID, SINGLETON_ID) \
10821     case BuiltinType::ID: return GCCTypeClass::RealFloat;
10822 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
10823     case BuiltinType::ID: break;
10824 #include "clang/AST/BuiltinTypes.def"
10825     case BuiltinType::Void:
10826       return GCCTypeClass::Void;
10827 
10828     case BuiltinType::Bool:
10829       return GCCTypeClass::Bool;
10830 
10831     case BuiltinType::Char_U:
10832     case BuiltinType::UChar:
10833     case BuiltinType::WChar_U:
10834     case BuiltinType::Char8:
10835     case BuiltinType::Char16:
10836     case BuiltinType::Char32:
10837     case BuiltinType::UShort:
10838     case BuiltinType::UInt:
10839     case BuiltinType::ULong:
10840     case BuiltinType::ULongLong:
10841     case BuiltinType::UInt128:
10842       return GCCTypeClass::Integer;
10843 
10844     case BuiltinType::UShortAccum:
10845     case BuiltinType::UAccum:
10846     case BuiltinType::ULongAccum:
10847     case BuiltinType::UShortFract:
10848     case BuiltinType::UFract:
10849     case BuiltinType::ULongFract:
10850     case BuiltinType::SatUShortAccum:
10851     case BuiltinType::SatUAccum:
10852     case BuiltinType::SatULongAccum:
10853     case BuiltinType::SatUShortFract:
10854     case BuiltinType::SatUFract:
10855     case BuiltinType::SatULongFract:
10856       return GCCTypeClass::None;
10857 
10858     case BuiltinType::NullPtr:
10859 
10860     case BuiltinType::ObjCId:
10861     case BuiltinType::ObjCClass:
10862     case BuiltinType::ObjCSel:
10863 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
10864     case BuiltinType::Id:
10865 #include "clang/Basic/OpenCLImageTypes.def"
10866 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
10867     case BuiltinType::Id:
10868 #include "clang/Basic/OpenCLExtensionTypes.def"
10869     case BuiltinType::OCLSampler:
10870     case BuiltinType::OCLEvent:
10871     case BuiltinType::OCLClkEvent:
10872     case BuiltinType::OCLQueue:
10873     case BuiltinType::OCLReserveID:
10874 #define SVE_TYPE(Name, Id, SingletonId) \
10875     case BuiltinType::Id:
10876 #include "clang/Basic/AArch64SVEACLETypes.def"
10877       return GCCTypeClass::None;
10878 
10879     case BuiltinType::Dependent:
10880       llvm_unreachable("unexpected dependent type");
10881     };
10882     llvm_unreachable("unexpected placeholder type");
10883 
10884   case Type::Enum:
10885     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
10886 
10887   case Type::Pointer:
10888   case Type::ConstantArray:
10889   case Type::VariableArray:
10890   case Type::IncompleteArray:
10891   case Type::FunctionNoProto:
10892   case Type::FunctionProto:
10893     return GCCTypeClass::Pointer;
10894 
10895   case Type::MemberPointer:
10896     return CanTy->isMemberDataPointerType()
10897                ? GCCTypeClass::PointerToDataMember
10898                : GCCTypeClass::PointerToMemberFunction;
10899 
10900   case Type::Complex:
10901     return GCCTypeClass::Complex;
10902 
10903   case Type::Record:
10904     return CanTy->isUnionType() ? GCCTypeClass::Union
10905                                 : GCCTypeClass::ClassOrStruct;
10906 
10907   case Type::Atomic:
10908     // GCC classifies _Atomic T the same as T.
10909     return EvaluateBuiltinClassifyType(
10910         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
10911 
10912   case Type::BlockPointer:
10913   case Type::Vector:
10914   case Type::ExtVector:
10915   case Type::ConstantMatrix:
10916   case Type::ObjCObject:
10917   case Type::ObjCInterface:
10918   case Type::ObjCObjectPointer:
10919   case Type::Pipe:
10920   case Type::ExtInt:
10921     // GCC classifies vectors as None. We follow its lead and classify all
10922     // other types that don't fit into the regular classification the same way.
10923     return GCCTypeClass::None;
10924 
10925   case Type::LValueReference:
10926   case Type::RValueReference:
10927     llvm_unreachable("invalid type for expression");
10928   }
10929 
10930   llvm_unreachable("unexpected type class");
10931 }
10932 
10933 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10934 /// as GCC.
10935 static GCCTypeClass
10936 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
10937   // If no argument was supplied, default to None. This isn't
10938   // ideal, however it is what gcc does.
10939   if (E->getNumArgs() == 0)
10940     return GCCTypeClass::None;
10941 
10942   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
10943   // being an ICE, but still folds it to a constant using the type of the first
10944   // argument.
10945   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
10946 }
10947 
10948 /// EvaluateBuiltinConstantPForLValue - Determine the result of
10949 /// __builtin_constant_p when applied to the given pointer.
10950 ///
10951 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
10952 /// or it points to the first character of a string literal.
10953 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
10954   APValue::LValueBase Base = LV.getLValueBase();
10955   if (Base.isNull()) {
10956     // A null base is acceptable.
10957     return true;
10958   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
10959     if (!isa<StringLiteral>(E))
10960       return false;
10961     return LV.getLValueOffset().isZero();
10962   } else if (Base.is<TypeInfoLValue>()) {
10963     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
10964     // evaluate to true.
10965     return true;
10966   } else {
10967     // Any other base is not constant enough for GCC.
10968     return false;
10969   }
10970 }
10971 
10972 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
10973 /// GCC as we can manage.
10974 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
10975   // This evaluation is not permitted to have side-effects, so evaluate it in
10976   // a speculative evaluation context.
10977   SpeculativeEvaluationRAII SpeculativeEval(Info);
10978 
10979   // Constant-folding is always enabled for the operand of __builtin_constant_p
10980   // (even when the enclosing evaluation context otherwise requires a strict
10981   // language-specific constant expression).
10982   FoldConstant Fold(Info, true);
10983 
10984   QualType ArgType = Arg->getType();
10985 
10986   // __builtin_constant_p always has one operand. The rules which gcc follows
10987   // are not precisely documented, but are as follows:
10988   //
10989   //  - If the operand is of integral, floating, complex or enumeration type,
10990   //    and can be folded to a known value of that type, it returns 1.
10991   //  - If the operand can be folded to a pointer to the first character
10992   //    of a string literal (or such a pointer cast to an integral type)
10993   //    or to a null pointer or an integer cast to a pointer, it returns 1.
10994   //
10995   // Otherwise, it returns 0.
10996   //
10997   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
10998   // its support for this did not work prior to GCC 9 and is not yet well
10999   // understood.
11000   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11001       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11002       ArgType->isNullPtrType()) {
11003     APValue V;
11004     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11005       Fold.keepDiagnostics();
11006       return false;
11007     }
11008 
11009     // For a pointer (possibly cast to integer), there are special rules.
11010     if (V.getKind() == APValue::LValue)
11011       return EvaluateBuiltinConstantPForLValue(V);
11012 
11013     // Otherwise, any constant value is good enough.
11014     return V.hasValue();
11015   }
11016 
11017   // Anything else isn't considered to be sufficiently constant.
11018   return false;
11019 }
11020 
11021 /// Retrieves the "underlying object type" of the given expression,
11022 /// as used by __builtin_object_size.
11023 static QualType getObjectType(APValue::LValueBase B) {
11024   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11025     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11026       return VD->getType();
11027   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11028     if (isa<CompoundLiteralExpr>(E))
11029       return E->getType();
11030   } else if (B.is<TypeInfoLValue>()) {
11031     return B.getTypeInfoType();
11032   } else if (B.is<DynamicAllocLValue>()) {
11033     return B.getDynamicAllocType();
11034   }
11035 
11036   return QualType();
11037 }
11038 
11039 /// A more selective version of E->IgnoreParenCasts for
11040 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11041 /// to change the type of E.
11042 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11043 ///
11044 /// Always returns an RValue with a pointer representation.
11045 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11046   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
11047 
11048   auto *NoParens = E->IgnoreParens();
11049   auto *Cast = dyn_cast<CastExpr>(NoParens);
11050   if (Cast == nullptr)
11051     return NoParens;
11052 
11053   // We only conservatively allow a few kinds of casts, because this code is
11054   // inherently a simple solution that seeks to support the common case.
11055   auto CastKind = Cast->getCastKind();
11056   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11057       CastKind != CK_AddressSpaceConversion)
11058     return NoParens;
11059 
11060   auto *SubExpr = Cast->getSubExpr();
11061   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
11062     return NoParens;
11063   return ignorePointerCastsAndParens(SubExpr);
11064 }
11065 
11066 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11067 /// record layout. e.g.
11068 ///   struct { struct { int a, b; } fst, snd; } obj;
11069 ///   obj.fst   // no
11070 ///   obj.snd   // yes
11071 ///   obj.fst.a // no
11072 ///   obj.fst.b // no
11073 ///   obj.snd.a // no
11074 ///   obj.snd.b // yes
11075 ///
11076 /// Please note: this function is specialized for how __builtin_object_size
11077 /// views "objects".
11078 ///
11079 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11080 /// correct result, it will always return true.
11081 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11082   assert(!LVal.Designator.Invalid);
11083 
11084   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11085     const RecordDecl *Parent = FD->getParent();
11086     Invalid = Parent->isInvalidDecl();
11087     if (Invalid || Parent->isUnion())
11088       return true;
11089     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11090     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11091   };
11092 
11093   auto &Base = LVal.getLValueBase();
11094   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11095     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11096       bool Invalid;
11097       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11098         return Invalid;
11099     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11100       for (auto *FD : IFD->chain()) {
11101         bool Invalid;
11102         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11103           return Invalid;
11104       }
11105     }
11106   }
11107 
11108   unsigned I = 0;
11109   QualType BaseType = getType(Base);
11110   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11111     // If we don't know the array bound, conservatively assume we're looking at
11112     // the final array element.
11113     ++I;
11114     if (BaseType->isIncompleteArrayType())
11115       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11116     else
11117       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11118   }
11119 
11120   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11121     const auto &Entry = LVal.Designator.Entries[I];
11122     if (BaseType->isArrayType()) {
11123       // Because __builtin_object_size treats arrays as objects, we can ignore
11124       // the index iff this is the last array in the Designator.
11125       if (I + 1 == E)
11126         return true;
11127       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11128       uint64_t Index = Entry.getAsArrayIndex();
11129       if (Index + 1 != CAT->getSize())
11130         return false;
11131       BaseType = CAT->getElementType();
11132     } else if (BaseType->isAnyComplexType()) {
11133       const auto *CT = BaseType->castAs<ComplexType>();
11134       uint64_t Index = Entry.getAsArrayIndex();
11135       if (Index != 1)
11136         return false;
11137       BaseType = CT->getElementType();
11138     } else if (auto *FD = getAsField(Entry)) {
11139       bool Invalid;
11140       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11141         return Invalid;
11142       BaseType = FD->getType();
11143     } else {
11144       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11145       return false;
11146     }
11147   }
11148   return true;
11149 }
11150 
11151 /// Tests to see if the LValue has a user-specified designator (that isn't
11152 /// necessarily valid). Note that this always returns 'true' if the LValue has
11153 /// an unsized array as its first designator entry, because there's currently no
11154 /// way to tell if the user typed *foo or foo[0].
11155 static bool refersToCompleteObject(const LValue &LVal) {
11156   if (LVal.Designator.Invalid)
11157     return false;
11158 
11159   if (!LVal.Designator.Entries.empty())
11160     return LVal.Designator.isMostDerivedAnUnsizedArray();
11161 
11162   if (!LVal.InvalidBase)
11163     return true;
11164 
11165   // If `E` is a MemberExpr, then the first part of the designator is hiding in
11166   // the LValueBase.
11167   const auto *E = LVal.Base.dyn_cast<const Expr *>();
11168   return !E || !isa<MemberExpr>(E);
11169 }
11170 
11171 /// Attempts to detect a user writing into a piece of memory that's impossible
11172 /// to figure out the size of by just using types.
11173 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11174   const SubobjectDesignator &Designator = LVal.Designator;
11175   // Notes:
11176   // - Users can only write off of the end when we have an invalid base. Invalid
11177   //   bases imply we don't know where the memory came from.
11178   // - We used to be a bit more aggressive here; we'd only be conservative if
11179   //   the array at the end was flexible, or if it had 0 or 1 elements. This
11180   //   broke some common standard library extensions (PR30346), but was
11181   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
11182   //   with some sort of list. OTOH, it seems that GCC is always
11183   //   conservative with the last element in structs (if it's an array), so our
11184   //   current behavior is more compatible than an explicit list approach would
11185   //   be.
11186   return LVal.InvalidBase &&
11187          Designator.Entries.size() == Designator.MostDerivedPathLength &&
11188          Designator.MostDerivedIsArrayElement &&
11189          isDesignatorAtObjectEnd(Ctx, LVal);
11190 }
11191 
11192 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11193 /// Fails if the conversion would cause loss of precision.
11194 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11195                                             CharUnits &Result) {
11196   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11197   if (Int.ugt(CharUnitsMax))
11198     return false;
11199   Result = CharUnits::fromQuantity(Int.getZExtValue());
11200   return true;
11201 }
11202 
11203 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11204 /// determine how many bytes exist from the beginning of the object to either
11205 /// the end of the current subobject, or the end of the object itself, depending
11206 /// on what the LValue looks like + the value of Type.
11207 ///
11208 /// If this returns false, the value of Result is undefined.
11209 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11210                                unsigned Type, const LValue &LVal,
11211                                CharUnits &EndOffset) {
11212   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11213 
11214   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11215     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11216       return false;
11217     return HandleSizeof(Info, ExprLoc, Ty, Result);
11218   };
11219 
11220   // We want to evaluate the size of the entire object. This is a valid fallback
11221   // for when Type=1 and the designator is invalid, because we're asked for an
11222   // upper-bound.
11223   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11224     // Type=3 wants a lower bound, so we can't fall back to this.
11225     if (Type == 3 && !DetermineForCompleteObject)
11226       return false;
11227 
11228     llvm::APInt APEndOffset;
11229     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11230         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11231       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11232 
11233     if (LVal.InvalidBase)
11234       return false;
11235 
11236     QualType BaseTy = getObjectType(LVal.getLValueBase());
11237     return CheckedHandleSizeof(BaseTy, EndOffset);
11238   }
11239 
11240   // We want to evaluate the size of a subobject.
11241   const SubobjectDesignator &Designator = LVal.Designator;
11242 
11243   // The following is a moderately common idiom in C:
11244   //
11245   // struct Foo { int a; char c[1]; };
11246   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11247   // strcpy(&F->c[0], Bar);
11248   //
11249   // In order to not break too much legacy code, we need to support it.
11250   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11251     // If we can resolve this to an alloc_size call, we can hand that back,
11252     // because we know for certain how many bytes there are to write to.
11253     llvm::APInt APEndOffset;
11254     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11255         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11256       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11257 
11258     // If we cannot determine the size of the initial allocation, then we can't
11259     // given an accurate upper-bound. However, we are still able to give
11260     // conservative lower-bounds for Type=3.
11261     if (Type == 1)
11262       return false;
11263   }
11264 
11265   CharUnits BytesPerElem;
11266   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11267     return false;
11268 
11269   // According to the GCC documentation, we want the size of the subobject
11270   // denoted by the pointer. But that's not quite right -- what we actually
11271   // want is the size of the immediately-enclosing array, if there is one.
11272   int64_t ElemsRemaining;
11273   if (Designator.MostDerivedIsArrayElement &&
11274       Designator.Entries.size() == Designator.MostDerivedPathLength) {
11275     uint64_t ArraySize = Designator.getMostDerivedArraySize();
11276     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11277     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11278   } else {
11279     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11280   }
11281 
11282   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11283   return true;
11284 }
11285 
11286 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11287 /// returns true and stores the result in @p Size.
11288 ///
11289 /// If @p WasError is non-null, this will report whether the failure to evaluate
11290 /// is to be treated as an Error in IntExprEvaluator.
11291 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11292                                          EvalInfo &Info, uint64_t &Size) {
11293   // Determine the denoted object.
11294   LValue LVal;
11295   {
11296     // The operand of __builtin_object_size is never evaluated for side-effects.
11297     // If there are any, but we can determine the pointed-to object anyway, then
11298     // ignore the side-effects.
11299     SpeculativeEvaluationRAII SpeculativeEval(Info);
11300     IgnoreSideEffectsRAII Fold(Info);
11301 
11302     if (E->isGLValue()) {
11303       // It's possible for us to be given GLValues if we're called via
11304       // Expr::tryEvaluateObjectSize.
11305       APValue RVal;
11306       if (!EvaluateAsRValue(Info, E, RVal))
11307         return false;
11308       LVal.setFrom(Info.Ctx, RVal);
11309     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11310                                 /*InvalidBaseOK=*/true))
11311       return false;
11312   }
11313 
11314   // If we point to before the start of the object, there are no accessible
11315   // bytes.
11316   if (LVal.getLValueOffset().isNegative()) {
11317     Size = 0;
11318     return true;
11319   }
11320 
11321   CharUnits EndOffset;
11322   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11323     return false;
11324 
11325   // If we've fallen outside of the end offset, just pretend there's nothing to
11326   // write to/read from.
11327   if (EndOffset <= LVal.getLValueOffset())
11328     Size = 0;
11329   else
11330     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11331   return true;
11332 }
11333 
11334 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11335   if (unsigned BuiltinOp = E->getBuiltinCallee())
11336     return VisitBuiltinCallExpr(E, BuiltinOp);
11337 
11338   return ExprEvaluatorBaseTy::VisitCallExpr(E);
11339 }
11340 
11341 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11342                                      APValue &Val, APSInt &Alignment) {
11343   QualType SrcTy = E->getArg(0)->getType();
11344   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11345     return false;
11346   // Even though we are evaluating integer expressions we could get a pointer
11347   // argument for the __builtin_is_aligned() case.
11348   if (SrcTy->isPointerType()) {
11349     LValue Ptr;
11350     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11351       return false;
11352     Ptr.moveInto(Val);
11353   } else if (!SrcTy->isIntegralOrEnumerationType()) {
11354     Info.FFDiag(E->getArg(0));
11355     return false;
11356   } else {
11357     APSInt SrcInt;
11358     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11359       return false;
11360     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11361            "Bit widths must be the same");
11362     Val = APValue(SrcInt);
11363   }
11364   assert(Val.hasValue());
11365   return true;
11366 }
11367 
11368 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11369                                             unsigned BuiltinOp) {
11370   switch (BuiltinOp) {
11371   default:
11372     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11373 
11374   case Builtin::BI__builtin_dynamic_object_size:
11375   case Builtin::BI__builtin_object_size: {
11376     // The type was checked when we built the expression.
11377     unsigned Type =
11378         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11379     assert(Type <= 3 && "unexpected type");
11380 
11381     uint64_t Size;
11382     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11383       return Success(Size, E);
11384 
11385     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11386       return Success((Type & 2) ? 0 : -1, E);
11387 
11388     // Expression had no side effects, but we couldn't statically determine the
11389     // size of the referenced object.
11390     switch (Info.EvalMode) {
11391     case EvalInfo::EM_ConstantExpression:
11392     case EvalInfo::EM_ConstantFold:
11393     case EvalInfo::EM_IgnoreSideEffects:
11394       // Leave it to IR generation.
11395       return Error(E);
11396     case EvalInfo::EM_ConstantExpressionUnevaluated:
11397       // Reduce it to a constant now.
11398       return Success((Type & 2) ? 0 : -1, E);
11399     }
11400 
11401     llvm_unreachable("unexpected EvalMode");
11402   }
11403 
11404   case Builtin::BI__builtin_os_log_format_buffer_size: {
11405     analyze_os_log::OSLogBufferLayout Layout;
11406     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11407     return Success(Layout.size().getQuantity(), E);
11408   }
11409 
11410   case Builtin::BI__builtin_is_aligned: {
11411     APValue Src;
11412     APSInt Alignment;
11413     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11414       return false;
11415     if (Src.isLValue()) {
11416       // If we evaluated a pointer, check the minimum known alignment.
11417       LValue Ptr;
11418       Ptr.setFrom(Info.Ctx, Src);
11419       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11420       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11421       // We can return true if the known alignment at the computed offset is
11422       // greater than the requested alignment.
11423       assert(PtrAlign.isPowerOfTwo());
11424       assert(Alignment.isPowerOf2());
11425       if (PtrAlign.getQuantity() >= Alignment)
11426         return Success(1, E);
11427       // If the alignment is not known to be sufficient, some cases could still
11428       // be aligned at run time. However, if the requested alignment is less or
11429       // equal to the base alignment and the offset is not aligned, we know that
11430       // the run-time value can never be aligned.
11431       if (BaseAlignment.getQuantity() >= Alignment &&
11432           PtrAlign.getQuantity() < Alignment)
11433         return Success(0, E);
11434       // Otherwise we can't infer whether the value is sufficiently aligned.
11435       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11436       //  in cases where we can't fully evaluate the pointer.
11437       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11438           << Alignment;
11439       return false;
11440     }
11441     assert(Src.isInt());
11442     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11443   }
11444   case Builtin::BI__builtin_align_up: {
11445     APValue Src;
11446     APSInt Alignment;
11447     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11448       return false;
11449     if (!Src.isInt())
11450       return Error(E);
11451     APSInt AlignedVal =
11452         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11453                Src.getInt().isUnsigned());
11454     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11455     return Success(AlignedVal, E);
11456   }
11457   case Builtin::BI__builtin_align_down: {
11458     APValue Src;
11459     APSInt Alignment;
11460     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11461       return false;
11462     if (!Src.isInt())
11463       return Error(E);
11464     APSInt AlignedVal =
11465         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11466     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11467     return Success(AlignedVal, E);
11468   }
11469 
11470   case Builtin::BI__builtin_bitreverse8:
11471   case Builtin::BI__builtin_bitreverse16:
11472   case Builtin::BI__builtin_bitreverse32:
11473   case Builtin::BI__builtin_bitreverse64: {
11474     APSInt Val;
11475     if (!EvaluateInteger(E->getArg(0), Val, Info))
11476       return false;
11477 
11478     return Success(Val.reverseBits(), E);
11479   }
11480 
11481   case Builtin::BI__builtin_bswap16:
11482   case Builtin::BI__builtin_bswap32:
11483   case Builtin::BI__builtin_bswap64: {
11484     APSInt Val;
11485     if (!EvaluateInteger(E->getArg(0), Val, Info))
11486       return false;
11487 
11488     return Success(Val.byteSwap(), E);
11489   }
11490 
11491   case Builtin::BI__builtin_classify_type:
11492     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11493 
11494   case Builtin::BI__builtin_clrsb:
11495   case Builtin::BI__builtin_clrsbl:
11496   case Builtin::BI__builtin_clrsbll: {
11497     APSInt Val;
11498     if (!EvaluateInteger(E->getArg(0), Val, Info))
11499       return false;
11500 
11501     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11502   }
11503 
11504   case Builtin::BI__builtin_clz:
11505   case Builtin::BI__builtin_clzl:
11506   case Builtin::BI__builtin_clzll:
11507   case Builtin::BI__builtin_clzs: {
11508     APSInt Val;
11509     if (!EvaluateInteger(E->getArg(0), Val, Info))
11510       return false;
11511     if (!Val)
11512       return Error(E);
11513 
11514     return Success(Val.countLeadingZeros(), E);
11515   }
11516 
11517   case Builtin::BI__builtin_constant_p: {
11518     const Expr *Arg = E->getArg(0);
11519     if (EvaluateBuiltinConstantP(Info, Arg))
11520       return Success(true, E);
11521     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11522       // Outside a constant context, eagerly evaluate to false in the presence
11523       // of side-effects in order to avoid -Wunsequenced false-positives in
11524       // a branch on __builtin_constant_p(expr).
11525       return Success(false, E);
11526     }
11527     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11528     return false;
11529   }
11530 
11531   case Builtin::BI__builtin_is_constant_evaluated: {
11532     const auto *Callee = Info.CurrentCall->getCallee();
11533     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
11534         (Info.CallStackDepth == 1 ||
11535          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
11536           Callee->getIdentifier() &&
11537           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
11538       // FIXME: Find a better way to avoid duplicated diagnostics.
11539       if (Info.EvalStatus.Diag)
11540         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
11541                                                : Info.CurrentCall->CallLoc,
11542                     diag::warn_is_constant_evaluated_always_true_constexpr)
11543             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
11544                                          : "std::is_constant_evaluated");
11545     }
11546 
11547     return Success(Info.InConstantContext, E);
11548   }
11549 
11550   case Builtin::BI__builtin_ctz:
11551   case Builtin::BI__builtin_ctzl:
11552   case Builtin::BI__builtin_ctzll:
11553   case Builtin::BI__builtin_ctzs: {
11554     APSInt Val;
11555     if (!EvaluateInteger(E->getArg(0), Val, Info))
11556       return false;
11557     if (!Val)
11558       return Error(E);
11559 
11560     return Success(Val.countTrailingZeros(), E);
11561   }
11562 
11563   case Builtin::BI__builtin_eh_return_data_regno: {
11564     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11565     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
11566     return Success(Operand, E);
11567   }
11568 
11569   case Builtin::BI__builtin_expect:
11570   case Builtin::BI__builtin_expect_with_probability:
11571     return Visit(E->getArg(0));
11572 
11573   case Builtin::BI__builtin_ffs:
11574   case Builtin::BI__builtin_ffsl:
11575   case Builtin::BI__builtin_ffsll: {
11576     APSInt Val;
11577     if (!EvaluateInteger(E->getArg(0), Val, Info))
11578       return false;
11579 
11580     unsigned N = Val.countTrailingZeros();
11581     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
11582   }
11583 
11584   case Builtin::BI__builtin_fpclassify: {
11585     APFloat Val(0.0);
11586     if (!EvaluateFloat(E->getArg(5), Val, Info))
11587       return false;
11588     unsigned Arg;
11589     switch (Val.getCategory()) {
11590     case APFloat::fcNaN: Arg = 0; break;
11591     case APFloat::fcInfinity: Arg = 1; break;
11592     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
11593     case APFloat::fcZero: Arg = 4; break;
11594     }
11595     return Visit(E->getArg(Arg));
11596   }
11597 
11598   case Builtin::BI__builtin_isinf_sign: {
11599     APFloat Val(0.0);
11600     return EvaluateFloat(E->getArg(0), Val, Info) &&
11601            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
11602   }
11603 
11604   case Builtin::BI__builtin_isinf: {
11605     APFloat Val(0.0);
11606     return EvaluateFloat(E->getArg(0), Val, Info) &&
11607            Success(Val.isInfinity() ? 1 : 0, E);
11608   }
11609 
11610   case Builtin::BI__builtin_isfinite: {
11611     APFloat Val(0.0);
11612     return EvaluateFloat(E->getArg(0), Val, Info) &&
11613            Success(Val.isFinite() ? 1 : 0, E);
11614   }
11615 
11616   case Builtin::BI__builtin_isnan: {
11617     APFloat Val(0.0);
11618     return EvaluateFloat(E->getArg(0), Val, Info) &&
11619            Success(Val.isNaN() ? 1 : 0, E);
11620   }
11621 
11622   case Builtin::BI__builtin_isnormal: {
11623     APFloat Val(0.0);
11624     return EvaluateFloat(E->getArg(0), Val, Info) &&
11625            Success(Val.isNormal() ? 1 : 0, E);
11626   }
11627 
11628   case Builtin::BI__builtin_parity:
11629   case Builtin::BI__builtin_parityl:
11630   case Builtin::BI__builtin_parityll: {
11631     APSInt Val;
11632     if (!EvaluateInteger(E->getArg(0), Val, Info))
11633       return false;
11634 
11635     return Success(Val.countPopulation() % 2, E);
11636   }
11637 
11638   case Builtin::BI__builtin_popcount:
11639   case Builtin::BI__builtin_popcountl:
11640   case Builtin::BI__builtin_popcountll: {
11641     APSInt Val;
11642     if (!EvaluateInteger(E->getArg(0), Val, Info))
11643       return false;
11644 
11645     return Success(Val.countPopulation(), E);
11646   }
11647 
11648   case Builtin::BI__builtin_rotateleft8:
11649   case Builtin::BI__builtin_rotateleft16:
11650   case Builtin::BI__builtin_rotateleft32:
11651   case Builtin::BI__builtin_rotateleft64:
11652   case Builtin::BI_rotl8: // Microsoft variants of rotate right
11653   case Builtin::BI_rotl16:
11654   case Builtin::BI_rotl:
11655   case Builtin::BI_lrotl:
11656   case Builtin::BI_rotl64: {
11657     APSInt Val, Amt;
11658     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11659         !EvaluateInteger(E->getArg(1), Amt, Info))
11660       return false;
11661 
11662     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
11663   }
11664 
11665   case Builtin::BI__builtin_rotateright8:
11666   case Builtin::BI__builtin_rotateright16:
11667   case Builtin::BI__builtin_rotateright32:
11668   case Builtin::BI__builtin_rotateright64:
11669   case Builtin::BI_rotr8: // Microsoft variants of rotate right
11670   case Builtin::BI_rotr16:
11671   case Builtin::BI_rotr:
11672   case Builtin::BI_lrotr:
11673   case Builtin::BI_rotr64: {
11674     APSInt Val, Amt;
11675     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11676         !EvaluateInteger(E->getArg(1), Amt, Info))
11677       return false;
11678 
11679     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
11680   }
11681 
11682   case Builtin::BIstrlen:
11683   case Builtin::BIwcslen:
11684     // A call to strlen is not a constant expression.
11685     if (Info.getLangOpts().CPlusPlus11)
11686       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11687         << /*isConstexpr*/0 << /*isConstructor*/0
11688         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11689     else
11690       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11691     LLVM_FALLTHROUGH;
11692   case Builtin::BI__builtin_strlen:
11693   case Builtin::BI__builtin_wcslen: {
11694     // As an extension, we support __builtin_strlen() as a constant expression,
11695     // and support folding strlen() to a constant.
11696     LValue String;
11697     if (!EvaluatePointer(E->getArg(0), String, Info))
11698       return false;
11699 
11700     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
11701 
11702     // Fast path: if it's a string literal, search the string value.
11703     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
11704             String.getLValueBase().dyn_cast<const Expr *>())) {
11705       // The string literal may have embedded null characters. Find the first
11706       // one and truncate there.
11707       StringRef Str = S->getBytes();
11708       int64_t Off = String.Offset.getQuantity();
11709       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
11710           S->getCharByteWidth() == 1 &&
11711           // FIXME: Add fast-path for wchar_t too.
11712           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
11713         Str = Str.substr(Off);
11714 
11715         StringRef::size_type Pos = Str.find(0);
11716         if (Pos != StringRef::npos)
11717           Str = Str.substr(0, Pos);
11718 
11719         return Success(Str.size(), E);
11720       }
11721 
11722       // Fall through to slow path to issue appropriate diagnostic.
11723     }
11724 
11725     // Slow path: scan the bytes of the string looking for the terminating 0.
11726     for (uint64_t Strlen = 0; /**/; ++Strlen) {
11727       APValue Char;
11728       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
11729           !Char.isInt())
11730         return false;
11731       if (!Char.getInt())
11732         return Success(Strlen, E);
11733       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
11734         return false;
11735     }
11736   }
11737 
11738   case Builtin::BIstrcmp:
11739   case Builtin::BIwcscmp:
11740   case Builtin::BIstrncmp:
11741   case Builtin::BIwcsncmp:
11742   case Builtin::BImemcmp:
11743   case Builtin::BIbcmp:
11744   case Builtin::BIwmemcmp:
11745     // A call to strlen is not a constant expression.
11746     if (Info.getLangOpts().CPlusPlus11)
11747       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11748         << /*isConstexpr*/0 << /*isConstructor*/0
11749         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11750     else
11751       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11752     LLVM_FALLTHROUGH;
11753   case Builtin::BI__builtin_strcmp:
11754   case Builtin::BI__builtin_wcscmp:
11755   case Builtin::BI__builtin_strncmp:
11756   case Builtin::BI__builtin_wcsncmp:
11757   case Builtin::BI__builtin_memcmp:
11758   case Builtin::BI__builtin_bcmp:
11759   case Builtin::BI__builtin_wmemcmp: {
11760     LValue String1, String2;
11761     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
11762         !EvaluatePointer(E->getArg(1), String2, Info))
11763       return false;
11764 
11765     uint64_t MaxLength = uint64_t(-1);
11766     if (BuiltinOp != Builtin::BIstrcmp &&
11767         BuiltinOp != Builtin::BIwcscmp &&
11768         BuiltinOp != Builtin::BI__builtin_strcmp &&
11769         BuiltinOp != Builtin::BI__builtin_wcscmp) {
11770       APSInt N;
11771       if (!EvaluateInteger(E->getArg(2), N, Info))
11772         return false;
11773       MaxLength = N.getExtValue();
11774     }
11775 
11776     // Empty substrings compare equal by definition.
11777     if (MaxLength == 0u)
11778       return Success(0, E);
11779 
11780     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11781         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11782         String1.Designator.Invalid || String2.Designator.Invalid)
11783       return false;
11784 
11785     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
11786     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
11787 
11788     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
11789                      BuiltinOp == Builtin::BIbcmp ||
11790                      BuiltinOp == Builtin::BI__builtin_memcmp ||
11791                      BuiltinOp == Builtin::BI__builtin_bcmp;
11792 
11793     assert(IsRawByte ||
11794            (Info.Ctx.hasSameUnqualifiedType(
11795                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
11796             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
11797 
11798     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
11799     // 'char8_t', but no other types.
11800     if (IsRawByte &&
11801         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
11802       // FIXME: Consider using our bit_cast implementation to support this.
11803       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
11804           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
11805           << CharTy1 << CharTy2;
11806       return false;
11807     }
11808 
11809     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
11810       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
11811              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
11812              Char1.isInt() && Char2.isInt();
11813     };
11814     const auto &AdvanceElems = [&] {
11815       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
11816              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
11817     };
11818 
11819     bool StopAtNull =
11820         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
11821          BuiltinOp != Builtin::BIwmemcmp &&
11822          BuiltinOp != Builtin::BI__builtin_memcmp &&
11823          BuiltinOp != Builtin::BI__builtin_bcmp &&
11824          BuiltinOp != Builtin::BI__builtin_wmemcmp);
11825     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
11826                   BuiltinOp == Builtin::BIwcsncmp ||
11827                   BuiltinOp == Builtin::BIwmemcmp ||
11828                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
11829                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
11830                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
11831 
11832     for (; MaxLength; --MaxLength) {
11833       APValue Char1, Char2;
11834       if (!ReadCurElems(Char1, Char2))
11835         return false;
11836       if (Char1.getInt().ne(Char2.getInt())) {
11837         if (IsWide) // wmemcmp compares with wchar_t signedness.
11838           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
11839         // memcmp always compares unsigned chars.
11840         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
11841       }
11842       if (StopAtNull && !Char1.getInt())
11843         return Success(0, E);
11844       assert(!(StopAtNull && !Char2.getInt()));
11845       if (!AdvanceElems())
11846         return false;
11847     }
11848     // We hit the strncmp / memcmp limit.
11849     return Success(0, E);
11850   }
11851 
11852   case Builtin::BI__atomic_always_lock_free:
11853   case Builtin::BI__atomic_is_lock_free:
11854   case Builtin::BI__c11_atomic_is_lock_free: {
11855     APSInt SizeVal;
11856     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
11857       return false;
11858 
11859     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
11860     // of two less than or equal to the maximum inline atomic width, we know it
11861     // is lock-free.  If the size isn't a power of two, or greater than the
11862     // maximum alignment where we promote atomics, we know it is not lock-free
11863     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
11864     // the answer can only be determined at runtime; for example, 16-byte
11865     // atomics have lock-free implementations on some, but not all,
11866     // x86-64 processors.
11867 
11868     // Check power-of-two.
11869     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
11870     if (Size.isPowerOfTwo()) {
11871       // Check against inlining width.
11872       unsigned InlineWidthBits =
11873           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
11874       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
11875         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
11876             Size == CharUnits::One() ||
11877             E->getArg(1)->isNullPointerConstant(Info.Ctx,
11878                                                 Expr::NPC_NeverValueDependent))
11879           // OK, we will inline appropriately-aligned operations of this size,
11880           // and _Atomic(T) is appropriately-aligned.
11881           return Success(1, E);
11882 
11883         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
11884           castAs<PointerType>()->getPointeeType();
11885         if (!PointeeType->isIncompleteType() &&
11886             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
11887           // OK, we will inline operations on this object.
11888           return Success(1, E);
11889         }
11890       }
11891     }
11892 
11893     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
11894         Success(0, E) : Error(E);
11895   }
11896   case Builtin::BIomp_is_initial_device:
11897     // We can decide statically which value the runtime would return if called.
11898     return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
11899   case Builtin::BI__builtin_add_overflow:
11900   case Builtin::BI__builtin_sub_overflow:
11901   case Builtin::BI__builtin_mul_overflow:
11902   case Builtin::BI__builtin_sadd_overflow:
11903   case Builtin::BI__builtin_uadd_overflow:
11904   case Builtin::BI__builtin_uaddl_overflow:
11905   case Builtin::BI__builtin_uaddll_overflow:
11906   case Builtin::BI__builtin_usub_overflow:
11907   case Builtin::BI__builtin_usubl_overflow:
11908   case Builtin::BI__builtin_usubll_overflow:
11909   case Builtin::BI__builtin_umul_overflow:
11910   case Builtin::BI__builtin_umull_overflow:
11911   case Builtin::BI__builtin_umulll_overflow:
11912   case Builtin::BI__builtin_saddl_overflow:
11913   case Builtin::BI__builtin_saddll_overflow:
11914   case Builtin::BI__builtin_ssub_overflow:
11915   case Builtin::BI__builtin_ssubl_overflow:
11916   case Builtin::BI__builtin_ssubll_overflow:
11917   case Builtin::BI__builtin_smul_overflow:
11918   case Builtin::BI__builtin_smull_overflow:
11919   case Builtin::BI__builtin_smulll_overflow: {
11920     LValue ResultLValue;
11921     APSInt LHS, RHS;
11922 
11923     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
11924     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
11925         !EvaluateInteger(E->getArg(1), RHS, Info) ||
11926         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
11927       return false;
11928 
11929     APSInt Result;
11930     bool DidOverflow = false;
11931 
11932     // If the types don't have to match, enlarge all 3 to the largest of them.
11933     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11934         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11935         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11936       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
11937                       ResultType->isSignedIntegerOrEnumerationType();
11938       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
11939                       ResultType->isSignedIntegerOrEnumerationType();
11940       uint64_t LHSSize = LHS.getBitWidth();
11941       uint64_t RHSSize = RHS.getBitWidth();
11942       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
11943       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
11944 
11945       // Add an additional bit if the signedness isn't uniformly agreed to. We
11946       // could do this ONLY if there is a signed and an unsigned that both have
11947       // MaxBits, but the code to check that is pretty nasty.  The issue will be
11948       // caught in the shrink-to-result later anyway.
11949       if (IsSigned && !AllSigned)
11950         ++MaxBits;
11951 
11952       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
11953       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
11954       Result = APSInt(MaxBits, !IsSigned);
11955     }
11956 
11957     // Find largest int.
11958     switch (BuiltinOp) {
11959     default:
11960       llvm_unreachable("Invalid value for BuiltinOp");
11961     case Builtin::BI__builtin_add_overflow:
11962     case Builtin::BI__builtin_sadd_overflow:
11963     case Builtin::BI__builtin_saddl_overflow:
11964     case Builtin::BI__builtin_saddll_overflow:
11965     case Builtin::BI__builtin_uadd_overflow:
11966     case Builtin::BI__builtin_uaddl_overflow:
11967     case Builtin::BI__builtin_uaddll_overflow:
11968       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
11969                               : LHS.uadd_ov(RHS, DidOverflow);
11970       break;
11971     case Builtin::BI__builtin_sub_overflow:
11972     case Builtin::BI__builtin_ssub_overflow:
11973     case Builtin::BI__builtin_ssubl_overflow:
11974     case Builtin::BI__builtin_ssubll_overflow:
11975     case Builtin::BI__builtin_usub_overflow:
11976     case Builtin::BI__builtin_usubl_overflow:
11977     case Builtin::BI__builtin_usubll_overflow:
11978       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
11979                               : LHS.usub_ov(RHS, DidOverflow);
11980       break;
11981     case Builtin::BI__builtin_mul_overflow:
11982     case Builtin::BI__builtin_smul_overflow:
11983     case Builtin::BI__builtin_smull_overflow:
11984     case Builtin::BI__builtin_smulll_overflow:
11985     case Builtin::BI__builtin_umul_overflow:
11986     case Builtin::BI__builtin_umull_overflow:
11987     case Builtin::BI__builtin_umulll_overflow:
11988       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
11989                               : LHS.umul_ov(RHS, DidOverflow);
11990       break;
11991     }
11992 
11993     // In the case where multiple sizes are allowed, truncate and see if
11994     // the values are the same.
11995     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
11996         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
11997         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
11998       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
11999       // since it will give us the behavior of a TruncOrSelf in the case where
12000       // its parameter <= its size.  We previously set Result to be at least the
12001       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12002       // will work exactly like TruncOrSelf.
12003       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12004       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12005 
12006       if (!APSInt::isSameValue(Temp, Result))
12007         DidOverflow = true;
12008       Result = Temp;
12009     }
12010 
12011     APValue APV{Result};
12012     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12013       return false;
12014     return Success(DidOverflow, E);
12015   }
12016   }
12017 }
12018 
12019 /// Determine whether this is a pointer past the end of the complete
12020 /// object referred to by the lvalue.
12021 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12022                                             const LValue &LV) {
12023   // A null pointer can be viewed as being "past the end" but we don't
12024   // choose to look at it that way here.
12025   if (!LV.getLValueBase())
12026     return false;
12027 
12028   // If the designator is valid and refers to a subobject, we're not pointing
12029   // past the end.
12030   if (!LV.getLValueDesignator().Invalid &&
12031       !LV.getLValueDesignator().isOnePastTheEnd())
12032     return false;
12033 
12034   // A pointer to an incomplete type might be past-the-end if the type's size is
12035   // zero.  We cannot tell because the type is incomplete.
12036   QualType Ty = getType(LV.getLValueBase());
12037   if (Ty->isIncompleteType())
12038     return true;
12039 
12040   // We're a past-the-end pointer if we point to the byte after the object,
12041   // no matter what our type or path is.
12042   auto Size = Ctx.getTypeSizeInChars(Ty);
12043   return LV.getLValueOffset() == Size;
12044 }
12045 
12046 namespace {
12047 
12048 /// Data recursive integer evaluator of certain binary operators.
12049 ///
12050 /// We use a data recursive algorithm for binary operators so that we are able
12051 /// to handle extreme cases of chained binary operators without causing stack
12052 /// overflow.
12053 class DataRecursiveIntBinOpEvaluator {
12054   struct EvalResult {
12055     APValue Val;
12056     bool Failed;
12057 
12058     EvalResult() : Failed(false) { }
12059 
12060     void swap(EvalResult &RHS) {
12061       Val.swap(RHS.Val);
12062       Failed = RHS.Failed;
12063       RHS.Failed = false;
12064     }
12065   };
12066 
12067   struct Job {
12068     const Expr *E;
12069     EvalResult LHSResult; // meaningful only for binary operator expression.
12070     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12071 
12072     Job() = default;
12073     Job(Job &&) = default;
12074 
12075     void startSpeculativeEval(EvalInfo &Info) {
12076       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12077     }
12078 
12079   private:
12080     SpeculativeEvaluationRAII SpecEvalRAII;
12081   };
12082 
12083   SmallVector<Job, 16> Queue;
12084 
12085   IntExprEvaluator &IntEval;
12086   EvalInfo &Info;
12087   APValue &FinalResult;
12088 
12089 public:
12090   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12091     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12092 
12093   /// True if \param E is a binary operator that we are going to handle
12094   /// data recursively.
12095   /// We handle binary operators that are comma, logical, or that have operands
12096   /// with integral or enumeration type.
12097   static bool shouldEnqueue(const BinaryOperator *E) {
12098     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12099            (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
12100             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12101             E->getRHS()->getType()->isIntegralOrEnumerationType());
12102   }
12103 
12104   bool Traverse(const BinaryOperator *E) {
12105     enqueue(E);
12106     EvalResult PrevResult;
12107     while (!Queue.empty())
12108       process(PrevResult);
12109 
12110     if (PrevResult.Failed) return false;
12111 
12112     FinalResult.swap(PrevResult.Val);
12113     return true;
12114   }
12115 
12116 private:
12117   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12118     return IntEval.Success(Value, E, Result);
12119   }
12120   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12121     return IntEval.Success(Value, E, Result);
12122   }
12123   bool Error(const Expr *E) {
12124     return IntEval.Error(E);
12125   }
12126   bool Error(const Expr *E, diag::kind D) {
12127     return IntEval.Error(E, D);
12128   }
12129 
12130   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12131     return Info.CCEDiag(E, D);
12132   }
12133 
12134   // Returns true if visiting the RHS is necessary, false otherwise.
12135   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12136                          bool &SuppressRHSDiags);
12137 
12138   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12139                   const BinaryOperator *E, APValue &Result);
12140 
12141   void EvaluateExpr(const Expr *E, EvalResult &Result) {
12142     Result.Failed = !Evaluate(Result.Val, Info, E);
12143     if (Result.Failed)
12144       Result.Val = APValue();
12145   }
12146 
12147   void process(EvalResult &Result);
12148 
12149   void enqueue(const Expr *E) {
12150     E = E->IgnoreParens();
12151     Queue.resize(Queue.size()+1);
12152     Queue.back().E = E;
12153     Queue.back().Kind = Job::AnyExprKind;
12154   }
12155 };
12156 
12157 }
12158 
12159 bool DataRecursiveIntBinOpEvaluator::
12160        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12161                          bool &SuppressRHSDiags) {
12162   if (E->getOpcode() == BO_Comma) {
12163     // Ignore LHS but note if we could not evaluate it.
12164     if (LHSResult.Failed)
12165       return Info.noteSideEffect();
12166     return true;
12167   }
12168 
12169   if (E->isLogicalOp()) {
12170     bool LHSAsBool;
12171     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12172       // We were able to evaluate the LHS, see if we can get away with not
12173       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12174       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12175         Success(LHSAsBool, E, LHSResult.Val);
12176         return false; // Ignore RHS
12177       }
12178     } else {
12179       LHSResult.Failed = true;
12180 
12181       // Since we weren't able to evaluate the left hand side, it
12182       // might have had side effects.
12183       if (!Info.noteSideEffect())
12184         return false;
12185 
12186       // We can't evaluate the LHS; however, sometimes the result
12187       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12188       // Don't ignore RHS and suppress diagnostics from this arm.
12189       SuppressRHSDiags = true;
12190     }
12191 
12192     return true;
12193   }
12194 
12195   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12196          E->getRHS()->getType()->isIntegralOrEnumerationType());
12197 
12198   if (LHSResult.Failed && !Info.noteFailure())
12199     return false; // Ignore RHS;
12200 
12201   return true;
12202 }
12203 
12204 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12205                                     bool IsSub) {
12206   // Compute the new offset in the appropriate width, wrapping at 64 bits.
12207   // FIXME: When compiling for a 32-bit target, we should use 32-bit
12208   // offsets.
12209   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12210   CharUnits &Offset = LVal.getLValueOffset();
12211   uint64_t Offset64 = Offset.getQuantity();
12212   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12213   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12214                                          : Offset64 + Index64);
12215 }
12216 
12217 bool DataRecursiveIntBinOpEvaluator::
12218        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12219                   const BinaryOperator *E, APValue &Result) {
12220   if (E->getOpcode() == BO_Comma) {
12221     if (RHSResult.Failed)
12222       return false;
12223     Result = RHSResult.Val;
12224     return true;
12225   }
12226 
12227   if (E->isLogicalOp()) {
12228     bool lhsResult, rhsResult;
12229     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12230     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12231 
12232     if (LHSIsOK) {
12233       if (RHSIsOK) {
12234         if (E->getOpcode() == BO_LOr)
12235           return Success(lhsResult || rhsResult, E, Result);
12236         else
12237           return Success(lhsResult && rhsResult, E, Result);
12238       }
12239     } else {
12240       if (RHSIsOK) {
12241         // We can't evaluate the LHS; however, sometimes the result
12242         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12243         if (rhsResult == (E->getOpcode() == BO_LOr))
12244           return Success(rhsResult, E, Result);
12245       }
12246     }
12247 
12248     return false;
12249   }
12250 
12251   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12252          E->getRHS()->getType()->isIntegralOrEnumerationType());
12253 
12254   if (LHSResult.Failed || RHSResult.Failed)
12255     return false;
12256 
12257   const APValue &LHSVal = LHSResult.Val;
12258   const APValue &RHSVal = RHSResult.Val;
12259 
12260   // Handle cases like (unsigned long)&a + 4.
12261   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12262     Result = LHSVal;
12263     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12264     return true;
12265   }
12266 
12267   // Handle cases like 4 + (unsigned long)&a
12268   if (E->getOpcode() == BO_Add &&
12269       RHSVal.isLValue() && LHSVal.isInt()) {
12270     Result = RHSVal;
12271     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12272     return true;
12273   }
12274 
12275   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12276     // Handle (intptr_t)&&A - (intptr_t)&&B.
12277     if (!LHSVal.getLValueOffset().isZero() ||
12278         !RHSVal.getLValueOffset().isZero())
12279       return false;
12280     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12281     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12282     if (!LHSExpr || !RHSExpr)
12283       return false;
12284     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12285     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12286     if (!LHSAddrExpr || !RHSAddrExpr)
12287       return false;
12288     // Make sure both labels come from the same function.
12289     if (LHSAddrExpr->getLabel()->getDeclContext() !=
12290         RHSAddrExpr->getLabel()->getDeclContext())
12291       return false;
12292     Result = APValue(LHSAddrExpr, RHSAddrExpr);
12293     return true;
12294   }
12295 
12296   // All the remaining cases expect both operands to be an integer
12297   if (!LHSVal.isInt() || !RHSVal.isInt())
12298     return Error(E);
12299 
12300   // Set up the width and signedness manually, in case it can't be deduced
12301   // from the operation we're performing.
12302   // FIXME: Don't do this in the cases where we can deduce it.
12303   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12304                E->getType()->isUnsignedIntegerOrEnumerationType());
12305   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12306                          RHSVal.getInt(), Value))
12307     return false;
12308   return Success(Value, E, Result);
12309 }
12310 
12311 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12312   Job &job = Queue.back();
12313 
12314   switch (job.Kind) {
12315     case Job::AnyExprKind: {
12316       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12317         if (shouldEnqueue(Bop)) {
12318           job.Kind = Job::BinOpKind;
12319           enqueue(Bop->getLHS());
12320           return;
12321         }
12322       }
12323 
12324       EvaluateExpr(job.E, Result);
12325       Queue.pop_back();
12326       return;
12327     }
12328 
12329     case Job::BinOpKind: {
12330       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12331       bool SuppressRHSDiags = false;
12332       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12333         Queue.pop_back();
12334         return;
12335       }
12336       if (SuppressRHSDiags)
12337         job.startSpeculativeEval(Info);
12338       job.LHSResult.swap(Result);
12339       job.Kind = Job::BinOpVisitedLHSKind;
12340       enqueue(Bop->getRHS());
12341       return;
12342     }
12343 
12344     case Job::BinOpVisitedLHSKind: {
12345       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12346       EvalResult RHS;
12347       RHS.swap(Result);
12348       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12349       Queue.pop_back();
12350       return;
12351     }
12352   }
12353 
12354   llvm_unreachable("Invalid Job::Kind!");
12355 }
12356 
12357 namespace {
12358 /// Used when we determine that we should fail, but can keep evaluating prior to
12359 /// noting that we had a failure.
12360 class DelayedNoteFailureRAII {
12361   EvalInfo &Info;
12362   bool NoteFailure;
12363 
12364 public:
12365   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
12366       : Info(Info), NoteFailure(NoteFailure) {}
12367   ~DelayedNoteFailureRAII() {
12368     if (NoteFailure) {
12369       bool ContinueAfterFailure = Info.noteFailure();
12370       (void)ContinueAfterFailure;
12371       assert(ContinueAfterFailure &&
12372              "Shouldn't have kept evaluating on failure.");
12373     }
12374   }
12375 };
12376 
12377 enum class CmpResult {
12378   Unequal,
12379   Less,
12380   Equal,
12381   Greater,
12382   Unordered,
12383 };
12384 }
12385 
12386 template <class SuccessCB, class AfterCB>
12387 static bool
12388 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12389                                  SuccessCB &&Success, AfterCB &&DoAfter) {
12390   assert(E->isComparisonOp() && "expected comparison operator");
12391   assert((E->getOpcode() == BO_Cmp ||
12392           E->getType()->isIntegralOrEnumerationType()) &&
12393          "unsupported binary expression evaluation");
12394   auto Error = [&](const Expr *E) {
12395     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12396     return false;
12397   };
12398 
12399   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12400   bool IsEquality = E->isEqualityOp();
12401 
12402   QualType LHSTy = E->getLHS()->getType();
12403   QualType RHSTy = E->getRHS()->getType();
12404 
12405   if (LHSTy->isIntegralOrEnumerationType() &&
12406       RHSTy->isIntegralOrEnumerationType()) {
12407     APSInt LHS, RHS;
12408     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12409     if (!LHSOK && !Info.noteFailure())
12410       return false;
12411     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12412       return false;
12413     if (LHS < RHS)
12414       return Success(CmpResult::Less, E);
12415     if (LHS > RHS)
12416       return Success(CmpResult::Greater, E);
12417     return Success(CmpResult::Equal, E);
12418   }
12419 
12420   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12421     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12422     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12423 
12424     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12425     if (!LHSOK && !Info.noteFailure())
12426       return false;
12427     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12428       return false;
12429     if (LHSFX < RHSFX)
12430       return Success(CmpResult::Less, E);
12431     if (LHSFX > RHSFX)
12432       return Success(CmpResult::Greater, E);
12433     return Success(CmpResult::Equal, E);
12434   }
12435 
12436   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12437     ComplexValue LHS, RHS;
12438     bool LHSOK;
12439     if (E->isAssignmentOp()) {
12440       LValue LV;
12441       EvaluateLValue(E->getLHS(), LV, Info);
12442       LHSOK = false;
12443     } else if (LHSTy->isRealFloatingType()) {
12444       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12445       if (LHSOK) {
12446         LHS.makeComplexFloat();
12447         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12448       }
12449     } else {
12450       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12451     }
12452     if (!LHSOK && !Info.noteFailure())
12453       return false;
12454 
12455     if (E->getRHS()->getType()->isRealFloatingType()) {
12456       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12457         return false;
12458       RHS.makeComplexFloat();
12459       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12460     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12461       return false;
12462 
12463     if (LHS.isComplexFloat()) {
12464       APFloat::cmpResult CR_r =
12465         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12466       APFloat::cmpResult CR_i =
12467         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12468       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12469       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12470     } else {
12471       assert(IsEquality && "invalid complex comparison");
12472       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12473                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
12474       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12475     }
12476   }
12477 
12478   if (LHSTy->isRealFloatingType() &&
12479       RHSTy->isRealFloatingType()) {
12480     APFloat RHS(0.0), LHS(0.0);
12481 
12482     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12483     if (!LHSOK && !Info.noteFailure())
12484       return false;
12485 
12486     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12487       return false;
12488 
12489     assert(E->isComparisonOp() && "Invalid binary operator!");
12490     auto GetCmpRes = [&]() {
12491       switch (LHS.compare(RHS)) {
12492       case APFloat::cmpEqual:
12493         return CmpResult::Equal;
12494       case APFloat::cmpLessThan:
12495         return CmpResult::Less;
12496       case APFloat::cmpGreaterThan:
12497         return CmpResult::Greater;
12498       case APFloat::cmpUnordered:
12499         return CmpResult::Unordered;
12500       }
12501       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12502     };
12503     return Success(GetCmpRes(), E);
12504   }
12505 
12506   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12507     LValue LHSValue, RHSValue;
12508 
12509     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12510     if (!LHSOK && !Info.noteFailure())
12511       return false;
12512 
12513     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12514       return false;
12515 
12516     // Reject differing bases from the normal codepath; we special-case
12517     // comparisons to null.
12518     if (!HasSameBase(LHSValue, RHSValue)) {
12519       // Inequalities and subtractions between unrelated pointers have
12520       // unspecified or undefined behavior.
12521       if (!IsEquality) {
12522         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
12523         return false;
12524       }
12525       // A constant address may compare equal to the address of a symbol.
12526       // The one exception is that address of an object cannot compare equal
12527       // to a null pointer constant.
12528       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12529           (!RHSValue.Base && !RHSValue.Offset.isZero()))
12530         return Error(E);
12531       // It's implementation-defined whether distinct literals will have
12532       // distinct addresses. In clang, the result of such a comparison is
12533       // unspecified, so it is not a constant expression. However, we do know
12534       // that the address of a literal will be non-null.
12535       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12536           LHSValue.Base && RHSValue.Base)
12537         return Error(E);
12538       // We can't tell whether weak symbols will end up pointing to the same
12539       // object.
12540       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12541         return Error(E);
12542       // We can't compare the address of the start of one object with the
12543       // past-the-end address of another object, per C++ DR1652.
12544       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
12545            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
12546           (RHSValue.Base && RHSValue.Offset.isZero() &&
12547            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
12548         return Error(E);
12549       // We can't tell whether an object is at the same address as another
12550       // zero sized object.
12551       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12552           (LHSValue.Base && isZeroSized(RHSValue)))
12553         return Error(E);
12554       return Success(CmpResult::Unequal, E);
12555     }
12556 
12557     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12558     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12559 
12560     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12561     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12562 
12563     // C++11 [expr.rel]p3:
12564     //   Pointers to void (after pointer conversions) can be compared, with a
12565     //   result defined as follows: If both pointers represent the same
12566     //   address or are both the null pointer value, the result is true if the
12567     //   operator is <= or >= and false otherwise; otherwise the result is
12568     //   unspecified.
12569     // We interpret this as applying to pointers to *cv* void.
12570     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
12571       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
12572 
12573     // C++11 [expr.rel]p2:
12574     // - If two pointers point to non-static data members of the same object,
12575     //   or to subobjects or array elements fo such members, recursively, the
12576     //   pointer to the later declared member compares greater provided the
12577     //   two members have the same access control and provided their class is
12578     //   not a union.
12579     //   [...]
12580     // - Otherwise pointer comparisons are unspecified.
12581     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
12582       bool WasArrayIndex;
12583       unsigned Mismatch = FindDesignatorMismatch(
12584           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
12585       // At the point where the designators diverge, the comparison has a
12586       // specified value if:
12587       //  - we are comparing array indices
12588       //  - we are comparing fields of a union, or fields with the same access
12589       // Otherwise, the result is unspecified and thus the comparison is not a
12590       // constant expression.
12591       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
12592           Mismatch < RHSDesignator.Entries.size()) {
12593         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
12594         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
12595         if (!LF && !RF)
12596           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
12597         else if (!LF)
12598           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12599               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
12600               << RF->getParent() << RF;
12601         else if (!RF)
12602           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12603               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
12604               << LF->getParent() << LF;
12605         else if (!LF->getParent()->isUnion() &&
12606                  LF->getAccess() != RF->getAccess())
12607           Info.CCEDiag(E,
12608                        diag::note_constexpr_pointer_comparison_differing_access)
12609               << LF << LF->getAccess() << RF << RF->getAccess()
12610               << LF->getParent();
12611       }
12612     }
12613 
12614     // The comparison here must be unsigned, and performed with the same
12615     // width as the pointer.
12616     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
12617     uint64_t CompareLHS = LHSOffset.getQuantity();
12618     uint64_t CompareRHS = RHSOffset.getQuantity();
12619     assert(PtrSize <= 64 && "Unexpected pointer width");
12620     uint64_t Mask = ~0ULL >> (64 - PtrSize);
12621     CompareLHS &= Mask;
12622     CompareRHS &= Mask;
12623 
12624     // If there is a base and this is a relational operator, we can only
12625     // compare pointers within the object in question; otherwise, the result
12626     // depends on where the object is located in memory.
12627     if (!LHSValue.Base.isNull() && IsRelational) {
12628       QualType BaseTy = getType(LHSValue.Base);
12629       if (BaseTy->isIncompleteType())
12630         return Error(E);
12631       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
12632       uint64_t OffsetLimit = Size.getQuantity();
12633       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
12634         return Error(E);
12635     }
12636 
12637     if (CompareLHS < CompareRHS)
12638       return Success(CmpResult::Less, E);
12639     if (CompareLHS > CompareRHS)
12640       return Success(CmpResult::Greater, E);
12641     return Success(CmpResult::Equal, E);
12642   }
12643 
12644   if (LHSTy->isMemberPointerType()) {
12645     assert(IsEquality && "unexpected member pointer operation");
12646     assert(RHSTy->isMemberPointerType() && "invalid comparison");
12647 
12648     MemberPtr LHSValue, RHSValue;
12649 
12650     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
12651     if (!LHSOK && !Info.noteFailure())
12652       return false;
12653 
12654     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12655       return false;
12656 
12657     // C++11 [expr.eq]p2:
12658     //   If both operands are null, they compare equal. Otherwise if only one is
12659     //   null, they compare unequal.
12660     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
12661       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
12662       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12663     }
12664 
12665     //   Otherwise if either is a pointer to a virtual member function, the
12666     //   result is unspecified.
12667     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
12668       if (MD->isVirtual())
12669         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12670     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
12671       if (MD->isVirtual())
12672         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12673 
12674     //   Otherwise they compare equal if and only if they would refer to the
12675     //   same member of the same most derived object or the same subobject if
12676     //   they were dereferenced with a hypothetical object of the associated
12677     //   class type.
12678     bool Equal = LHSValue == RHSValue;
12679     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12680   }
12681 
12682   if (LHSTy->isNullPtrType()) {
12683     assert(E->isComparisonOp() && "unexpected nullptr operation");
12684     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12685     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12686     // are compared, the result is true of the operator is <=, >= or ==, and
12687     // false otherwise.
12688     return Success(CmpResult::Equal, E);
12689   }
12690 
12691   return DoAfter();
12692 }
12693 
12694 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
12695   if (!CheckLiteralType(Info, E))
12696     return false;
12697 
12698   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12699     ComparisonCategoryResult CCR;
12700     switch (CR) {
12701     case CmpResult::Unequal:
12702       llvm_unreachable("should never produce Unequal for three-way comparison");
12703     case CmpResult::Less:
12704       CCR = ComparisonCategoryResult::Less;
12705       break;
12706     case CmpResult::Equal:
12707       CCR = ComparisonCategoryResult::Equal;
12708       break;
12709     case CmpResult::Greater:
12710       CCR = ComparisonCategoryResult::Greater;
12711       break;
12712     case CmpResult::Unordered:
12713       CCR = ComparisonCategoryResult::Unordered;
12714       break;
12715     }
12716     // Evaluation succeeded. Lookup the information for the comparison category
12717     // type and fetch the VarDecl for the result.
12718     const ComparisonCategoryInfo &CmpInfo =
12719         Info.Ctx.CompCategories.getInfoForType(E->getType());
12720     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
12721     // Check and evaluate the result as a constant expression.
12722     LValue LV;
12723     LV.set(VD);
12724     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12725       return false;
12726     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
12727   };
12728   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12729     return ExprEvaluatorBaseTy::VisitBinCmp(E);
12730   });
12731 }
12732 
12733 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12734   // We don't call noteFailure immediately because the assignment happens after
12735   // we evaluate LHS and RHS.
12736   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
12737     return Error(E);
12738 
12739   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
12740   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
12741     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
12742 
12743   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
12744           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
12745          "DataRecursiveIntBinOpEvaluator should have handled integral types");
12746 
12747   if (E->isComparisonOp()) {
12748     // Evaluate builtin binary comparisons by evaluating them as three-way
12749     // comparisons and then translating the result.
12750     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12751       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
12752              "should only produce Unequal for equality comparisons");
12753       bool IsEqual   = CR == CmpResult::Equal,
12754            IsLess    = CR == CmpResult::Less,
12755            IsGreater = CR == CmpResult::Greater;
12756       auto Op = E->getOpcode();
12757       switch (Op) {
12758       default:
12759         llvm_unreachable("unsupported binary operator");
12760       case BO_EQ:
12761       case BO_NE:
12762         return Success(IsEqual == (Op == BO_EQ), E);
12763       case BO_LT:
12764         return Success(IsLess, E);
12765       case BO_GT:
12766         return Success(IsGreater, E);
12767       case BO_LE:
12768         return Success(IsEqual || IsLess, E);
12769       case BO_GE:
12770         return Success(IsEqual || IsGreater, E);
12771       }
12772     };
12773     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12774       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12775     });
12776   }
12777 
12778   QualType LHSTy = E->getLHS()->getType();
12779   QualType RHSTy = E->getRHS()->getType();
12780 
12781   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
12782       E->getOpcode() == BO_Sub) {
12783     LValue LHSValue, RHSValue;
12784 
12785     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12786     if (!LHSOK && !Info.noteFailure())
12787       return false;
12788 
12789     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12790       return false;
12791 
12792     // Reject differing bases from the normal codepath; we special-case
12793     // comparisons to null.
12794     if (!HasSameBase(LHSValue, RHSValue)) {
12795       // Handle &&A - &&B.
12796       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
12797         return Error(E);
12798       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
12799       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
12800       if (!LHSExpr || !RHSExpr)
12801         return Error(E);
12802       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12803       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12804       if (!LHSAddrExpr || !RHSAddrExpr)
12805         return Error(E);
12806       // Make sure both labels come from the same function.
12807       if (LHSAddrExpr->getLabel()->getDeclContext() !=
12808           RHSAddrExpr->getLabel()->getDeclContext())
12809         return Error(E);
12810       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
12811     }
12812     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12813     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12814 
12815     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12816     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12817 
12818     // C++11 [expr.add]p6:
12819     //   Unless both pointers point to elements of the same array object, or
12820     //   one past the last element of the array object, the behavior is
12821     //   undefined.
12822     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
12823         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
12824                                 RHSDesignator))
12825       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
12826 
12827     QualType Type = E->getLHS()->getType();
12828     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
12829 
12830     CharUnits ElementSize;
12831     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
12832       return false;
12833 
12834     // As an extension, a type may have zero size (empty struct or union in
12835     // C, array of zero length). Pointer subtraction in such cases has
12836     // undefined behavior, so is not constant.
12837     if (ElementSize.isZero()) {
12838       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
12839           << ElementType;
12840       return false;
12841     }
12842 
12843     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
12844     // and produce incorrect results when it overflows. Such behavior
12845     // appears to be non-conforming, but is common, so perhaps we should
12846     // assume the standard intended for such cases to be undefined behavior
12847     // and check for them.
12848 
12849     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
12850     // overflow in the final conversion to ptrdiff_t.
12851     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
12852     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
12853     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
12854                     false);
12855     APSInt TrueResult = (LHS - RHS) / ElemSize;
12856     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
12857 
12858     if (Result.extend(65) != TrueResult &&
12859         !HandleOverflow(Info, E, TrueResult, E->getType()))
12860       return false;
12861     return Success(Result, E);
12862   }
12863 
12864   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12865 }
12866 
12867 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
12868 /// a result as the expression's type.
12869 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
12870                                     const UnaryExprOrTypeTraitExpr *E) {
12871   switch(E->getKind()) {
12872   case UETT_PreferredAlignOf:
12873   case UETT_AlignOf: {
12874     if (E->isArgumentType())
12875       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
12876                      E);
12877     else
12878       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
12879                      E);
12880   }
12881 
12882   case UETT_VecStep: {
12883     QualType Ty = E->getTypeOfArgument();
12884 
12885     if (Ty->isVectorType()) {
12886       unsigned n = Ty->castAs<VectorType>()->getNumElements();
12887 
12888       // The vec_step built-in functions that take a 3-component
12889       // vector return 4. (OpenCL 1.1 spec 6.11.12)
12890       if (n == 3)
12891         n = 4;
12892 
12893       return Success(n, E);
12894     } else
12895       return Success(1, E);
12896   }
12897 
12898   case UETT_SizeOf: {
12899     QualType SrcTy = E->getTypeOfArgument();
12900     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
12901     //   the result is the size of the referenced type."
12902     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
12903       SrcTy = Ref->getPointeeType();
12904 
12905     CharUnits Sizeof;
12906     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
12907       return false;
12908     return Success(Sizeof, E);
12909   }
12910   case UETT_OpenMPRequiredSimdAlign:
12911     assert(E->isArgumentType());
12912     return Success(
12913         Info.Ctx.toCharUnitsFromBits(
12914                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
12915             .getQuantity(),
12916         E);
12917   }
12918 
12919   llvm_unreachable("unknown expr/type trait");
12920 }
12921 
12922 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
12923   CharUnits Result;
12924   unsigned n = OOE->getNumComponents();
12925   if (n == 0)
12926     return Error(OOE);
12927   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
12928   for (unsigned i = 0; i != n; ++i) {
12929     OffsetOfNode ON = OOE->getComponent(i);
12930     switch (ON.getKind()) {
12931     case OffsetOfNode::Array: {
12932       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
12933       APSInt IdxResult;
12934       if (!EvaluateInteger(Idx, IdxResult, Info))
12935         return false;
12936       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
12937       if (!AT)
12938         return Error(OOE);
12939       CurrentType = AT->getElementType();
12940       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
12941       Result += IdxResult.getSExtValue() * ElementSize;
12942       break;
12943     }
12944 
12945     case OffsetOfNode::Field: {
12946       FieldDecl *MemberDecl = ON.getField();
12947       const RecordType *RT = CurrentType->getAs<RecordType>();
12948       if (!RT)
12949         return Error(OOE);
12950       RecordDecl *RD = RT->getDecl();
12951       if (RD->isInvalidDecl()) return false;
12952       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
12953       unsigned i = MemberDecl->getFieldIndex();
12954       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
12955       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
12956       CurrentType = MemberDecl->getType().getNonReferenceType();
12957       break;
12958     }
12959 
12960     case OffsetOfNode::Identifier:
12961       llvm_unreachable("dependent __builtin_offsetof");
12962 
12963     case OffsetOfNode::Base: {
12964       CXXBaseSpecifier *BaseSpec = ON.getBase();
12965       if (BaseSpec->isVirtual())
12966         return Error(OOE);
12967 
12968       // Find the layout of the class whose base we are looking into.
12969       const RecordType *RT = CurrentType->getAs<RecordType>();
12970       if (!RT)
12971         return Error(OOE);
12972       RecordDecl *RD = RT->getDecl();
12973       if (RD->isInvalidDecl()) return false;
12974       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
12975 
12976       // Find the base class itself.
12977       CurrentType = BaseSpec->getType();
12978       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
12979       if (!BaseRT)
12980         return Error(OOE);
12981 
12982       // Add the offset to the base.
12983       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
12984       break;
12985     }
12986     }
12987   }
12988   return Success(Result, OOE);
12989 }
12990 
12991 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12992   switch (E->getOpcode()) {
12993   default:
12994     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
12995     // See C99 6.6p3.
12996     return Error(E);
12997   case UO_Extension:
12998     // FIXME: Should extension allow i-c-e extension expressions in its scope?
12999     // If so, we could clear the diagnostic ID.
13000     return Visit(E->getSubExpr());
13001   case UO_Plus:
13002     // The result is just the value.
13003     return Visit(E->getSubExpr());
13004   case UO_Minus: {
13005     if (!Visit(E->getSubExpr()))
13006       return false;
13007     if (!Result.isInt()) return Error(E);
13008     const APSInt &Value = Result.getInt();
13009     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
13010         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13011                         E->getType()))
13012       return false;
13013     return Success(-Value, E);
13014   }
13015   case UO_Not: {
13016     if (!Visit(E->getSubExpr()))
13017       return false;
13018     if (!Result.isInt()) return Error(E);
13019     return Success(~Result.getInt(), E);
13020   }
13021   case UO_LNot: {
13022     bool bres;
13023     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13024       return false;
13025     return Success(!bres, E);
13026   }
13027   }
13028 }
13029 
13030 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13031 /// result type is integer.
13032 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13033   const Expr *SubExpr = E->getSubExpr();
13034   QualType DestType = E->getType();
13035   QualType SrcType = SubExpr->getType();
13036 
13037   switch (E->getCastKind()) {
13038   case CK_BaseToDerived:
13039   case CK_DerivedToBase:
13040   case CK_UncheckedDerivedToBase:
13041   case CK_Dynamic:
13042   case CK_ToUnion:
13043   case CK_ArrayToPointerDecay:
13044   case CK_FunctionToPointerDecay:
13045   case CK_NullToPointer:
13046   case CK_NullToMemberPointer:
13047   case CK_BaseToDerivedMemberPointer:
13048   case CK_DerivedToBaseMemberPointer:
13049   case CK_ReinterpretMemberPointer:
13050   case CK_ConstructorConversion:
13051   case CK_IntegralToPointer:
13052   case CK_ToVoid:
13053   case CK_VectorSplat:
13054   case CK_IntegralToFloating:
13055   case CK_FloatingCast:
13056   case CK_CPointerToObjCPointerCast:
13057   case CK_BlockPointerToObjCPointerCast:
13058   case CK_AnyPointerToBlockPointerCast:
13059   case CK_ObjCObjectLValueCast:
13060   case CK_FloatingRealToComplex:
13061   case CK_FloatingComplexToReal:
13062   case CK_FloatingComplexCast:
13063   case CK_FloatingComplexToIntegralComplex:
13064   case CK_IntegralRealToComplex:
13065   case CK_IntegralComplexCast:
13066   case CK_IntegralComplexToFloatingComplex:
13067   case CK_BuiltinFnToFnPtr:
13068   case CK_ZeroToOCLOpaqueType:
13069   case CK_NonAtomicToAtomic:
13070   case CK_AddressSpaceConversion:
13071   case CK_IntToOCLSampler:
13072   case CK_FloatingToFixedPoint:
13073   case CK_FixedPointToFloating:
13074   case CK_FixedPointCast:
13075   case CK_IntegralToFixedPoint:
13076     llvm_unreachable("invalid cast kind for integral value");
13077 
13078   case CK_BitCast:
13079   case CK_Dependent:
13080   case CK_LValueBitCast:
13081   case CK_ARCProduceObject:
13082   case CK_ARCConsumeObject:
13083   case CK_ARCReclaimReturnedObject:
13084   case CK_ARCExtendBlockObject:
13085   case CK_CopyAndAutoreleaseBlockObject:
13086     return Error(E);
13087 
13088   case CK_UserDefinedConversion:
13089   case CK_LValueToRValue:
13090   case CK_AtomicToNonAtomic:
13091   case CK_NoOp:
13092   case CK_LValueToRValueBitCast:
13093     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13094 
13095   case CK_MemberPointerToBoolean:
13096   case CK_PointerToBoolean:
13097   case CK_IntegralToBoolean:
13098   case CK_FloatingToBoolean:
13099   case CK_BooleanToSignedIntegral:
13100   case CK_FloatingComplexToBoolean:
13101   case CK_IntegralComplexToBoolean: {
13102     bool BoolResult;
13103     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13104       return false;
13105     uint64_t IntResult = BoolResult;
13106     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13107       IntResult = (uint64_t)-1;
13108     return Success(IntResult, E);
13109   }
13110 
13111   case CK_FixedPointToIntegral: {
13112     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13113     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13114       return false;
13115     bool Overflowed;
13116     llvm::APSInt Result = Src.convertToInt(
13117         Info.Ctx.getIntWidth(DestType),
13118         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13119     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13120       return false;
13121     return Success(Result, E);
13122   }
13123 
13124   case CK_FixedPointToBoolean: {
13125     // Unsigned padding does not affect this.
13126     APValue Val;
13127     if (!Evaluate(Val, Info, SubExpr))
13128       return false;
13129     return Success(Val.getFixedPoint().getBoolValue(), E);
13130   }
13131 
13132   case CK_IntegralCast: {
13133     if (!Visit(SubExpr))
13134       return false;
13135 
13136     if (!Result.isInt()) {
13137       // Allow casts of address-of-label differences if they are no-ops
13138       // or narrowing.  (The narrowing case isn't actually guaranteed to
13139       // be constant-evaluatable except in some narrow cases which are hard
13140       // to detect here.  We let it through on the assumption the user knows
13141       // what they are doing.)
13142       if (Result.isAddrLabelDiff())
13143         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13144       // Only allow casts of lvalues if they are lossless.
13145       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13146     }
13147 
13148     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13149                                       Result.getInt()), E);
13150   }
13151 
13152   case CK_PointerToIntegral: {
13153     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
13154 
13155     LValue LV;
13156     if (!EvaluatePointer(SubExpr, LV, Info))
13157       return false;
13158 
13159     if (LV.getLValueBase()) {
13160       // Only allow based lvalue casts if they are lossless.
13161       // FIXME: Allow a larger integer size than the pointer size, and allow
13162       // narrowing back down to pointer width in subsequent integral casts.
13163       // FIXME: Check integer type's active bits, not its type size.
13164       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13165         return Error(E);
13166 
13167       LV.Designator.setInvalid();
13168       LV.moveInto(Result);
13169       return true;
13170     }
13171 
13172     APSInt AsInt;
13173     APValue V;
13174     LV.moveInto(V);
13175     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13176       llvm_unreachable("Can't cast this!");
13177 
13178     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13179   }
13180 
13181   case CK_IntegralComplexToReal: {
13182     ComplexValue C;
13183     if (!EvaluateComplex(SubExpr, C, Info))
13184       return false;
13185     return Success(C.getComplexIntReal(), E);
13186   }
13187 
13188   case CK_FloatingToIntegral: {
13189     APFloat F(0.0);
13190     if (!EvaluateFloat(SubExpr, F, Info))
13191       return false;
13192 
13193     APSInt Value;
13194     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13195       return false;
13196     return Success(Value, E);
13197   }
13198   }
13199 
13200   llvm_unreachable("unknown cast resulting in integral value");
13201 }
13202 
13203 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13204   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13205     ComplexValue LV;
13206     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13207       return false;
13208     if (!LV.isComplexInt())
13209       return Error(E);
13210     return Success(LV.getComplexIntReal(), E);
13211   }
13212 
13213   return Visit(E->getSubExpr());
13214 }
13215 
13216 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13217   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13218     ComplexValue LV;
13219     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13220       return false;
13221     if (!LV.isComplexInt())
13222       return Error(E);
13223     return Success(LV.getComplexIntImag(), E);
13224   }
13225 
13226   VisitIgnoredValue(E->getSubExpr());
13227   return Success(0, E);
13228 }
13229 
13230 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13231   return Success(E->getPackLength(), E);
13232 }
13233 
13234 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13235   return Success(E->getValue(), E);
13236 }
13237 
13238 bool IntExprEvaluator::VisitConceptSpecializationExpr(
13239        const ConceptSpecializationExpr *E) {
13240   return Success(E->isSatisfied(), E);
13241 }
13242 
13243 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13244   return Success(E->isSatisfied(), E);
13245 }
13246 
13247 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13248   switch (E->getOpcode()) {
13249     default:
13250       // Invalid unary operators
13251       return Error(E);
13252     case UO_Plus:
13253       // The result is just the value.
13254       return Visit(E->getSubExpr());
13255     case UO_Minus: {
13256       if (!Visit(E->getSubExpr())) return false;
13257       if (!Result.isFixedPoint())
13258         return Error(E);
13259       bool Overflowed;
13260       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13261       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13262         return false;
13263       return Success(Negated, E);
13264     }
13265     case UO_LNot: {
13266       bool bres;
13267       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13268         return false;
13269       return Success(!bres, E);
13270     }
13271   }
13272 }
13273 
13274 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13275   const Expr *SubExpr = E->getSubExpr();
13276   QualType DestType = E->getType();
13277   assert(DestType->isFixedPointType() &&
13278          "Expected destination type to be a fixed point type");
13279   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13280 
13281   switch (E->getCastKind()) {
13282   case CK_FixedPointCast: {
13283     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13284     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13285       return false;
13286     bool Overflowed;
13287     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13288     if (Overflowed) {
13289       if (Info.checkingForUndefinedBehavior())
13290         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13291                                          diag::warn_fixedpoint_constant_overflow)
13292           << Result.toString() << E->getType();
13293       else if (!HandleOverflow(Info, E, Result, E->getType()))
13294         return false;
13295     }
13296     return Success(Result, E);
13297   }
13298   case CK_IntegralToFixedPoint: {
13299     APSInt Src;
13300     if (!EvaluateInteger(SubExpr, Src, Info))
13301       return false;
13302 
13303     bool Overflowed;
13304     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13305         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13306 
13307     if (Overflowed) {
13308       if (Info.checkingForUndefinedBehavior())
13309         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13310                                          diag::warn_fixedpoint_constant_overflow)
13311           << IntResult.toString() << E->getType();
13312       else if (!HandleOverflow(Info, E, IntResult, E->getType()))
13313         return false;
13314     }
13315 
13316     return Success(IntResult, E);
13317   }
13318   case CK_FloatingToFixedPoint: {
13319     APFloat Src(0.0);
13320     if (!EvaluateFloat(SubExpr, Src, Info))
13321       return false;
13322 
13323     bool Overflowed;
13324     APFixedPoint Result = APFixedPoint::getFromFloatValue(
13325         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13326 
13327     if (Overflowed) {
13328       if (Info.checkingForUndefinedBehavior())
13329         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13330                                          diag::warn_fixedpoint_constant_overflow)
13331           << Result.toString() << E->getType();
13332       else if (!HandleOverflow(Info, E, Result, E->getType()))
13333         return false;
13334     }
13335 
13336     return Success(Result, E);
13337   }
13338   case CK_NoOp:
13339   case CK_LValueToRValue:
13340     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13341   default:
13342     return Error(E);
13343   }
13344 }
13345 
13346 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13347   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13348     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13349 
13350   const Expr *LHS = E->getLHS();
13351   const Expr *RHS = E->getRHS();
13352   FixedPointSemantics ResultFXSema =
13353       Info.Ctx.getFixedPointSemantics(E->getType());
13354 
13355   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13356   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13357     return false;
13358   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13359   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13360     return false;
13361 
13362   bool OpOverflow = false, ConversionOverflow = false;
13363   APFixedPoint Result(LHSFX.getSemantics());
13364   switch (E->getOpcode()) {
13365   case BO_Add: {
13366     Result = LHSFX.add(RHSFX, &OpOverflow)
13367                   .convert(ResultFXSema, &ConversionOverflow);
13368     break;
13369   }
13370   case BO_Sub: {
13371     Result = LHSFX.sub(RHSFX, &OpOverflow)
13372                   .convert(ResultFXSema, &ConversionOverflow);
13373     break;
13374   }
13375   case BO_Mul: {
13376     Result = LHSFX.mul(RHSFX, &OpOverflow)
13377                   .convert(ResultFXSema, &ConversionOverflow);
13378     break;
13379   }
13380   case BO_Div: {
13381     if (RHSFX.getValue() == 0) {
13382       Info.FFDiag(E, diag::note_expr_divide_by_zero);
13383       return false;
13384     }
13385     Result = LHSFX.div(RHSFX, &OpOverflow)
13386                   .convert(ResultFXSema, &ConversionOverflow);
13387     break;
13388   }
13389   case BO_Shl:
13390   case BO_Shr: {
13391     FixedPointSemantics LHSSema = LHSFX.getSemantics();
13392     llvm::APSInt RHSVal = RHSFX.getValue();
13393 
13394     unsigned ShiftBW =
13395         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13396     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13397     // Embedded-C 4.1.6.2.2:
13398     //   The right operand must be nonnegative and less than the total number
13399     //   of (nonpadding) bits of the fixed-point operand ...
13400     if (RHSVal.isNegative())
13401       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13402     else if (Amt != RHSVal)
13403       Info.CCEDiag(E, diag::note_constexpr_large_shift)
13404           << RHSVal << E->getType() << ShiftBW;
13405 
13406     if (E->getOpcode() == BO_Shl)
13407       Result = LHSFX.shl(Amt, &OpOverflow);
13408     else
13409       Result = LHSFX.shr(Amt, &OpOverflow);
13410     break;
13411   }
13412   default:
13413     return false;
13414   }
13415   if (OpOverflow || ConversionOverflow) {
13416     if (Info.checkingForUndefinedBehavior())
13417       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13418                                        diag::warn_fixedpoint_constant_overflow)
13419         << Result.toString() << E->getType();
13420     else if (!HandleOverflow(Info, E, Result, E->getType()))
13421       return false;
13422   }
13423   return Success(Result, E);
13424 }
13425 
13426 //===----------------------------------------------------------------------===//
13427 // Float Evaluation
13428 //===----------------------------------------------------------------------===//
13429 
13430 namespace {
13431 class FloatExprEvaluator
13432   : public ExprEvaluatorBase<FloatExprEvaluator> {
13433   APFloat &Result;
13434 public:
13435   FloatExprEvaluator(EvalInfo &info, APFloat &result)
13436     : ExprEvaluatorBaseTy(info), Result(result) {}
13437 
13438   bool Success(const APValue &V, const Expr *e) {
13439     Result = V.getFloat();
13440     return true;
13441   }
13442 
13443   bool ZeroInitialization(const Expr *E) {
13444     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13445     return true;
13446   }
13447 
13448   bool VisitCallExpr(const CallExpr *E);
13449 
13450   bool VisitUnaryOperator(const UnaryOperator *E);
13451   bool VisitBinaryOperator(const BinaryOperator *E);
13452   bool VisitFloatingLiteral(const FloatingLiteral *E);
13453   bool VisitCastExpr(const CastExpr *E);
13454 
13455   bool VisitUnaryReal(const UnaryOperator *E);
13456   bool VisitUnaryImag(const UnaryOperator *E);
13457 
13458   // FIXME: Missing: array subscript of vector, member of vector
13459 };
13460 } // end anonymous namespace
13461 
13462 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13463   assert(E->isRValue() && E->getType()->isRealFloatingType());
13464   return FloatExprEvaluator(Info, Result).Visit(E);
13465 }
13466 
13467 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13468                                   QualType ResultTy,
13469                                   const Expr *Arg,
13470                                   bool SNaN,
13471                                   llvm::APFloat &Result) {
13472   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13473   if (!S) return false;
13474 
13475   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13476 
13477   llvm::APInt fill;
13478 
13479   // Treat empty strings as if they were zero.
13480   if (S->getString().empty())
13481     fill = llvm::APInt(32, 0);
13482   else if (S->getString().getAsInteger(0, fill))
13483     return false;
13484 
13485   if (Context.getTargetInfo().isNan2008()) {
13486     if (SNaN)
13487       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13488     else
13489       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13490   } else {
13491     // Prior to IEEE 754-2008, architectures were allowed to choose whether
13492     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13493     // a different encoding to what became a standard in 2008, and for pre-
13494     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13495     // sNaN. This is now known as "legacy NaN" encoding.
13496     if (SNaN)
13497       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13498     else
13499       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13500   }
13501 
13502   return true;
13503 }
13504 
13505 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
13506   switch (E->getBuiltinCallee()) {
13507   default:
13508     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13509 
13510   case Builtin::BI__builtin_huge_val:
13511   case Builtin::BI__builtin_huge_valf:
13512   case Builtin::BI__builtin_huge_vall:
13513   case Builtin::BI__builtin_huge_valf128:
13514   case Builtin::BI__builtin_inf:
13515   case Builtin::BI__builtin_inff:
13516   case Builtin::BI__builtin_infl:
13517   case Builtin::BI__builtin_inff128: {
13518     const llvm::fltSemantics &Sem =
13519       Info.Ctx.getFloatTypeSemantics(E->getType());
13520     Result = llvm::APFloat::getInf(Sem);
13521     return true;
13522   }
13523 
13524   case Builtin::BI__builtin_nans:
13525   case Builtin::BI__builtin_nansf:
13526   case Builtin::BI__builtin_nansl:
13527   case Builtin::BI__builtin_nansf128:
13528     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13529                                true, Result))
13530       return Error(E);
13531     return true;
13532 
13533   case Builtin::BI__builtin_nan:
13534   case Builtin::BI__builtin_nanf:
13535   case Builtin::BI__builtin_nanl:
13536   case Builtin::BI__builtin_nanf128:
13537     // If this is __builtin_nan() turn this into a nan, otherwise we
13538     // can't constant fold it.
13539     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13540                                false, Result))
13541       return Error(E);
13542     return true;
13543 
13544   case Builtin::BI__builtin_fabs:
13545   case Builtin::BI__builtin_fabsf:
13546   case Builtin::BI__builtin_fabsl:
13547   case Builtin::BI__builtin_fabsf128:
13548     if (!EvaluateFloat(E->getArg(0), Result, Info))
13549       return false;
13550 
13551     if (Result.isNegative())
13552       Result.changeSign();
13553     return true;
13554 
13555   // FIXME: Builtin::BI__builtin_powi
13556   // FIXME: Builtin::BI__builtin_powif
13557   // FIXME: Builtin::BI__builtin_powil
13558 
13559   case Builtin::BI__builtin_copysign:
13560   case Builtin::BI__builtin_copysignf:
13561   case Builtin::BI__builtin_copysignl:
13562   case Builtin::BI__builtin_copysignf128: {
13563     APFloat RHS(0.);
13564     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
13565         !EvaluateFloat(E->getArg(1), RHS, Info))
13566       return false;
13567     Result.copySign(RHS);
13568     return true;
13569   }
13570   }
13571 }
13572 
13573 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13574   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13575     ComplexValue CV;
13576     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13577       return false;
13578     Result = CV.FloatReal;
13579     return true;
13580   }
13581 
13582   return Visit(E->getSubExpr());
13583 }
13584 
13585 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13586   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13587     ComplexValue CV;
13588     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13589       return false;
13590     Result = CV.FloatImag;
13591     return true;
13592   }
13593 
13594   VisitIgnoredValue(E->getSubExpr());
13595   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
13596   Result = llvm::APFloat::getZero(Sem);
13597   return true;
13598 }
13599 
13600 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13601   switch (E->getOpcode()) {
13602   default: return Error(E);
13603   case UO_Plus:
13604     return EvaluateFloat(E->getSubExpr(), Result, Info);
13605   case UO_Minus:
13606     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
13607       return false;
13608     Result.changeSign();
13609     return true;
13610   }
13611 }
13612 
13613 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13614   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13615     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13616 
13617   APFloat RHS(0.0);
13618   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
13619   if (!LHSOK && !Info.noteFailure())
13620     return false;
13621   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
13622          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
13623 }
13624 
13625 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
13626   Result = E->getValue();
13627   return true;
13628 }
13629 
13630 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
13631   const Expr* SubExpr = E->getSubExpr();
13632 
13633   switch (E->getCastKind()) {
13634   default:
13635     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13636 
13637   case CK_IntegralToFloating: {
13638     APSInt IntResult;
13639     return EvaluateInteger(SubExpr, IntResult, Info) &&
13640            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
13641                                 E->getType(), Result);
13642   }
13643 
13644   case CK_FixedPointToFloating: {
13645     APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13646     if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
13647       return false;
13648     Result =
13649         FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
13650     return true;
13651   }
13652 
13653   case CK_FloatingCast: {
13654     if (!Visit(SubExpr))
13655       return false;
13656     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
13657                                   Result);
13658   }
13659 
13660   case CK_FloatingComplexToReal: {
13661     ComplexValue V;
13662     if (!EvaluateComplex(SubExpr, V, Info))
13663       return false;
13664     Result = V.getComplexFloatReal();
13665     return true;
13666   }
13667   }
13668 }
13669 
13670 //===----------------------------------------------------------------------===//
13671 // Complex Evaluation (for float and integer)
13672 //===----------------------------------------------------------------------===//
13673 
13674 namespace {
13675 class ComplexExprEvaluator
13676   : public ExprEvaluatorBase<ComplexExprEvaluator> {
13677   ComplexValue &Result;
13678 
13679 public:
13680   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
13681     : ExprEvaluatorBaseTy(info), Result(Result) {}
13682 
13683   bool Success(const APValue &V, const Expr *e) {
13684     Result.setFrom(V);
13685     return true;
13686   }
13687 
13688   bool ZeroInitialization(const Expr *E);
13689 
13690   //===--------------------------------------------------------------------===//
13691   //                            Visitor Methods
13692   //===--------------------------------------------------------------------===//
13693 
13694   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
13695   bool VisitCastExpr(const CastExpr *E);
13696   bool VisitBinaryOperator(const BinaryOperator *E);
13697   bool VisitUnaryOperator(const UnaryOperator *E);
13698   bool VisitInitListExpr(const InitListExpr *E);
13699   bool VisitCallExpr(const CallExpr *E);
13700 };
13701 } // end anonymous namespace
13702 
13703 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
13704                             EvalInfo &Info) {
13705   assert(E->isRValue() && E->getType()->isAnyComplexType());
13706   return ComplexExprEvaluator(Info, Result).Visit(E);
13707 }
13708 
13709 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
13710   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
13711   if (ElemTy->isRealFloatingType()) {
13712     Result.makeComplexFloat();
13713     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
13714     Result.FloatReal = Zero;
13715     Result.FloatImag = Zero;
13716   } else {
13717     Result.makeComplexInt();
13718     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
13719     Result.IntReal = Zero;
13720     Result.IntImag = Zero;
13721   }
13722   return true;
13723 }
13724 
13725 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
13726   const Expr* SubExpr = E->getSubExpr();
13727 
13728   if (SubExpr->getType()->isRealFloatingType()) {
13729     Result.makeComplexFloat();
13730     APFloat &Imag = Result.FloatImag;
13731     if (!EvaluateFloat(SubExpr, Imag, Info))
13732       return false;
13733 
13734     Result.FloatReal = APFloat(Imag.getSemantics());
13735     return true;
13736   } else {
13737     assert(SubExpr->getType()->isIntegerType() &&
13738            "Unexpected imaginary literal.");
13739 
13740     Result.makeComplexInt();
13741     APSInt &Imag = Result.IntImag;
13742     if (!EvaluateInteger(SubExpr, Imag, Info))
13743       return false;
13744 
13745     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
13746     return true;
13747   }
13748 }
13749 
13750 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
13751 
13752   switch (E->getCastKind()) {
13753   case CK_BitCast:
13754   case CK_BaseToDerived:
13755   case CK_DerivedToBase:
13756   case CK_UncheckedDerivedToBase:
13757   case CK_Dynamic:
13758   case CK_ToUnion:
13759   case CK_ArrayToPointerDecay:
13760   case CK_FunctionToPointerDecay:
13761   case CK_NullToPointer:
13762   case CK_NullToMemberPointer:
13763   case CK_BaseToDerivedMemberPointer:
13764   case CK_DerivedToBaseMemberPointer:
13765   case CK_MemberPointerToBoolean:
13766   case CK_ReinterpretMemberPointer:
13767   case CK_ConstructorConversion:
13768   case CK_IntegralToPointer:
13769   case CK_PointerToIntegral:
13770   case CK_PointerToBoolean:
13771   case CK_ToVoid:
13772   case CK_VectorSplat:
13773   case CK_IntegralCast:
13774   case CK_BooleanToSignedIntegral:
13775   case CK_IntegralToBoolean:
13776   case CK_IntegralToFloating:
13777   case CK_FloatingToIntegral:
13778   case CK_FloatingToBoolean:
13779   case CK_FloatingCast:
13780   case CK_CPointerToObjCPointerCast:
13781   case CK_BlockPointerToObjCPointerCast:
13782   case CK_AnyPointerToBlockPointerCast:
13783   case CK_ObjCObjectLValueCast:
13784   case CK_FloatingComplexToReal:
13785   case CK_FloatingComplexToBoolean:
13786   case CK_IntegralComplexToReal:
13787   case CK_IntegralComplexToBoolean:
13788   case CK_ARCProduceObject:
13789   case CK_ARCConsumeObject:
13790   case CK_ARCReclaimReturnedObject:
13791   case CK_ARCExtendBlockObject:
13792   case CK_CopyAndAutoreleaseBlockObject:
13793   case CK_BuiltinFnToFnPtr:
13794   case CK_ZeroToOCLOpaqueType:
13795   case CK_NonAtomicToAtomic:
13796   case CK_AddressSpaceConversion:
13797   case CK_IntToOCLSampler:
13798   case CK_FloatingToFixedPoint:
13799   case CK_FixedPointToFloating:
13800   case CK_FixedPointCast:
13801   case CK_FixedPointToBoolean:
13802   case CK_FixedPointToIntegral:
13803   case CK_IntegralToFixedPoint:
13804     llvm_unreachable("invalid cast kind for complex value");
13805 
13806   case CK_LValueToRValue:
13807   case CK_AtomicToNonAtomic:
13808   case CK_NoOp:
13809   case CK_LValueToRValueBitCast:
13810     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13811 
13812   case CK_Dependent:
13813   case CK_LValueBitCast:
13814   case CK_UserDefinedConversion:
13815     return Error(E);
13816 
13817   case CK_FloatingRealToComplex: {
13818     APFloat &Real = Result.FloatReal;
13819     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
13820       return false;
13821 
13822     Result.makeComplexFloat();
13823     Result.FloatImag = APFloat(Real.getSemantics());
13824     return true;
13825   }
13826 
13827   case CK_FloatingComplexCast: {
13828     if (!Visit(E->getSubExpr()))
13829       return false;
13830 
13831     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13832     QualType From
13833       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13834 
13835     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
13836            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
13837   }
13838 
13839   case CK_FloatingComplexToIntegralComplex: {
13840     if (!Visit(E->getSubExpr()))
13841       return false;
13842 
13843     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13844     QualType From
13845       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13846     Result.makeComplexInt();
13847     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
13848                                 To, Result.IntReal) &&
13849            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
13850                                 To, Result.IntImag);
13851   }
13852 
13853   case CK_IntegralRealToComplex: {
13854     APSInt &Real = Result.IntReal;
13855     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
13856       return false;
13857 
13858     Result.makeComplexInt();
13859     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
13860     return true;
13861   }
13862 
13863   case CK_IntegralComplexCast: {
13864     if (!Visit(E->getSubExpr()))
13865       return false;
13866 
13867     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13868     QualType From
13869       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13870 
13871     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
13872     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
13873     return true;
13874   }
13875 
13876   case CK_IntegralComplexToFloatingComplex: {
13877     if (!Visit(E->getSubExpr()))
13878       return false;
13879 
13880     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13881     QualType From
13882       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13883     Result.makeComplexFloat();
13884     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
13885                                 To, Result.FloatReal) &&
13886            HandleIntToFloatCast(Info, E, From, Result.IntImag,
13887                                 To, Result.FloatImag);
13888   }
13889   }
13890 
13891   llvm_unreachable("unknown cast resulting in complex value");
13892 }
13893 
13894 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13895   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13896     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13897 
13898   // Track whether the LHS or RHS is real at the type system level. When this is
13899   // the case we can simplify our evaluation strategy.
13900   bool LHSReal = false, RHSReal = false;
13901 
13902   bool LHSOK;
13903   if (E->getLHS()->getType()->isRealFloatingType()) {
13904     LHSReal = true;
13905     APFloat &Real = Result.FloatReal;
13906     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
13907     if (LHSOK) {
13908       Result.makeComplexFloat();
13909       Result.FloatImag = APFloat(Real.getSemantics());
13910     }
13911   } else {
13912     LHSOK = Visit(E->getLHS());
13913   }
13914   if (!LHSOK && !Info.noteFailure())
13915     return false;
13916 
13917   ComplexValue RHS;
13918   if (E->getRHS()->getType()->isRealFloatingType()) {
13919     RHSReal = true;
13920     APFloat &Real = RHS.FloatReal;
13921     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
13922       return false;
13923     RHS.makeComplexFloat();
13924     RHS.FloatImag = APFloat(Real.getSemantics());
13925   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
13926     return false;
13927 
13928   assert(!(LHSReal && RHSReal) &&
13929          "Cannot have both operands of a complex operation be real.");
13930   switch (E->getOpcode()) {
13931   default: return Error(E);
13932   case BO_Add:
13933     if (Result.isComplexFloat()) {
13934       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
13935                                        APFloat::rmNearestTiesToEven);
13936       if (LHSReal)
13937         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
13938       else if (!RHSReal)
13939         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
13940                                          APFloat::rmNearestTiesToEven);
13941     } else {
13942       Result.getComplexIntReal() += RHS.getComplexIntReal();
13943       Result.getComplexIntImag() += RHS.getComplexIntImag();
13944     }
13945     break;
13946   case BO_Sub:
13947     if (Result.isComplexFloat()) {
13948       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
13949                                             APFloat::rmNearestTiesToEven);
13950       if (LHSReal) {
13951         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
13952         Result.getComplexFloatImag().changeSign();
13953       } else if (!RHSReal) {
13954         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
13955                                               APFloat::rmNearestTiesToEven);
13956       }
13957     } else {
13958       Result.getComplexIntReal() -= RHS.getComplexIntReal();
13959       Result.getComplexIntImag() -= RHS.getComplexIntImag();
13960     }
13961     break;
13962   case BO_Mul:
13963     if (Result.isComplexFloat()) {
13964       // This is an implementation of complex multiplication according to the
13965       // constraints laid out in C11 Annex G. The implementation uses the
13966       // following naming scheme:
13967       //   (a + ib) * (c + id)
13968       ComplexValue LHS = Result;
13969       APFloat &A = LHS.getComplexFloatReal();
13970       APFloat &B = LHS.getComplexFloatImag();
13971       APFloat &C = RHS.getComplexFloatReal();
13972       APFloat &D = RHS.getComplexFloatImag();
13973       APFloat &ResR = Result.getComplexFloatReal();
13974       APFloat &ResI = Result.getComplexFloatImag();
13975       if (LHSReal) {
13976         assert(!RHSReal && "Cannot have two real operands for a complex op!");
13977         ResR = A * C;
13978         ResI = A * D;
13979       } else if (RHSReal) {
13980         ResR = C * A;
13981         ResI = C * B;
13982       } else {
13983         // In the fully general case, we need to handle NaNs and infinities
13984         // robustly.
13985         APFloat AC = A * C;
13986         APFloat BD = B * D;
13987         APFloat AD = A * D;
13988         APFloat BC = B * C;
13989         ResR = AC - BD;
13990         ResI = AD + BC;
13991         if (ResR.isNaN() && ResI.isNaN()) {
13992           bool Recalc = false;
13993           if (A.isInfinity() || B.isInfinity()) {
13994             A = APFloat::copySign(
13995                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
13996             B = APFloat::copySign(
13997                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
13998             if (C.isNaN())
13999               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14000             if (D.isNaN())
14001               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14002             Recalc = true;
14003           }
14004           if (C.isInfinity() || D.isInfinity()) {
14005             C = APFloat::copySign(
14006                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14007             D = APFloat::copySign(
14008                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14009             if (A.isNaN())
14010               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14011             if (B.isNaN())
14012               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14013             Recalc = true;
14014           }
14015           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14016                           AD.isInfinity() || BC.isInfinity())) {
14017             if (A.isNaN())
14018               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14019             if (B.isNaN())
14020               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14021             if (C.isNaN())
14022               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14023             if (D.isNaN())
14024               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14025             Recalc = true;
14026           }
14027           if (Recalc) {
14028             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14029             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14030           }
14031         }
14032       }
14033     } else {
14034       ComplexValue LHS = Result;
14035       Result.getComplexIntReal() =
14036         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14037          LHS.getComplexIntImag() * RHS.getComplexIntImag());
14038       Result.getComplexIntImag() =
14039         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14040          LHS.getComplexIntImag() * RHS.getComplexIntReal());
14041     }
14042     break;
14043   case BO_Div:
14044     if (Result.isComplexFloat()) {
14045       // This is an implementation of complex division according to the
14046       // constraints laid out in C11 Annex G. The implementation uses the
14047       // following naming scheme:
14048       //   (a + ib) / (c + id)
14049       ComplexValue LHS = Result;
14050       APFloat &A = LHS.getComplexFloatReal();
14051       APFloat &B = LHS.getComplexFloatImag();
14052       APFloat &C = RHS.getComplexFloatReal();
14053       APFloat &D = RHS.getComplexFloatImag();
14054       APFloat &ResR = Result.getComplexFloatReal();
14055       APFloat &ResI = Result.getComplexFloatImag();
14056       if (RHSReal) {
14057         ResR = A / C;
14058         ResI = B / C;
14059       } else {
14060         if (LHSReal) {
14061           // No real optimizations we can do here, stub out with zero.
14062           B = APFloat::getZero(A.getSemantics());
14063         }
14064         int DenomLogB = 0;
14065         APFloat MaxCD = maxnum(abs(C), abs(D));
14066         if (MaxCD.isFinite()) {
14067           DenomLogB = ilogb(MaxCD);
14068           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14069           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14070         }
14071         APFloat Denom = C * C + D * D;
14072         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14073                       APFloat::rmNearestTiesToEven);
14074         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14075                       APFloat::rmNearestTiesToEven);
14076         if (ResR.isNaN() && ResI.isNaN()) {
14077           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14078             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14079             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14080           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14081                      D.isFinite()) {
14082             A = APFloat::copySign(
14083                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14084             B = APFloat::copySign(
14085                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14086             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14087             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14088           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14089             C = APFloat::copySign(
14090                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14091             D = APFloat::copySign(
14092                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14093             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14094             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14095           }
14096         }
14097       }
14098     } else {
14099       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14100         return Error(E, diag::note_expr_divide_by_zero);
14101 
14102       ComplexValue LHS = Result;
14103       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14104         RHS.getComplexIntImag() * RHS.getComplexIntImag();
14105       Result.getComplexIntReal() =
14106         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14107          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14108       Result.getComplexIntImag() =
14109         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14110          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14111     }
14112     break;
14113   }
14114 
14115   return true;
14116 }
14117 
14118 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14119   // Get the operand value into 'Result'.
14120   if (!Visit(E->getSubExpr()))
14121     return false;
14122 
14123   switch (E->getOpcode()) {
14124   default:
14125     return Error(E);
14126   case UO_Extension:
14127     return true;
14128   case UO_Plus:
14129     // The result is always just the subexpr.
14130     return true;
14131   case UO_Minus:
14132     if (Result.isComplexFloat()) {
14133       Result.getComplexFloatReal().changeSign();
14134       Result.getComplexFloatImag().changeSign();
14135     }
14136     else {
14137       Result.getComplexIntReal() = -Result.getComplexIntReal();
14138       Result.getComplexIntImag() = -Result.getComplexIntImag();
14139     }
14140     return true;
14141   case UO_Not:
14142     if (Result.isComplexFloat())
14143       Result.getComplexFloatImag().changeSign();
14144     else
14145       Result.getComplexIntImag() = -Result.getComplexIntImag();
14146     return true;
14147   }
14148 }
14149 
14150 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14151   if (E->getNumInits() == 2) {
14152     if (E->getType()->isComplexType()) {
14153       Result.makeComplexFloat();
14154       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14155         return false;
14156       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14157         return false;
14158     } else {
14159       Result.makeComplexInt();
14160       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14161         return false;
14162       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14163         return false;
14164     }
14165     return true;
14166   }
14167   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14168 }
14169 
14170 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14171   switch (E->getBuiltinCallee()) {
14172   case Builtin::BI__builtin_complex:
14173     Result.makeComplexFloat();
14174     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14175       return false;
14176     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14177       return false;
14178     return true;
14179 
14180   default:
14181     break;
14182   }
14183 
14184   return ExprEvaluatorBaseTy::VisitCallExpr(E);
14185 }
14186 
14187 //===----------------------------------------------------------------------===//
14188 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14189 // implicit conversion.
14190 //===----------------------------------------------------------------------===//
14191 
14192 namespace {
14193 class AtomicExprEvaluator :
14194     public ExprEvaluatorBase<AtomicExprEvaluator> {
14195   const LValue *This;
14196   APValue &Result;
14197 public:
14198   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14199       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14200 
14201   bool Success(const APValue &V, const Expr *E) {
14202     Result = V;
14203     return true;
14204   }
14205 
14206   bool ZeroInitialization(const Expr *E) {
14207     ImplicitValueInitExpr VIE(
14208         E->getType()->castAs<AtomicType>()->getValueType());
14209     // For atomic-qualified class (and array) types in C++, initialize the
14210     // _Atomic-wrapped subobject directly, in-place.
14211     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14212                 : Evaluate(Result, Info, &VIE);
14213   }
14214 
14215   bool VisitCastExpr(const CastExpr *E) {
14216     switch (E->getCastKind()) {
14217     default:
14218       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14219     case CK_NonAtomicToAtomic:
14220       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14221                   : Evaluate(Result, Info, E->getSubExpr());
14222     }
14223   }
14224 };
14225 } // end anonymous namespace
14226 
14227 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14228                            EvalInfo &Info) {
14229   assert(E->isRValue() && E->getType()->isAtomicType());
14230   return AtomicExprEvaluator(Info, This, Result).Visit(E);
14231 }
14232 
14233 //===----------------------------------------------------------------------===//
14234 // Void expression evaluation, primarily for a cast to void on the LHS of a
14235 // comma operator
14236 //===----------------------------------------------------------------------===//
14237 
14238 namespace {
14239 class VoidExprEvaluator
14240   : public ExprEvaluatorBase<VoidExprEvaluator> {
14241 public:
14242   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14243 
14244   bool Success(const APValue &V, const Expr *e) { return true; }
14245 
14246   bool ZeroInitialization(const Expr *E) { return true; }
14247 
14248   bool VisitCastExpr(const CastExpr *E) {
14249     switch (E->getCastKind()) {
14250     default:
14251       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14252     case CK_ToVoid:
14253       VisitIgnoredValue(E->getSubExpr());
14254       return true;
14255     }
14256   }
14257 
14258   bool VisitCallExpr(const CallExpr *E) {
14259     switch (E->getBuiltinCallee()) {
14260     case Builtin::BI__assume:
14261     case Builtin::BI__builtin_assume:
14262       // The argument is not evaluated!
14263       return true;
14264 
14265     case Builtin::BI__builtin_operator_delete:
14266       return HandleOperatorDeleteCall(Info, E);
14267 
14268     default:
14269       break;
14270     }
14271 
14272     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14273   }
14274 
14275   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14276 };
14277 } // end anonymous namespace
14278 
14279 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14280   // We cannot speculatively evaluate a delete expression.
14281   if (Info.SpeculativeEvaluationDepth)
14282     return false;
14283 
14284   FunctionDecl *OperatorDelete = E->getOperatorDelete();
14285   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14286     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14287         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14288     return false;
14289   }
14290 
14291   const Expr *Arg = E->getArgument();
14292 
14293   LValue Pointer;
14294   if (!EvaluatePointer(Arg, Pointer, Info))
14295     return false;
14296   if (Pointer.Designator.Invalid)
14297     return false;
14298 
14299   // Deleting a null pointer has no effect.
14300   if (Pointer.isNullPointer()) {
14301     // This is the only case where we need to produce an extension warning:
14302     // the only other way we can succeed is if we find a dynamic allocation,
14303     // and we will have warned when we allocated it in that case.
14304     if (!Info.getLangOpts().CPlusPlus20)
14305       Info.CCEDiag(E, diag::note_constexpr_new);
14306     return true;
14307   }
14308 
14309   Optional<DynAlloc *> Alloc = CheckDeleteKind(
14310       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14311   if (!Alloc)
14312     return false;
14313   QualType AllocType = Pointer.Base.getDynamicAllocType();
14314 
14315   // For the non-array case, the designator must be empty if the static type
14316   // does not have a virtual destructor.
14317   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14318       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14319     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14320         << Arg->getType()->getPointeeType() << AllocType;
14321     return false;
14322   }
14323 
14324   // For a class type with a virtual destructor, the selected operator delete
14325   // is the one looked up when building the destructor.
14326   if (!E->isArrayForm() && !E->isGlobalDelete()) {
14327     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14328     if (VirtualDelete &&
14329         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14330       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14331           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14332       return false;
14333     }
14334   }
14335 
14336   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14337                          (*Alloc)->Value, AllocType))
14338     return false;
14339 
14340   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14341     // The element was already erased. This means the destructor call also
14342     // deleted the object.
14343     // FIXME: This probably results in undefined behavior before we get this
14344     // far, and should be diagnosed elsewhere first.
14345     Info.FFDiag(E, diag::note_constexpr_double_delete);
14346     return false;
14347   }
14348 
14349   return true;
14350 }
14351 
14352 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14353   assert(E->isRValue() && E->getType()->isVoidType());
14354   return VoidExprEvaluator(Info).Visit(E);
14355 }
14356 
14357 //===----------------------------------------------------------------------===//
14358 // Top level Expr::EvaluateAsRValue method.
14359 //===----------------------------------------------------------------------===//
14360 
14361 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14362   // In C, function designators are not lvalues, but we evaluate them as if they
14363   // are.
14364   QualType T = E->getType();
14365   if (E->isGLValue() || T->isFunctionType()) {
14366     LValue LV;
14367     if (!EvaluateLValue(E, LV, Info))
14368       return false;
14369     LV.moveInto(Result);
14370   } else if (T->isVectorType()) {
14371     if (!EvaluateVector(E, Result, Info))
14372       return false;
14373   } else if (T->isIntegralOrEnumerationType()) {
14374     if (!IntExprEvaluator(Info, Result).Visit(E))
14375       return false;
14376   } else if (T->hasPointerRepresentation()) {
14377     LValue LV;
14378     if (!EvaluatePointer(E, LV, Info))
14379       return false;
14380     LV.moveInto(Result);
14381   } else if (T->isRealFloatingType()) {
14382     llvm::APFloat F(0.0);
14383     if (!EvaluateFloat(E, F, Info))
14384       return false;
14385     Result = APValue(F);
14386   } else if (T->isAnyComplexType()) {
14387     ComplexValue C;
14388     if (!EvaluateComplex(E, C, Info))
14389       return false;
14390     C.moveInto(Result);
14391   } else if (T->isFixedPointType()) {
14392     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
14393   } else if (T->isMemberPointerType()) {
14394     MemberPtr P;
14395     if (!EvaluateMemberPointer(E, P, Info))
14396       return false;
14397     P.moveInto(Result);
14398     return true;
14399   } else if (T->isArrayType()) {
14400     LValue LV;
14401     APValue &Value =
14402         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14403     if (!EvaluateArray(E, LV, Value, Info))
14404       return false;
14405     Result = Value;
14406   } else if (T->isRecordType()) {
14407     LValue LV;
14408     APValue &Value =
14409         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14410     if (!EvaluateRecord(E, LV, Value, Info))
14411       return false;
14412     Result = Value;
14413   } else if (T->isVoidType()) {
14414     if (!Info.getLangOpts().CPlusPlus11)
14415       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
14416         << E->getType();
14417     if (!EvaluateVoid(E, Info))
14418       return false;
14419   } else if (T->isAtomicType()) {
14420     QualType Unqual = T.getAtomicUnqualifiedType();
14421     if (Unqual->isArrayType() || Unqual->isRecordType()) {
14422       LValue LV;
14423       APValue &Value = Info.CurrentCall->createTemporary(
14424           E, Unqual, ScopeKind::FullExpression, LV);
14425       if (!EvaluateAtomic(E, &LV, Value, Info))
14426         return false;
14427     } else {
14428       if (!EvaluateAtomic(E, nullptr, Result, Info))
14429         return false;
14430     }
14431   } else if (Info.getLangOpts().CPlusPlus11) {
14432     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
14433     return false;
14434   } else {
14435     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14436     return false;
14437   }
14438 
14439   return true;
14440 }
14441 
14442 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
14443 /// cases, the in-place evaluation is essential, since later initializers for
14444 /// an object can indirectly refer to subobjects which were initialized earlier.
14445 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
14446                             const Expr *E, bool AllowNonLiteralTypes) {
14447   assert(!E->isValueDependent());
14448 
14449   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
14450     return false;
14451 
14452   if (E->isRValue()) {
14453     // Evaluate arrays and record types in-place, so that later initializers can
14454     // refer to earlier-initialized members of the object.
14455     QualType T = E->getType();
14456     if (T->isArrayType())
14457       return EvaluateArray(E, This, Result, Info);
14458     else if (T->isRecordType())
14459       return EvaluateRecord(E, This, Result, Info);
14460     else if (T->isAtomicType()) {
14461       QualType Unqual = T.getAtomicUnqualifiedType();
14462       if (Unqual->isArrayType() || Unqual->isRecordType())
14463         return EvaluateAtomic(E, &This, Result, Info);
14464     }
14465   }
14466 
14467   // For any other type, in-place evaluation is unimportant.
14468   return Evaluate(Result, Info, E);
14469 }
14470 
14471 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
14472 /// lvalue-to-rvalue cast if it is an lvalue.
14473 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
14474   if (Info.EnableNewConstInterp) {
14475     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
14476       return false;
14477   } else {
14478     if (E->getType().isNull())
14479       return false;
14480 
14481     if (!CheckLiteralType(Info, E))
14482       return false;
14483 
14484     if (!::Evaluate(Result, Info, E))
14485       return false;
14486 
14487     if (E->isGLValue()) {
14488       LValue LV;
14489       LV.setFrom(Info.Ctx, Result);
14490       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14491         return false;
14492     }
14493   }
14494 
14495   // Check this core constant expression is a constant expression.
14496   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result) &&
14497          CheckMemoryLeaks(Info);
14498 }
14499 
14500 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
14501                                  const ASTContext &Ctx, bool &IsConst) {
14502   // Fast-path evaluations of integer literals, since we sometimes see files
14503   // containing vast quantities of these.
14504   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
14505     Result.Val = APValue(APSInt(L->getValue(),
14506                                 L->getType()->isUnsignedIntegerType()));
14507     IsConst = true;
14508     return true;
14509   }
14510 
14511   // This case should be rare, but we need to check it before we check on
14512   // the type below.
14513   if (Exp->getType().isNull()) {
14514     IsConst = false;
14515     return true;
14516   }
14517 
14518   // FIXME: Evaluating values of large array and record types can cause
14519   // performance problems. Only do so in C++11 for now.
14520   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
14521                           Exp->getType()->isRecordType()) &&
14522       !Ctx.getLangOpts().CPlusPlus11) {
14523     IsConst = false;
14524     return true;
14525   }
14526   return false;
14527 }
14528 
14529 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
14530                                       Expr::SideEffectsKind SEK) {
14531   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
14532          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
14533 }
14534 
14535 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
14536                              const ASTContext &Ctx, EvalInfo &Info) {
14537   bool IsConst;
14538   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
14539     return IsConst;
14540 
14541   return EvaluateAsRValue(Info, E, Result.Val);
14542 }
14543 
14544 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
14545                           const ASTContext &Ctx,
14546                           Expr::SideEffectsKind AllowSideEffects,
14547                           EvalInfo &Info) {
14548   if (!E->getType()->isIntegralOrEnumerationType())
14549     return false;
14550 
14551   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
14552       !ExprResult.Val.isInt() ||
14553       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14554     return false;
14555 
14556   return true;
14557 }
14558 
14559 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
14560                                  const ASTContext &Ctx,
14561                                  Expr::SideEffectsKind AllowSideEffects,
14562                                  EvalInfo &Info) {
14563   if (!E->getType()->isFixedPointType())
14564     return false;
14565 
14566   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
14567     return false;
14568 
14569   if (!ExprResult.Val.isFixedPoint() ||
14570       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14571     return false;
14572 
14573   return true;
14574 }
14575 
14576 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
14577 /// any crazy technique (that has nothing to do with language standards) that
14578 /// we want to.  If this function returns true, it returns the folded constant
14579 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
14580 /// will be applied to the result.
14581 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
14582                             bool InConstantContext) const {
14583   assert(!isValueDependent() &&
14584          "Expression evaluator can't be called on a dependent expression.");
14585   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14586   Info.InConstantContext = InConstantContext;
14587   return ::EvaluateAsRValue(this, Result, Ctx, Info);
14588 }
14589 
14590 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
14591                                       bool InConstantContext) const {
14592   assert(!isValueDependent() &&
14593          "Expression evaluator can't be called on a dependent expression.");
14594   EvalResult Scratch;
14595   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
14596          HandleConversionToBool(Scratch.Val, Result);
14597 }
14598 
14599 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
14600                          SideEffectsKind AllowSideEffects,
14601                          bool InConstantContext) const {
14602   assert(!isValueDependent() &&
14603          "Expression evaluator can't be called on a dependent expression.");
14604   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14605   Info.InConstantContext = InConstantContext;
14606   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
14607 }
14608 
14609 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
14610                                 SideEffectsKind AllowSideEffects,
14611                                 bool InConstantContext) const {
14612   assert(!isValueDependent() &&
14613          "Expression evaluator can't be called on a dependent expression.");
14614   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14615   Info.InConstantContext = InConstantContext;
14616   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
14617 }
14618 
14619 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
14620                            SideEffectsKind AllowSideEffects,
14621                            bool InConstantContext) const {
14622   assert(!isValueDependent() &&
14623          "Expression evaluator can't be called on a dependent expression.");
14624 
14625   if (!getType()->isRealFloatingType())
14626     return false;
14627 
14628   EvalResult ExprResult;
14629   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
14630       !ExprResult.Val.isFloat() ||
14631       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14632     return false;
14633 
14634   Result = ExprResult.Val.getFloat();
14635   return true;
14636 }
14637 
14638 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
14639                             bool InConstantContext) const {
14640   assert(!isValueDependent() &&
14641          "Expression evaluator can't be called on a dependent expression.");
14642 
14643   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
14644   Info.InConstantContext = InConstantContext;
14645   LValue LV;
14646   CheckedTemporaries CheckedTemps;
14647   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
14648       Result.HasSideEffects ||
14649       !CheckLValueConstantExpression(Info, getExprLoc(),
14650                                      Ctx.getLValueReferenceType(getType()), LV,
14651                                      Expr::EvaluateForCodeGen, CheckedTemps))
14652     return false;
14653 
14654   LV.moveInto(Result.Val);
14655   return true;
14656 }
14657 
14658 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
14659                                   const ASTContext &Ctx, bool InPlace) const {
14660   assert(!isValueDependent() &&
14661          "Expression evaluator can't be called on a dependent expression.");
14662 
14663   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
14664   EvalInfo Info(Ctx, Result, EM);
14665   Info.InConstantContext = true;
14666 
14667   if (InPlace) {
14668     Info.setEvaluatingDecl(this, Result.Val);
14669     LValue LVal;
14670     LVal.set(this);
14671     if (!::EvaluateInPlace(Result.Val, Info, LVal, this) ||
14672         Result.HasSideEffects)
14673       return false;
14674   } else if (!::Evaluate(Result.Val, Info, this) || Result.HasSideEffects)
14675     return false;
14676 
14677   if (!Info.discardCleanups())
14678     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14679 
14680   return CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
14681                                  Result.Val, Usage) &&
14682          CheckMemoryLeaks(Info);
14683 }
14684 
14685 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
14686                                  const VarDecl *VD,
14687                                  SmallVectorImpl<PartialDiagnosticAt> &Notes,
14688                                  bool IsConstantInitialization) const {
14689   assert(!isValueDependent() &&
14690          "Expression evaluator can't be called on a dependent expression.");
14691 
14692   // FIXME: Evaluating initializers for large array and record types can cause
14693   // performance problems. Only do so in C++11 for now.
14694   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
14695       !Ctx.getLangOpts().CPlusPlus11)
14696     return false;
14697 
14698   Expr::EvalStatus EStatus;
14699   EStatus.Diag = &Notes;
14700 
14701   EvalInfo Info(Ctx, EStatus,
14702                 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11)
14703                     ? EvalInfo::EM_ConstantExpression
14704                     : EvalInfo::EM_ConstantFold);
14705   Info.setEvaluatingDecl(VD, Value);
14706   Info.InConstantContext = IsConstantInitialization;
14707 
14708   SourceLocation DeclLoc = VD->getLocation();
14709   QualType DeclTy = VD->getType();
14710 
14711   if (Info.EnableNewConstInterp) {
14712     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
14713     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
14714       return false;
14715   } else {
14716     LValue LVal;
14717     LVal.set(VD);
14718 
14719     if (!EvaluateInPlace(Value, Info, LVal, this,
14720                          /*AllowNonLiteralTypes=*/true) ||
14721         EStatus.HasSideEffects)
14722       return false;
14723 
14724     // At this point, any lifetime-extended temporaries are completely
14725     // initialized.
14726     Info.performLifetimeExtension();
14727 
14728     if (!Info.discardCleanups())
14729       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14730   }
14731   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value) &&
14732          CheckMemoryLeaks(Info);
14733 }
14734 
14735 bool VarDecl::evaluateDestruction(
14736     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
14737   Expr::EvalStatus EStatus;
14738   EStatus.Diag = &Notes;
14739 
14740   // Make a copy of the value for the destructor to mutate, if we know it.
14741   // Otherwise, treat the value as default-initialized; if the destructor works
14742   // anyway, then the destruction is constant (and must be essentially empty).
14743   APValue DestroyedValue;
14744   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
14745     DestroyedValue = *getEvaluatedValue();
14746   else if (!getDefaultInitValue(getType(), DestroyedValue))
14747     return false;
14748 
14749   EvalInfo Info(getASTContext(), EStatus, EvalInfo::EM_ConstantExpression);
14750   Info.setEvaluatingDecl(this, DestroyedValue,
14751                          EvalInfo::EvaluatingDeclKind::Dtor);
14752   Info.InConstantContext = true;
14753 
14754   SourceLocation DeclLoc = getLocation();
14755   QualType DeclTy = getType();
14756 
14757   LValue LVal;
14758   LVal.set(this);
14759 
14760   if (!HandleDestruction(Info, DeclLoc, LVal.Base, DestroyedValue, DeclTy) ||
14761       EStatus.HasSideEffects)
14762     return false;
14763 
14764   if (!Info.discardCleanups())
14765     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14766 
14767   ensureEvaluatedStmt()->HasConstantDestruction = true;
14768   return true;
14769 }
14770 
14771 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
14772 /// constant folded, but discard the result.
14773 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
14774   assert(!isValueDependent() &&
14775          "Expression evaluator can't be called on a dependent expression.");
14776 
14777   EvalResult Result;
14778   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
14779          !hasUnacceptableSideEffect(Result, SEK);
14780 }
14781 
14782 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
14783                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14784   assert(!isValueDependent() &&
14785          "Expression evaluator can't be called on a dependent expression.");
14786 
14787   EvalResult EVResult;
14788   EVResult.Diag = Diag;
14789   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14790   Info.InConstantContext = true;
14791 
14792   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
14793   (void)Result;
14794   assert(Result && "Could not evaluate expression");
14795   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14796 
14797   return EVResult.Val.getInt();
14798 }
14799 
14800 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
14801     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14802   assert(!isValueDependent() &&
14803          "Expression evaluator can't be called on a dependent expression.");
14804 
14805   EvalResult EVResult;
14806   EVResult.Diag = Diag;
14807   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14808   Info.InConstantContext = true;
14809   Info.CheckingForUndefinedBehavior = true;
14810 
14811   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
14812   (void)Result;
14813   assert(Result && "Could not evaluate expression");
14814   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14815 
14816   return EVResult.Val.getInt();
14817 }
14818 
14819 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
14820   assert(!isValueDependent() &&
14821          "Expression evaluator can't be called on a dependent expression.");
14822 
14823   bool IsConst;
14824   EvalResult EVResult;
14825   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
14826     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14827     Info.CheckingForUndefinedBehavior = true;
14828     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
14829   }
14830 }
14831 
14832 bool Expr::EvalResult::isGlobalLValue() const {
14833   assert(Val.isLValue());
14834   return IsGlobalLValue(Val.getLValueBase());
14835 }
14836 
14837 
14838 /// isIntegerConstantExpr - this recursive routine will test if an expression is
14839 /// an integer constant expression.
14840 
14841 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
14842 /// comma, etc
14843 
14844 // CheckICE - This function does the fundamental ICE checking: the returned
14845 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
14846 // and a (possibly null) SourceLocation indicating the location of the problem.
14847 //
14848 // Note that to reduce code duplication, this helper does no evaluation
14849 // itself; the caller checks whether the expression is evaluatable, and
14850 // in the rare cases where CheckICE actually cares about the evaluated
14851 // value, it calls into Evaluate.
14852 
14853 namespace {
14854 
14855 enum ICEKind {
14856   /// This expression is an ICE.
14857   IK_ICE,
14858   /// This expression is not an ICE, but if it isn't evaluated, it's
14859   /// a legal subexpression for an ICE. This return value is used to handle
14860   /// the comma operator in C99 mode, and non-constant subexpressions.
14861   IK_ICEIfUnevaluated,
14862   /// This expression is not an ICE, and is not a legal subexpression for one.
14863   IK_NotICE
14864 };
14865 
14866 struct ICEDiag {
14867   ICEKind Kind;
14868   SourceLocation Loc;
14869 
14870   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
14871 };
14872 
14873 }
14874 
14875 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
14876 
14877 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
14878 
14879 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
14880   Expr::EvalResult EVResult;
14881   Expr::EvalStatus Status;
14882   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
14883 
14884   Info.InConstantContext = true;
14885   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
14886       !EVResult.Val.isInt())
14887     return ICEDiag(IK_NotICE, E->getBeginLoc());
14888 
14889   return NoDiag();
14890 }
14891 
14892 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
14893   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
14894   if (!E->getType()->isIntegralOrEnumerationType())
14895     return ICEDiag(IK_NotICE, E->getBeginLoc());
14896 
14897   switch (E->getStmtClass()) {
14898 #define ABSTRACT_STMT(Node)
14899 #define STMT(Node, Base) case Expr::Node##Class:
14900 #define EXPR(Node, Base)
14901 #include "clang/AST/StmtNodes.inc"
14902   case Expr::PredefinedExprClass:
14903   case Expr::FloatingLiteralClass:
14904   case Expr::ImaginaryLiteralClass:
14905   case Expr::StringLiteralClass:
14906   case Expr::ArraySubscriptExprClass:
14907   case Expr::MatrixSubscriptExprClass:
14908   case Expr::OMPArraySectionExprClass:
14909   case Expr::OMPArrayShapingExprClass:
14910   case Expr::OMPIteratorExprClass:
14911   case Expr::MemberExprClass:
14912   case Expr::CompoundAssignOperatorClass:
14913   case Expr::CompoundLiteralExprClass:
14914   case Expr::ExtVectorElementExprClass:
14915   case Expr::DesignatedInitExprClass:
14916   case Expr::ArrayInitLoopExprClass:
14917   case Expr::ArrayInitIndexExprClass:
14918   case Expr::NoInitExprClass:
14919   case Expr::DesignatedInitUpdateExprClass:
14920   case Expr::ImplicitValueInitExprClass:
14921   case Expr::ParenListExprClass:
14922   case Expr::VAArgExprClass:
14923   case Expr::AddrLabelExprClass:
14924   case Expr::StmtExprClass:
14925   case Expr::CXXMemberCallExprClass:
14926   case Expr::CUDAKernelCallExprClass:
14927   case Expr::CXXAddrspaceCastExprClass:
14928   case Expr::CXXDynamicCastExprClass:
14929   case Expr::CXXTypeidExprClass:
14930   case Expr::CXXUuidofExprClass:
14931   case Expr::MSPropertyRefExprClass:
14932   case Expr::MSPropertySubscriptExprClass:
14933   case Expr::CXXNullPtrLiteralExprClass:
14934   case Expr::UserDefinedLiteralClass:
14935   case Expr::CXXThisExprClass:
14936   case Expr::CXXThrowExprClass:
14937   case Expr::CXXNewExprClass:
14938   case Expr::CXXDeleteExprClass:
14939   case Expr::CXXPseudoDestructorExprClass:
14940   case Expr::UnresolvedLookupExprClass:
14941   case Expr::TypoExprClass:
14942   case Expr::RecoveryExprClass:
14943   case Expr::DependentScopeDeclRefExprClass:
14944   case Expr::CXXConstructExprClass:
14945   case Expr::CXXInheritedCtorInitExprClass:
14946   case Expr::CXXStdInitializerListExprClass:
14947   case Expr::CXXBindTemporaryExprClass:
14948   case Expr::ExprWithCleanupsClass:
14949   case Expr::CXXTemporaryObjectExprClass:
14950   case Expr::CXXUnresolvedConstructExprClass:
14951   case Expr::CXXDependentScopeMemberExprClass:
14952   case Expr::UnresolvedMemberExprClass:
14953   case Expr::ObjCStringLiteralClass:
14954   case Expr::ObjCBoxedExprClass:
14955   case Expr::ObjCArrayLiteralClass:
14956   case Expr::ObjCDictionaryLiteralClass:
14957   case Expr::ObjCEncodeExprClass:
14958   case Expr::ObjCMessageExprClass:
14959   case Expr::ObjCSelectorExprClass:
14960   case Expr::ObjCProtocolExprClass:
14961   case Expr::ObjCIvarRefExprClass:
14962   case Expr::ObjCPropertyRefExprClass:
14963   case Expr::ObjCSubscriptRefExprClass:
14964   case Expr::ObjCIsaExprClass:
14965   case Expr::ObjCAvailabilityCheckExprClass:
14966   case Expr::ShuffleVectorExprClass:
14967   case Expr::ConvertVectorExprClass:
14968   case Expr::BlockExprClass:
14969   case Expr::NoStmtClass:
14970   case Expr::OpaqueValueExprClass:
14971   case Expr::PackExpansionExprClass:
14972   case Expr::SubstNonTypeTemplateParmPackExprClass:
14973   case Expr::FunctionParmPackExprClass:
14974   case Expr::AsTypeExprClass:
14975   case Expr::ObjCIndirectCopyRestoreExprClass:
14976   case Expr::MaterializeTemporaryExprClass:
14977   case Expr::PseudoObjectExprClass:
14978   case Expr::AtomicExprClass:
14979   case Expr::LambdaExprClass:
14980   case Expr::CXXFoldExprClass:
14981   case Expr::CoawaitExprClass:
14982   case Expr::DependentCoawaitExprClass:
14983   case Expr::CoyieldExprClass:
14984     return ICEDiag(IK_NotICE, E->getBeginLoc());
14985 
14986   case Expr::InitListExprClass: {
14987     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
14988     // form "T x = { a };" is equivalent to "T x = a;".
14989     // Unless we're initializing a reference, T is a scalar as it is known to be
14990     // of integral or enumeration type.
14991     if (E->isRValue())
14992       if (cast<InitListExpr>(E)->getNumInits() == 1)
14993         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
14994     return ICEDiag(IK_NotICE, E->getBeginLoc());
14995   }
14996 
14997   case Expr::SizeOfPackExprClass:
14998   case Expr::GNUNullExprClass:
14999   case Expr::SourceLocExprClass:
15000     return NoDiag();
15001 
15002   case Expr::SubstNonTypeTemplateParmExprClass:
15003     return
15004       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
15005 
15006   case Expr::ConstantExprClass:
15007     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
15008 
15009   case Expr::ParenExprClass:
15010     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15011   case Expr::GenericSelectionExprClass:
15012     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15013   case Expr::IntegerLiteralClass:
15014   case Expr::FixedPointLiteralClass:
15015   case Expr::CharacterLiteralClass:
15016   case Expr::ObjCBoolLiteralExprClass:
15017   case Expr::CXXBoolLiteralExprClass:
15018   case Expr::CXXScalarValueInitExprClass:
15019   case Expr::TypeTraitExprClass:
15020   case Expr::ConceptSpecializationExprClass:
15021   case Expr::RequiresExprClass:
15022   case Expr::ArrayTypeTraitExprClass:
15023   case Expr::ExpressionTraitExprClass:
15024   case Expr::CXXNoexceptExprClass:
15025     return NoDiag();
15026   case Expr::CallExprClass:
15027   case Expr::CXXOperatorCallExprClass: {
15028     // C99 6.6/3 allows function calls within unevaluated subexpressions of
15029     // constant expressions, but they can never be ICEs because an ICE cannot
15030     // contain an operand of (pointer to) function type.
15031     const CallExpr *CE = cast<CallExpr>(E);
15032     if (CE->getBuiltinCallee())
15033       return CheckEvalInICE(E, Ctx);
15034     return ICEDiag(IK_NotICE, E->getBeginLoc());
15035   }
15036   case Expr::CXXRewrittenBinaryOperatorClass:
15037     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15038                     Ctx);
15039   case Expr::DeclRefExprClass: {
15040     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
15041       return NoDiag();
15042     const VarDecl *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl());
15043     if (VD && VD->isUsableInConstantExpressions(Ctx)) {
15044       // C++ 7.1.5.1p2
15045       //   A variable of non-volatile const-qualified integral or enumeration
15046       //   type initialized by an ICE can be used in ICEs.
15047       return NoDiag();
15048     }
15049     return ICEDiag(IK_NotICE, E->getBeginLoc());
15050   }
15051   case Expr::UnaryOperatorClass: {
15052     const UnaryOperator *Exp = cast<UnaryOperator>(E);
15053     switch (Exp->getOpcode()) {
15054     case UO_PostInc:
15055     case UO_PostDec:
15056     case UO_PreInc:
15057     case UO_PreDec:
15058     case UO_AddrOf:
15059     case UO_Deref:
15060     case UO_Coawait:
15061       // C99 6.6/3 allows increment and decrement within unevaluated
15062       // subexpressions of constant expressions, but they can never be ICEs
15063       // because an ICE cannot contain an lvalue operand.
15064       return ICEDiag(IK_NotICE, E->getBeginLoc());
15065     case UO_Extension:
15066     case UO_LNot:
15067     case UO_Plus:
15068     case UO_Minus:
15069     case UO_Not:
15070     case UO_Real:
15071     case UO_Imag:
15072       return CheckICE(Exp->getSubExpr(), Ctx);
15073     }
15074     llvm_unreachable("invalid unary operator class");
15075   }
15076   case Expr::OffsetOfExprClass: {
15077     // Note that per C99, offsetof must be an ICE. And AFAIK, using
15078     // EvaluateAsRValue matches the proposed gcc behavior for cases like
15079     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
15080     // compliance: we should warn earlier for offsetof expressions with
15081     // array subscripts that aren't ICEs, and if the array subscripts
15082     // are ICEs, the value of the offsetof must be an integer constant.
15083     return CheckEvalInICE(E, Ctx);
15084   }
15085   case Expr::UnaryExprOrTypeTraitExprClass: {
15086     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15087     if ((Exp->getKind() ==  UETT_SizeOf) &&
15088         Exp->getTypeOfArgument()->isVariableArrayType())
15089       return ICEDiag(IK_NotICE, E->getBeginLoc());
15090     return NoDiag();
15091   }
15092   case Expr::BinaryOperatorClass: {
15093     const BinaryOperator *Exp = cast<BinaryOperator>(E);
15094     switch (Exp->getOpcode()) {
15095     case BO_PtrMemD:
15096     case BO_PtrMemI:
15097     case BO_Assign:
15098     case BO_MulAssign:
15099     case BO_DivAssign:
15100     case BO_RemAssign:
15101     case BO_AddAssign:
15102     case BO_SubAssign:
15103     case BO_ShlAssign:
15104     case BO_ShrAssign:
15105     case BO_AndAssign:
15106     case BO_XorAssign:
15107     case BO_OrAssign:
15108       // C99 6.6/3 allows assignments within unevaluated subexpressions of
15109       // constant expressions, but they can never be ICEs because an ICE cannot
15110       // contain an lvalue operand.
15111       return ICEDiag(IK_NotICE, E->getBeginLoc());
15112 
15113     case BO_Mul:
15114     case BO_Div:
15115     case BO_Rem:
15116     case BO_Add:
15117     case BO_Sub:
15118     case BO_Shl:
15119     case BO_Shr:
15120     case BO_LT:
15121     case BO_GT:
15122     case BO_LE:
15123     case BO_GE:
15124     case BO_EQ:
15125     case BO_NE:
15126     case BO_And:
15127     case BO_Xor:
15128     case BO_Or:
15129     case BO_Comma:
15130     case BO_Cmp: {
15131       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15132       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15133       if (Exp->getOpcode() == BO_Div ||
15134           Exp->getOpcode() == BO_Rem) {
15135         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15136         // we don't evaluate one.
15137         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15138           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15139           if (REval == 0)
15140             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15141           if (REval.isSigned() && REval.isAllOnesValue()) {
15142             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15143             if (LEval.isMinSignedValue())
15144               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15145           }
15146         }
15147       }
15148       if (Exp->getOpcode() == BO_Comma) {
15149         if (Ctx.getLangOpts().C99) {
15150           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15151           // if it isn't evaluated.
15152           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15153             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15154         } else {
15155           // In both C89 and C++, commas in ICEs are illegal.
15156           return ICEDiag(IK_NotICE, E->getBeginLoc());
15157         }
15158       }
15159       return Worst(LHSResult, RHSResult);
15160     }
15161     case BO_LAnd:
15162     case BO_LOr: {
15163       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15164       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15165       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15166         // Rare case where the RHS has a comma "side-effect"; we need
15167         // to actually check the condition to see whether the side
15168         // with the comma is evaluated.
15169         if ((Exp->getOpcode() == BO_LAnd) !=
15170             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15171           return RHSResult;
15172         return NoDiag();
15173       }
15174 
15175       return Worst(LHSResult, RHSResult);
15176     }
15177     }
15178     llvm_unreachable("invalid binary operator kind");
15179   }
15180   case Expr::ImplicitCastExprClass:
15181   case Expr::CStyleCastExprClass:
15182   case Expr::CXXFunctionalCastExprClass:
15183   case Expr::CXXStaticCastExprClass:
15184   case Expr::CXXReinterpretCastExprClass:
15185   case Expr::CXXConstCastExprClass:
15186   case Expr::ObjCBridgedCastExprClass: {
15187     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15188     if (isa<ExplicitCastExpr>(E)) {
15189       if (const FloatingLiteral *FL
15190             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15191         unsigned DestWidth = Ctx.getIntWidth(E->getType());
15192         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15193         APSInt IgnoredVal(DestWidth, !DestSigned);
15194         bool Ignored;
15195         // If the value does not fit in the destination type, the behavior is
15196         // undefined, so we are not required to treat it as a constant
15197         // expression.
15198         if (FL->getValue().convertToInteger(IgnoredVal,
15199                                             llvm::APFloat::rmTowardZero,
15200                                             &Ignored) & APFloat::opInvalidOp)
15201           return ICEDiag(IK_NotICE, E->getBeginLoc());
15202         return NoDiag();
15203       }
15204     }
15205     switch (cast<CastExpr>(E)->getCastKind()) {
15206     case CK_LValueToRValue:
15207     case CK_AtomicToNonAtomic:
15208     case CK_NonAtomicToAtomic:
15209     case CK_NoOp:
15210     case CK_IntegralToBoolean:
15211     case CK_IntegralCast:
15212       return CheckICE(SubExpr, Ctx);
15213     default:
15214       return ICEDiag(IK_NotICE, E->getBeginLoc());
15215     }
15216   }
15217   case Expr::BinaryConditionalOperatorClass: {
15218     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
15219     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
15220     if (CommonResult.Kind == IK_NotICE) return CommonResult;
15221     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15222     if (FalseResult.Kind == IK_NotICE) return FalseResult;
15223     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15224     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15225         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15226     return FalseResult;
15227   }
15228   case Expr::ConditionalOperatorClass: {
15229     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15230     // If the condition (ignoring parens) is a __builtin_constant_p call,
15231     // then only the true side is actually considered in an integer constant
15232     // expression, and it is fully evaluated.  This is an important GNU
15233     // extension.  See GCC PR38377 for discussion.
15234     if (const CallExpr *CallCE
15235         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15236       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15237         return CheckEvalInICE(E, Ctx);
15238     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15239     if (CondResult.Kind == IK_NotICE)
15240       return CondResult;
15241 
15242     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15243     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15244 
15245     if (TrueResult.Kind == IK_NotICE)
15246       return TrueResult;
15247     if (FalseResult.Kind == IK_NotICE)
15248       return FalseResult;
15249     if (CondResult.Kind == IK_ICEIfUnevaluated)
15250       return CondResult;
15251     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15252       return NoDiag();
15253     // Rare case where the diagnostics depend on which side is evaluated
15254     // Note that if we get here, CondResult is 0, and at least one of
15255     // TrueResult and FalseResult is non-zero.
15256     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15257       return FalseResult;
15258     return TrueResult;
15259   }
15260   case Expr::CXXDefaultArgExprClass:
15261     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15262   case Expr::CXXDefaultInitExprClass:
15263     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15264   case Expr::ChooseExprClass: {
15265     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15266   }
15267   case Expr::BuiltinBitCastExprClass: {
15268     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15269       return ICEDiag(IK_NotICE, E->getBeginLoc());
15270     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15271   }
15272   }
15273 
15274   llvm_unreachable("Invalid StmtClass!");
15275 }
15276 
15277 /// Evaluate an expression as a C++11 integral constant expression.
15278 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15279                                                     const Expr *E,
15280                                                     llvm::APSInt *Value,
15281                                                     SourceLocation *Loc) {
15282   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15283     if (Loc) *Loc = E->getExprLoc();
15284     return false;
15285   }
15286 
15287   APValue Result;
15288   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15289     return false;
15290 
15291   if (!Result.isInt()) {
15292     if (Loc) *Loc = E->getExprLoc();
15293     return false;
15294   }
15295 
15296   if (Value) *Value = Result.getInt();
15297   return true;
15298 }
15299 
15300 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
15301                                  SourceLocation *Loc) const {
15302   assert(!isValueDependent() &&
15303          "Expression evaluator can't be called on a dependent expression.");
15304 
15305   if (Ctx.getLangOpts().CPlusPlus11)
15306     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
15307 
15308   ICEDiag D = CheckICE(this, Ctx);
15309   if (D.Kind != IK_ICE) {
15310     if (Loc) *Loc = D.Loc;
15311     return false;
15312   }
15313   return true;
15314 }
15315 
15316 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx,
15317                                                     SourceLocation *Loc,
15318                                                     bool isEvaluated) const {
15319   assert(!isValueDependent() &&
15320          "Expression evaluator can't be called on a dependent expression.");
15321 
15322   APSInt Value;
15323 
15324   if (Ctx.getLangOpts().CPlusPlus11) {
15325     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
15326       return Value;
15327     return None;
15328   }
15329 
15330   if (!isIntegerConstantExpr(Ctx, Loc))
15331     return None;
15332 
15333   // The only possible side-effects here are due to UB discovered in the
15334   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
15335   // required to treat the expression as an ICE, so we produce the folded
15336   // value.
15337   EvalResult ExprResult;
15338   Expr::EvalStatus Status;
15339   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
15340   Info.InConstantContext = true;
15341 
15342   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
15343     llvm_unreachable("ICE cannot be evaluated!");
15344 
15345   return ExprResult.Val.getInt();
15346 }
15347 
15348 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
15349   assert(!isValueDependent() &&
15350          "Expression evaluator can't be called on a dependent expression.");
15351 
15352   return CheckICE(this, Ctx).Kind == IK_ICE;
15353 }
15354 
15355 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
15356                                SourceLocation *Loc) const {
15357   assert(!isValueDependent() &&
15358          "Expression evaluator can't be called on a dependent expression.");
15359 
15360   // We support this checking in C++98 mode in order to diagnose compatibility
15361   // issues.
15362   assert(Ctx.getLangOpts().CPlusPlus);
15363 
15364   // Build evaluation settings.
15365   Expr::EvalStatus Status;
15366   SmallVector<PartialDiagnosticAt, 8> Diags;
15367   Status.Diag = &Diags;
15368   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15369 
15370   APValue Scratch;
15371   bool IsConstExpr =
15372       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
15373       // FIXME: We don't produce a diagnostic for this, but the callers that
15374       // call us on arbitrary full-expressions should generally not care.
15375       Info.discardCleanups() && !Status.HasSideEffects;
15376 
15377   if (!Diags.empty()) {
15378     IsConstExpr = false;
15379     if (Loc) *Loc = Diags[0].first;
15380   } else if (!IsConstExpr) {
15381     // FIXME: This shouldn't happen.
15382     if (Loc) *Loc = getExprLoc();
15383   }
15384 
15385   return IsConstExpr;
15386 }
15387 
15388 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
15389                                     const FunctionDecl *Callee,
15390                                     ArrayRef<const Expr*> Args,
15391                                     const Expr *This) const {
15392   assert(!isValueDependent() &&
15393          "Expression evaluator can't be called on a dependent expression.");
15394 
15395   Expr::EvalStatus Status;
15396   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
15397   Info.InConstantContext = true;
15398 
15399   LValue ThisVal;
15400   const LValue *ThisPtr = nullptr;
15401   if (This) {
15402 #ifndef NDEBUG
15403     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
15404     assert(MD && "Don't provide `this` for non-methods.");
15405     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
15406 #endif
15407     if (!This->isValueDependent() &&
15408         EvaluateObjectArgument(Info, This, ThisVal) &&
15409         !Info.EvalStatus.HasSideEffects)
15410       ThisPtr = &ThisVal;
15411 
15412     // Ignore any side-effects from a failed evaluation. This is safe because
15413     // they can't interfere with any other argument evaluation.
15414     Info.EvalStatus.HasSideEffects = false;
15415   }
15416 
15417   CallRef Call = Info.CurrentCall->createCall(Callee);
15418   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
15419        I != E; ++I) {
15420     unsigned Idx = I - Args.begin();
15421     if (Idx >= Callee->getNumParams())
15422       break;
15423     const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
15424     if ((*I)->isValueDependent() ||
15425         !EvaluateCallArg(PVD, *I, Call, Info) ||
15426         Info.EvalStatus.HasSideEffects) {
15427       // If evaluation fails, throw away the argument entirely.
15428       if (APValue *Slot = Info.getParamSlot(Call, PVD))
15429         *Slot = APValue();
15430     }
15431 
15432     // Ignore any side-effects from a failed evaluation. This is safe because
15433     // they can't interfere with any other argument evaluation.
15434     Info.EvalStatus.HasSideEffects = false;
15435   }
15436 
15437   // Parameter cleanups happen in the caller and are not part of this
15438   // evaluation.
15439   Info.discardCleanups();
15440   Info.EvalStatus.HasSideEffects = false;
15441 
15442   // Build fake call to Callee.
15443   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
15444   // FIXME: Missing ExprWithCleanups in enable_if conditions?
15445   FullExpressionRAII Scope(Info);
15446   return Evaluate(Value, Info, this) && Scope.destroy() &&
15447          !Info.EvalStatus.HasSideEffects;
15448 }
15449 
15450 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
15451                                    SmallVectorImpl<
15452                                      PartialDiagnosticAt> &Diags) {
15453   // FIXME: It would be useful to check constexpr function templates, but at the
15454   // moment the constant expression evaluator cannot cope with the non-rigorous
15455   // ASTs which we build for dependent expressions.
15456   if (FD->isDependentContext())
15457     return true;
15458 
15459   // Bail out if a constexpr constructor has an initializer that contains an
15460   // error. We deliberately don't produce a diagnostic, as we have produced a
15461   // relevant diagnostic when parsing the error initializer.
15462   if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
15463     for (const auto *InitExpr : Ctor->inits()) {
15464       if (InitExpr->getInit() && InitExpr->getInit()->containsErrors())
15465         return false;
15466     }
15467   }
15468   Expr::EvalStatus Status;
15469   Status.Diag = &Diags;
15470 
15471   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
15472   Info.InConstantContext = true;
15473   Info.CheckingPotentialConstantExpression = true;
15474 
15475   // The constexpr VM attempts to compile all methods to bytecode here.
15476   if (Info.EnableNewConstInterp) {
15477     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
15478     return Diags.empty();
15479   }
15480 
15481   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
15482   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
15483 
15484   // Fabricate an arbitrary expression on the stack and pretend that it
15485   // is a temporary being used as the 'this' pointer.
15486   LValue This;
15487   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
15488   This.set({&VIE, Info.CurrentCall->Index});
15489 
15490   ArrayRef<const Expr*> Args;
15491 
15492   APValue Scratch;
15493   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
15494     // Evaluate the call as a constant initializer, to allow the construction
15495     // of objects of non-literal types.
15496     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
15497     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
15498   } else {
15499     SourceLocation Loc = FD->getLocation();
15500     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
15501                        Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
15502   }
15503 
15504   return Diags.empty();
15505 }
15506 
15507 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
15508                                               const FunctionDecl *FD,
15509                                               SmallVectorImpl<
15510                                                 PartialDiagnosticAt> &Diags) {
15511   assert(!E->isValueDependent() &&
15512          "Expression evaluator can't be called on a dependent expression.");
15513 
15514   Expr::EvalStatus Status;
15515   Status.Diag = &Diags;
15516 
15517   EvalInfo Info(FD->getASTContext(), Status,
15518                 EvalInfo::EM_ConstantExpressionUnevaluated);
15519   Info.InConstantContext = true;
15520   Info.CheckingPotentialConstantExpression = true;
15521 
15522   // Fabricate a call stack frame to give the arguments a plausible cover story.
15523   CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
15524 
15525   APValue ResultScratch;
15526   Evaluate(ResultScratch, Info, E);
15527   return Diags.empty();
15528 }
15529 
15530 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
15531                                  unsigned Type) const {
15532   if (!getType()->isPointerType())
15533     return false;
15534 
15535   Expr::EvalStatus Status;
15536   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15537   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
15538 }
15539