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     return B.getType();
83   }
84 
85   /// Get an LValue path entry, which is known to not be an array index, as a
86   /// field declaration.
87   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
88     return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
89   }
90   /// Get an LValue path entry, which is known to not be an array index, as a
91   /// base class declaration.
92   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
93     return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
94   }
95   /// Determine whether this LValue path entry for a base class names a virtual
96   /// base class.
97   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
98     return E.getAsBaseOrMember().getInt();
99   }
100 
101   /// Given an expression, determine the type used to store the result of
102   /// evaluating that expression.
103   static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
104     if (E->isRValue())
105       return E->getType();
106     return Ctx.getLValueReferenceType(E->getType());
107   }
108 
109   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
110   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
111     const FunctionDecl *Callee = CE->getDirectCallee();
112     return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
113   }
114 
115   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
116   /// This will look through a single cast.
117   ///
118   /// Returns null if we couldn't unwrap a function with alloc_size.
119   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
120     if (!E->getType()->isPointerType())
121       return nullptr;
122 
123     E = E->IgnoreParens();
124     // If we're doing a variable assignment from e.g. malloc(N), there will
125     // probably be a cast of some kind. In exotic cases, we might also see a
126     // top-level ExprWithCleanups. Ignore them either way.
127     if (const auto *FE = dyn_cast<FullExpr>(E))
128       E = FE->getSubExpr()->IgnoreParens();
129 
130     if (const auto *Cast = dyn_cast<CastExpr>(E))
131       E = Cast->getSubExpr()->IgnoreParens();
132 
133     if (const auto *CE = dyn_cast<CallExpr>(E))
134       return getAllocSizeAttr(CE) ? CE : nullptr;
135     return nullptr;
136   }
137 
138   /// Determines whether or not the given Base contains a call to a function
139   /// with the alloc_size attribute.
140   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
141     const auto *E = Base.dyn_cast<const Expr *>();
142     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
143   }
144 
145   /// Determines whether the given kind of constant expression is only ever
146   /// used for name mangling. If so, it's permitted to reference things that we
147   /// can't generate code for (in particular, dllimported functions).
148   static bool isForManglingOnly(ConstantExprKind Kind) {
149     switch (Kind) {
150     case ConstantExprKind::Normal:
151     case ConstantExprKind::ClassTemplateArgument:
152     case ConstantExprKind::ImmediateInvocation:
153       // Note that non-type template arguments of class type are emitted as
154       // template parameter objects.
155       return false;
156 
157     case ConstantExprKind::NonClassTemplateArgument:
158       return true;
159     }
160     llvm_unreachable("unknown ConstantExprKind");
161   }
162 
163   static bool isTemplateArgument(ConstantExprKind Kind) {
164     switch (Kind) {
165     case ConstantExprKind::Normal:
166     case ConstantExprKind::ImmediateInvocation:
167       return false;
168 
169     case ConstantExprKind::ClassTemplateArgument:
170     case ConstantExprKind::NonClassTemplateArgument:
171       return true;
172     }
173     llvm_unreachable("unknown ConstantExprKind");
174   }
175 
176   /// The bound to claim that an array of unknown bound has.
177   /// The value in MostDerivedArraySize is undefined in this case. So, set it
178   /// to an arbitrary value that's likely to loudly break things if it's used.
179   static const uint64_t AssumedSizeForUnsizedArray =
180       std::numeric_limits<uint64_t>::max() / 2;
181 
182   /// Determines if an LValue with the given LValueBase will have an unsized
183   /// array in its designator.
184   /// Find the path length and type of the most-derived subobject in the given
185   /// path, and find the size of the containing array, if any.
186   static unsigned
187   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
188                            ArrayRef<APValue::LValuePathEntry> Path,
189                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
190                            bool &FirstEntryIsUnsizedArray) {
191     // This only accepts LValueBases from APValues, and APValues don't support
192     // arrays that lack size info.
193     assert(!isBaseAnAllocSizeCall(Base) &&
194            "Unsized arrays shouldn't appear here");
195     unsigned MostDerivedLength = 0;
196     Type = getType(Base);
197 
198     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
199       if (Type->isArrayType()) {
200         const ArrayType *AT = Ctx.getAsArrayType(Type);
201         Type = AT->getElementType();
202         MostDerivedLength = I + 1;
203         IsArray = true;
204 
205         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
206           ArraySize = CAT->getSize().getZExtValue();
207         } else {
208           assert(I == 0 && "unexpected unsized array designator");
209           FirstEntryIsUnsizedArray = true;
210           ArraySize = AssumedSizeForUnsizedArray;
211         }
212       } else if (Type->isAnyComplexType()) {
213         const ComplexType *CT = Type->castAs<ComplexType>();
214         Type = CT->getElementType();
215         ArraySize = 2;
216         MostDerivedLength = I + 1;
217         IsArray = true;
218       } else if (const FieldDecl *FD = getAsField(Path[I])) {
219         Type = FD->getType();
220         ArraySize = 0;
221         MostDerivedLength = I + 1;
222         IsArray = false;
223       } else {
224         // Path[I] describes a base class.
225         ArraySize = 0;
226         IsArray = false;
227       }
228     }
229     return MostDerivedLength;
230   }
231 
232   /// A path from a glvalue to a subobject of that glvalue.
233   struct SubobjectDesignator {
234     /// True if the subobject was named in a manner not supported by C++11. Such
235     /// lvalues can still be folded, but they are not core constant expressions
236     /// and we cannot perform lvalue-to-rvalue conversions on them.
237     unsigned Invalid : 1;
238 
239     /// Is this a pointer one past the end of an object?
240     unsigned IsOnePastTheEnd : 1;
241 
242     /// Indicator of whether the first entry is an unsized array.
243     unsigned FirstEntryIsAnUnsizedArray : 1;
244 
245     /// Indicator of whether the most-derived object is an array element.
246     unsigned MostDerivedIsArrayElement : 1;
247 
248     /// The length of the path to the most-derived object of which this is a
249     /// subobject.
250     unsigned MostDerivedPathLength : 28;
251 
252     /// The size of the array of which the most-derived object is an element.
253     /// This will always be 0 if the most-derived object is not an array
254     /// element. 0 is not an indicator of whether or not the most-derived object
255     /// is an array, however, because 0-length arrays are allowed.
256     ///
257     /// If the current array is an unsized array, the value of this is
258     /// undefined.
259     uint64_t MostDerivedArraySize;
260 
261     /// The type of the most derived object referred to by this address.
262     QualType MostDerivedType;
263 
264     typedef APValue::LValuePathEntry PathEntry;
265 
266     /// The entries on the path from the glvalue to the designated subobject.
267     SmallVector<PathEntry, 8> Entries;
268 
269     SubobjectDesignator() : Invalid(true) {}
270 
271     explicit SubobjectDesignator(QualType T)
272         : Invalid(false), IsOnePastTheEnd(false),
273           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
274           MostDerivedPathLength(0), MostDerivedArraySize(0),
275           MostDerivedType(T) {}
276 
277     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
278         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
279           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
280           MostDerivedPathLength(0), MostDerivedArraySize(0) {
281       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
282       if (!Invalid) {
283         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
284         ArrayRef<PathEntry> VEntries = V.getLValuePath();
285         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
286         if (V.getLValueBase()) {
287           bool IsArray = false;
288           bool FirstIsUnsizedArray = false;
289           MostDerivedPathLength = findMostDerivedSubobject(
290               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
291               MostDerivedType, IsArray, FirstIsUnsizedArray);
292           MostDerivedIsArrayElement = IsArray;
293           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
294         }
295       }
296     }
297 
298     void truncate(ASTContext &Ctx, APValue::LValueBase Base,
299                   unsigned NewLength) {
300       if (Invalid)
301         return;
302 
303       assert(Base && "cannot truncate path for null pointer");
304       assert(NewLength <= Entries.size() && "not a truncation");
305 
306       if (NewLength == Entries.size())
307         return;
308       Entries.resize(NewLength);
309 
310       bool IsArray = false;
311       bool FirstIsUnsizedArray = false;
312       MostDerivedPathLength = findMostDerivedSubobject(
313           Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
314           FirstIsUnsizedArray);
315       MostDerivedIsArrayElement = IsArray;
316       FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
317     }
318 
319     void setInvalid() {
320       Invalid = true;
321       Entries.clear();
322     }
323 
324     /// Determine whether the most derived subobject is an array without a
325     /// known bound.
326     bool isMostDerivedAnUnsizedArray() const {
327       assert(!Invalid && "Calling this makes no sense on invalid designators");
328       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
329     }
330 
331     /// Determine what the most derived array's size is. Results in an assertion
332     /// failure if the most derived array lacks a size.
333     uint64_t getMostDerivedArraySize() const {
334       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
335       return MostDerivedArraySize;
336     }
337 
338     /// Determine whether this is a one-past-the-end pointer.
339     bool isOnePastTheEnd() const {
340       assert(!Invalid);
341       if (IsOnePastTheEnd)
342         return true;
343       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
344           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
345               MostDerivedArraySize)
346         return true;
347       return false;
348     }
349 
350     /// Get the range of valid index adjustments in the form
351     ///   {maximum value that can be subtracted from this pointer,
352     ///    maximum value that can be added to this pointer}
353     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
354       if (Invalid || isMostDerivedAnUnsizedArray())
355         return {0, 0};
356 
357       // [expr.add]p4: For the purposes of these operators, a pointer to a
358       // nonarray object behaves the same as a pointer to the first element of
359       // an array of length one with the type of the object as its element type.
360       bool IsArray = MostDerivedPathLength == Entries.size() &&
361                      MostDerivedIsArrayElement;
362       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
363                                     : (uint64_t)IsOnePastTheEnd;
364       uint64_t ArraySize =
365           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
366       return {ArrayIndex, ArraySize - ArrayIndex};
367     }
368 
369     /// Check that this refers to a valid subobject.
370     bool isValidSubobject() const {
371       if (Invalid)
372         return false;
373       return !isOnePastTheEnd();
374     }
375     /// Check that this refers to a valid subobject, and if not, produce a
376     /// relevant diagnostic and set the designator as invalid.
377     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
378 
379     /// Get the type of the designated object.
380     QualType getType(ASTContext &Ctx) const {
381       assert(!Invalid && "invalid designator has no subobject type");
382       return MostDerivedPathLength == Entries.size()
383                  ? MostDerivedType
384                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
385     }
386 
387     /// Update this designator to refer to the first element within this array.
388     void addArrayUnchecked(const ConstantArrayType *CAT) {
389       Entries.push_back(PathEntry::ArrayIndex(0));
390 
391       // This is a most-derived object.
392       MostDerivedType = CAT->getElementType();
393       MostDerivedIsArrayElement = true;
394       MostDerivedArraySize = CAT->getSize().getZExtValue();
395       MostDerivedPathLength = Entries.size();
396     }
397     /// Update this designator to refer to the first element within the array of
398     /// elements of type T. This is an array of unknown size.
399     void addUnsizedArrayUnchecked(QualType ElemTy) {
400       Entries.push_back(PathEntry::ArrayIndex(0));
401 
402       MostDerivedType = ElemTy;
403       MostDerivedIsArrayElement = true;
404       // The value in MostDerivedArraySize is undefined in this case. So, set it
405       // to an arbitrary value that's likely to loudly break things if it's
406       // used.
407       MostDerivedArraySize = AssumedSizeForUnsizedArray;
408       MostDerivedPathLength = Entries.size();
409     }
410     /// Update this designator to refer to the given base or member of this
411     /// object.
412     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
413       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
414 
415       // If this isn't a base class, it's a new most-derived object.
416       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
417         MostDerivedType = FD->getType();
418         MostDerivedIsArrayElement = false;
419         MostDerivedArraySize = 0;
420         MostDerivedPathLength = Entries.size();
421       }
422     }
423     /// Update this designator to refer to the given complex component.
424     void addComplexUnchecked(QualType EltTy, bool Imag) {
425       Entries.push_back(PathEntry::ArrayIndex(Imag));
426 
427       // This is technically a most-derived object, though in practice this
428       // is unlikely to matter.
429       MostDerivedType = EltTy;
430       MostDerivedIsArrayElement = true;
431       MostDerivedArraySize = 2;
432       MostDerivedPathLength = Entries.size();
433     }
434     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
435     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
436                                    const APSInt &N);
437     /// Add N to the address of this subobject.
438     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
439       if (Invalid || !N) return;
440       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
441       if (isMostDerivedAnUnsizedArray()) {
442         diagnoseUnsizedArrayPointerArithmetic(Info, E);
443         // Can't verify -- trust that the user is doing the right thing (or if
444         // not, trust that the caller will catch the bad behavior).
445         // FIXME: Should we reject if this overflows, at least?
446         Entries.back() = PathEntry::ArrayIndex(
447             Entries.back().getAsArrayIndex() + TruncatedN);
448         return;
449       }
450 
451       // [expr.add]p4: For the purposes of these operators, a pointer to a
452       // nonarray object behaves the same as a pointer to the first element of
453       // an array of length one with the type of the object as its element type.
454       bool IsArray = MostDerivedPathLength == Entries.size() &&
455                      MostDerivedIsArrayElement;
456       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
457                                     : (uint64_t)IsOnePastTheEnd;
458       uint64_t ArraySize =
459           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
460 
461       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
462         // Calculate the actual index in a wide enough type, so we can include
463         // it in the note.
464         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
465         (llvm::APInt&)N += ArrayIndex;
466         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
467         diagnosePointerArithmetic(Info, E, N);
468         setInvalid();
469         return;
470       }
471 
472       ArrayIndex += TruncatedN;
473       assert(ArrayIndex <= ArraySize &&
474              "bounds check succeeded for out-of-bounds index");
475 
476       if (IsArray)
477         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
478       else
479         IsOnePastTheEnd = (ArrayIndex != 0);
480     }
481   };
482 
483   /// A scope at the end of which an object can need to be destroyed.
484   enum class ScopeKind {
485     Block,
486     FullExpression,
487     Call
488   };
489 
490   /// A reference to a particular call and its arguments.
491   struct CallRef {
492     CallRef() : OrigCallee(), CallIndex(0), Version() {}
493     CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
494         : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
495 
496     explicit operator bool() const { return OrigCallee; }
497 
498     /// Get the parameter that the caller initialized, corresponding to the
499     /// given parameter in the callee.
500     const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
501       return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
502                         : PVD;
503     }
504 
505     /// The callee at the point where the arguments were evaluated. This might
506     /// be different from the actual callee (a different redeclaration, or a
507     /// virtual override), but this function's parameters are the ones that
508     /// appear in the parameter map.
509     const FunctionDecl *OrigCallee;
510     /// The call index of the frame that holds the argument values.
511     unsigned CallIndex;
512     /// The version of the parameters corresponding to this call.
513     unsigned Version;
514   };
515 
516   /// A stack frame in the constexpr call stack.
517   class CallStackFrame : public interp::Frame {
518   public:
519     EvalInfo &Info;
520 
521     /// Parent - The caller of this stack frame.
522     CallStackFrame *Caller;
523 
524     /// Callee - The function which was called.
525     const FunctionDecl *Callee;
526 
527     /// This - The binding for the this pointer in this call, if any.
528     const LValue *This;
529 
530     /// Information on how to find the arguments to this call. Our arguments
531     /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
532     /// key and this value as the version.
533     CallRef Arguments;
534 
535     /// Source location information about the default argument or default
536     /// initializer expression we're evaluating, if any.
537     CurrentSourceLocExprScope CurSourceLocExprScope;
538 
539     // Note that we intentionally use std::map here so that references to
540     // values are stable.
541     typedef std::pair<const void *, unsigned> MapKeyTy;
542     typedef std::map<MapKeyTy, APValue> MapTy;
543     /// Temporaries - Temporary lvalues materialized within this stack frame.
544     MapTy Temporaries;
545 
546     /// CallLoc - The location of the call expression for this call.
547     SourceLocation CallLoc;
548 
549     /// Index - The call index of this call.
550     unsigned Index;
551 
552     /// The stack of integers for tracking version numbers for temporaries.
553     SmallVector<unsigned, 2> TempVersionStack = {1};
554     unsigned CurTempVersion = TempVersionStack.back();
555 
556     unsigned getTempVersion() const { return TempVersionStack.back(); }
557 
558     void pushTempVersion() {
559       TempVersionStack.push_back(++CurTempVersion);
560     }
561 
562     void popTempVersion() {
563       TempVersionStack.pop_back();
564     }
565 
566     CallRef createCall(const FunctionDecl *Callee) {
567       return {Callee, Index, ++CurTempVersion};
568     }
569 
570     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
571     // on the overall stack usage of deeply-recursing constexpr evaluations.
572     // (We should cache this map rather than recomputing it repeatedly.)
573     // But let's try this and see how it goes; we can look into caching the map
574     // as a later change.
575 
576     /// LambdaCaptureFields - Mapping from captured variables/this to
577     /// corresponding data members in the closure class.
578     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
579     FieldDecl *LambdaThisCaptureField;
580 
581     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
582                    const FunctionDecl *Callee, const LValue *This,
583                    CallRef Arguments);
584     ~CallStackFrame();
585 
586     // Return the temporary for Key whose version number is Version.
587     APValue *getTemporary(const void *Key, unsigned Version) {
588       MapKeyTy KV(Key, Version);
589       auto LB = Temporaries.lower_bound(KV);
590       if (LB != Temporaries.end() && LB->first == KV)
591         return &LB->second;
592       // Pair (Key,Version) wasn't found in the map. Check that no elements
593       // in the map have 'Key' as their key.
594       assert((LB == Temporaries.end() || LB->first.first != Key) &&
595              (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
596              "Element with key 'Key' found in map");
597       return nullptr;
598     }
599 
600     // Return the current temporary for Key in the map.
601     APValue *getCurrentTemporary(const void *Key) {
602       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
603       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
604         return &std::prev(UB)->second;
605       return nullptr;
606     }
607 
608     // Return the version number of the current temporary for Key.
609     unsigned getCurrentTemporaryVersion(const void *Key) const {
610       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
611       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
612         return std::prev(UB)->first.second;
613       return 0;
614     }
615 
616     /// Allocate storage for an object of type T in this stack frame.
617     /// Populates LV with a handle to the created object. Key identifies
618     /// the temporary within the stack frame, and must not be reused without
619     /// bumping the temporary version number.
620     template<typename KeyT>
621     APValue &createTemporary(const KeyT *Key, QualType T,
622                              ScopeKind Scope, LValue &LV);
623 
624     /// Allocate storage for a parameter of a function call made in this frame.
625     APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
626 
627     void describe(llvm::raw_ostream &OS) override;
628 
629     Frame *getCaller() const override { return Caller; }
630     SourceLocation getCallLocation() const override { return CallLoc; }
631     const FunctionDecl *getCallee() const override { return Callee; }
632 
633     bool isStdFunction() const {
634       for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
635         if (DC->isStdNamespace())
636           return true;
637       return false;
638     }
639 
640   private:
641     APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
642                          ScopeKind Scope);
643   };
644 
645   /// Temporarily override 'this'.
646   class ThisOverrideRAII {
647   public:
648     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
649         : Frame(Frame), OldThis(Frame.This) {
650       if (Enable)
651         Frame.This = NewThis;
652     }
653     ~ThisOverrideRAII() {
654       Frame.This = OldThis;
655     }
656   private:
657     CallStackFrame &Frame;
658     const LValue *OldThis;
659   };
660 }
661 
662 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
663                               const LValue &This, QualType ThisType);
664 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
665                               APValue::LValueBase LVBase, APValue &Value,
666                               QualType T);
667 
668 namespace {
669   /// A cleanup, and a flag indicating whether it is lifetime-extended.
670   class Cleanup {
671     llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
672     APValue::LValueBase Base;
673     QualType T;
674 
675   public:
676     Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
677             ScopeKind Scope)
678         : Value(Val, Scope), Base(Base), T(T) {}
679 
680     /// Determine whether this cleanup should be performed at the end of the
681     /// given kind of scope.
682     bool isDestroyedAtEndOf(ScopeKind K) const {
683       return (int)Value.getInt() >= (int)K;
684     }
685     bool endLifetime(EvalInfo &Info, bool RunDestructors) {
686       if (RunDestructors) {
687         SourceLocation Loc;
688         if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
689           Loc = VD->getLocation();
690         else if (const Expr *E = Base.dyn_cast<const Expr*>())
691           Loc = E->getExprLoc();
692         return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
693       }
694       *Value.getPointer() = APValue();
695       return true;
696     }
697 
698     bool hasSideEffect() {
699       return T.isDestructedType();
700     }
701   };
702 
703   /// A reference to an object whose construction we are currently evaluating.
704   struct ObjectUnderConstruction {
705     APValue::LValueBase Base;
706     ArrayRef<APValue::LValuePathEntry> Path;
707     friend bool operator==(const ObjectUnderConstruction &LHS,
708                            const ObjectUnderConstruction &RHS) {
709       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
710     }
711     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
712       return llvm::hash_combine(Obj.Base, Obj.Path);
713     }
714   };
715   enum class ConstructionPhase {
716     None,
717     Bases,
718     AfterBases,
719     AfterFields,
720     Destroying,
721     DestroyingBases
722   };
723 }
724 
725 namespace llvm {
726 template<> struct DenseMapInfo<ObjectUnderConstruction> {
727   using Base = DenseMapInfo<APValue::LValueBase>;
728   static ObjectUnderConstruction getEmptyKey() {
729     return {Base::getEmptyKey(), {}}; }
730   static ObjectUnderConstruction getTombstoneKey() {
731     return {Base::getTombstoneKey(), {}};
732   }
733   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
734     return hash_value(Object);
735   }
736   static bool isEqual(const ObjectUnderConstruction &LHS,
737                       const ObjectUnderConstruction &RHS) {
738     return LHS == RHS;
739   }
740 };
741 }
742 
743 namespace {
744   /// A dynamically-allocated heap object.
745   struct DynAlloc {
746     /// The value of this heap-allocated object.
747     APValue Value;
748     /// The allocating expression; used for diagnostics. Either a CXXNewExpr
749     /// or a CallExpr (the latter is for direct calls to operator new inside
750     /// std::allocator<T>::allocate).
751     const Expr *AllocExpr = nullptr;
752 
753     enum Kind {
754       New,
755       ArrayNew,
756       StdAllocator
757     };
758 
759     /// Get the kind of the allocation. This must match between allocation
760     /// and deallocation.
761     Kind getKind() const {
762       if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
763         return NE->isArray() ? ArrayNew : New;
764       assert(isa<CallExpr>(AllocExpr));
765       return StdAllocator;
766     }
767   };
768 
769   struct DynAllocOrder {
770     bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
771       return L.getIndex() < R.getIndex();
772     }
773   };
774 
775   /// EvalInfo - This is a private struct used by the evaluator to capture
776   /// information about a subexpression as it is folded.  It retains information
777   /// about the AST context, but also maintains information about the folded
778   /// expression.
779   ///
780   /// If an expression could be evaluated, it is still possible it is not a C
781   /// "integer constant expression" or constant expression.  If not, this struct
782   /// captures information about how and why not.
783   ///
784   /// One bit of information passed *into* the request for constant folding
785   /// indicates whether the subexpression is "evaluated" or not according to C
786   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
787   /// evaluate the expression regardless of what the RHS is, but C only allows
788   /// certain things in certain situations.
789   class EvalInfo : public interp::State {
790   public:
791     ASTContext &Ctx;
792 
793     /// EvalStatus - Contains information about the evaluation.
794     Expr::EvalStatus &EvalStatus;
795 
796     /// CurrentCall - The top of the constexpr call stack.
797     CallStackFrame *CurrentCall;
798 
799     /// CallStackDepth - The number of calls in the call stack right now.
800     unsigned CallStackDepth;
801 
802     /// NextCallIndex - The next call index to assign.
803     unsigned NextCallIndex;
804 
805     /// StepsLeft - The remaining number of evaluation steps we're permitted
806     /// to perform. This is essentially a limit for the number of statements
807     /// we will evaluate.
808     unsigned StepsLeft;
809 
810     /// Enable the experimental new constant interpreter. If an expression is
811     /// not supported by the interpreter, an error is triggered.
812     bool EnableNewConstInterp;
813 
814     /// BottomFrame - The frame in which evaluation started. This must be
815     /// initialized after CurrentCall and CallStackDepth.
816     CallStackFrame BottomFrame;
817 
818     /// A stack of values whose lifetimes end at the end of some surrounding
819     /// evaluation frame.
820     llvm::SmallVector<Cleanup, 16> CleanupStack;
821 
822     /// EvaluatingDecl - This is the declaration whose initializer is being
823     /// evaluated, if any.
824     APValue::LValueBase EvaluatingDecl;
825 
826     enum class EvaluatingDeclKind {
827       None,
828       /// We're evaluating the construction of EvaluatingDecl.
829       Ctor,
830       /// We're evaluating the destruction of EvaluatingDecl.
831       Dtor,
832     };
833     EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
834 
835     /// EvaluatingDeclValue - This is the value being constructed for the
836     /// declaration whose initializer is being evaluated, if any.
837     APValue *EvaluatingDeclValue;
838 
839     /// Set of objects that are currently being constructed.
840     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
841         ObjectsUnderConstruction;
842 
843     /// Current heap allocations, along with the location where each was
844     /// allocated. We use std::map here because we need stable addresses
845     /// for the stored APValues.
846     std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
847 
848     /// The number of heap allocations performed so far in this evaluation.
849     unsigned NumHeapAllocs = 0;
850 
851     struct EvaluatingConstructorRAII {
852       EvalInfo &EI;
853       ObjectUnderConstruction Object;
854       bool DidInsert;
855       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
856                                 bool HasBases)
857           : EI(EI), Object(Object) {
858         DidInsert =
859             EI.ObjectsUnderConstruction
860                 .insert({Object, HasBases ? ConstructionPhase::Bases
861                                           : ConstructionPhase::AfterBases})
862                 .second;
863       }
864       void finishedConstructingBases() {
865         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
866       }
867       void finishedConstructingFields() {
868         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
869       }
870       ~EvaluatingConstructorRAII() {
871         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
872       }
873     };
874 
875     struct EvaluatingDestructorRAII {
876       EvalInfo &EI;
877       ObjectUnderConstruction Object;
878       bool DidInsert;
879       EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
880           : EI(EI), Object(Object) {
881         DidInsert = EI.ObjectsUnderConstruction
882                         .insert({Object, ConstructionPhase::Destroying})
883                         .second;
884       }
885       void startedDestroyingBases() {
886         EI.ObjectsUnderConstruction[Object] =
887             ConstructionPhase::DestroyingBases;
888       }
889       ~EvaluatingDestructorRAII() {
890         if (DidInsert)
891           EI.ObjectsUnderConstruction.erase(Object);
892       }
893     };
894 
895     ConstructionPhase
896     isEvaluatingCtorDtor(APValue::LValueBase Base,
897                          ArrayRef<APValue::LValuePathEntry> Path) {
898       return ObjectsUnderConstruction.lookup({Base, Path});
899     }
900 
901     /// If we're currently speculatively evaluating, the outermost call stack
902     /// depth at which we can mutate state, otherwise 0.
903     unsigned SpeculativeEvaluationDepth = 0;
904 
905     /// The current array initialization index, if we're performing array
906     /// initialization.
907     uint64_t ArrayInitIndex = -1;
908 
909     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
910     /// notes attached to it will also be stored, otherwise they will not be.
911     bool HasActiveDiagnostic;
912 
913     /// Have we emitted a diagnostic explaining why we couldn't constant
914     /// fold (not just why it's not strictly a constant expression)?
915     bool HasFoldFailureDiagnostic;
916 
917     /// Whether or not we're in a context where the front end requires a
918     /// constant value.
919     bool InConstantContext;
920 
921     /// Whether we're checking that an expression is a potential constant
922     /// expression. If so, do not fail on constructs that could become constant
923     /// later on (such as a use of an undefined global).
924     bool CheckingPotentialConstantExpression = false;
925 
926     /// Whether we're checking for an expression that has undefined behavior.
927     /// If so, we will produce warnings if we encounter an operation that is
928     /// always undefined.
929     bool CheckingForUndefinedBehavior = false;
930 
931     enum EvaluationMode {
932       /// Evaluate as a constant expression. Stop if we find that the expression
933       /// is not a constant expression.
934       EM_ConstantExpression,
935 
936       /// Evaluate as a constant expression. Stop if we find that the expression
937       /// is not a constant expression. Some expressions can be retried in the
938       /// optimizer if we don't constant fold them here, but in an unevaluated
939       /// context we try to fold them immediately since the optimizer never
940       /// gets a chance to look at it.
941       EM_ConstantExpressionUnevaluated,
942 
943       /// Fold the expression to a constant. Stop if we hit a side-effect that
944       /// we can't model.
945       EM_ConstantFold,
946 
947       /// Evaluate in any way we know how. Don't worry about side-effects that
948       /// can't be modeled.
949       EM_IgnoreSideEffects,
950     } EvalMode;
951 
952     /// Are we checking whether the expression is a potential constant
953     /// expression?
954     bool checkingPotentialConstantExpression() const override  {
955       return CheckingPotentialConstantExpression;
956     }
957 
958     /// Are we checking an expression for overflow?
959     // FIXME: We should check for any kind of undefined or suspicious behavior
960     // in such constructs, not just overflow.
961     bool checkingForUndefinedBehavior() const override {
962       return CheckingForUndefinedBehavior;
963     }
964 
965     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
966         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
967           CallStackDepth(0), NextCallIndex(1),
968           StepsLeft(C.getLangOpts().ConstexprStepLimit),
969           EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
970           BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()),
971           EvaluatingDecl((const ValueDecl *)nullptr),
972           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
973           HasFoldFailureDiagnostic(false), InConstantContext(false),
974           EvalMode(Mode) {}
975 
976     ~EvalInfo() {
977       discardCleanups();
978     }
979 
980     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
981                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
982       EvaluatingDecl = Base;
983       IsEvaluatingDecl = EDK;
984       EvaluatingDeclValue = &Value;
985     }
986 
987     bool CheckCallLimit(SourceLocation Loc) {
988       // Don't perform any constexpr calls (other than the call we're checking)
989       // when checking a potential constant expression.
990       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
991         return false;
992       if (NextCallIndex == 0) {
993         // NextCallIndex has wrapped around.
994         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
995         return false;
996       }
997       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
998         return true;
999       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1000         << getLangOpts().ConstexprCallDepth;
1001       return false;
1002     }
1003 
1004     std::pair<CallStackFrame *, unsigned>
1005     getCallFrameAndDepth(unsigned CallIndex) {
1006       assert(CallIndex && "no call index in getCallFrameAndDepth");
1007       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1008       // be null in this loop.
1009       unsigned Depth = CallStackDepth;
1010       CallStackFrame *Frame = CurrentCall;
1011       while (Frame->Index > CallIndex) {
1012         Frame = Frame->Caller;
1013         --Depth;
1014       }
1015       if (Frame->Index == CallIndex)
1016         return {Frame, Depth};
1017       return {nullptr, 0};
1018     }
1019 
1020     bool nextStep(const Stmt *S) {
1021       if (!StepsLeft) {
1022         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1023         return false;
1024       }
1025       --StepsLeft;
1026       return true;
1027     }
1028 
1029     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1030 
1031     Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
1032       Optional<DynAlloc*> Result;
1033       auto It = HeapAllocs.find(DA);
1034       if (It != HeapAllocs.end())
1035         Result = &It->second;
1036       return Result;
1037     }
1038 
1039     /// Get the allocated storage for the given parameter of the given call.
1040     APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1041       CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1042       return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1043                    : nullptr;
1044     }
1045 
1046     /// Information about a stack frame for std::allocator<T>::[de]allocate.
1047     struct StdAllocatorCaller {
1048       unsigned FrameIndex;
1049       QualType ElemType;
1050       explicit operator bool() const { return FrameIndex != 0; };
1051     };
1052 
1053     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1054       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1055            Call = Call->Caller) {
1056         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1057         if (!MD)
1058           continue;
1059         const IdentifierInfo *FnII = MD->getIdentifier();
1060         if (!FnII || !FnII->isStr(FnName))
1061           continue;
1062 
1063         const auto *CTSD =
1064             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1065         if (!CTSD)
1066           continue;
1067 
1068         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1069         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1070         if (CTSD->isInStdNamespace() && ClassII &&
1071             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1072             TAL[0].getKind() == TemplateArgument::Type)
1073           return {Call->Index, TAL[0].getAsType()};
1074       }
1075 
1076       return {};
1077     }
1078 
1079     void performLifetimeExtension() {
1080       // Disable the cleanups for lifetime-extended temporaries.
1081       CleanupStack.erase(std::remove_if(CleanupStack.begin(),
1082                                         CleanupStack.end(),
1083                                         [](Cleanup &C) {
1084                                           return !C.isDestroyedAtEndOf(
1085                                               ScopeKind::FullExpression);
1086                                         }),
1087                          CleanupStack.end());
1088      }
1089 
1090     /// Throw away any remaining cleanups at the end of evaluation. If any
1091     /// cleanups would have had a side-effect, note that as an unmodeled
1092     /// side-effect and return false. Otherwise, return true.
1093     bool discardCleanups() {
1094       for (Cleanup &C : CleanupStack) {
1095         if (C.hasSideEffect() && !noteSideEffect()) {
1096           CleanupStack.clear();
1097           return false;
1098         }
1099       }
1100       CleanupStack.clear();
1101       return true;
1102     }
1103 
1104   private:
1105     interp::Frame *getCurrentFrame() override { return CurrentCall; }
1106     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1107 
1108     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1109     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1110 
1111     void setFoldFailureDiagnostic(bool Flag) override {
1112       HasFoldFailureDiagnostic = Flag;
1113     }
1114 
1115     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1116 
1117     ASTContext &getCtx() const override { return Ctx; }
1118 
1119     // If we have a prior diagnostic, it will be noting that the expression
1120     // isn't a constant expression. This diagnostic is more important,
1121     // unless we require this evaluation to produce a constant expression.
1122     //
1123     // FIXME: We might want to show both diagnostics to the user in
1124     // EM_ConstantFold mode.
1125     bool hasPriorDiagnostic() override {
1126       if (!EvalStatus.Diag->empty()) {
1127         switch (EvalMode) {
1128         case EM_ConstantFold:
1129         case EM_IgnoreSideEffects:
1130           if (!HasFoldFailureDiagnostic)
1131             break;
1132           // We've already failed to fold something. Keep that diagnostic.
1133           LLVM_FALLTHROUGH;
1134         case EM_ConstantExpression:
1135         case EM_ConstantExpressionUnevaluated:
1136           setActiveDiagnostic(false);
1137           return true;
1138         }
1139       }
1140       return false;
1141     }
1142 
1143     unsigned getCallStackDepth() override { return CallStackDepth; }
1144 
1145   public:
1146     /// Should we continue evaluation after encountering a side-effect that we
1147     /// couldn't model?
1148     bool keepEvaluatingAfterSideEffect() {
1149       switch (EvalMode) {
1150       case EM_IgnoreSideEffects:
1151         return true;
1152 
1153       case EM_ConstantExpression:
1154       case EM_ConstantExpressionUnevaluated:
1155       case EM_ConstantFold:
1156         // By default, assume any side effect might be valid in some other
1157         // evaluation of this expression from a different context.
1158         return checkingPotentialConstantExpression() ||
1159                checkingForUndefinedBehavior();
1160       }
1161       llvm_unreachable("Missed EvalMode case");
1162     }
1163 
1164     /// Note that we have had a side-effect, and determine whether we should
1165     /// keep evaluating.
1166     bool noteSideEffect() {
1167       EvalStatus.HasSideEffects = true;
1168       return keepEvaluatingAfterSideEffect();
1169     }
1170 
1171     /// Should we continue evaluation after encountering undefined behavior?
1172     bool keepEvaluatingAfterUndefinedBehavior() {
1173       switch (EvalMode) {
1174       case EM_IgnoreSideEffects:
1175       case EM_ConstantFold:
1176         return true;
1177 
1178       case EM_ConstantExpression:
1179       case EM_ConstantExpressionUnevaluated:
1180         return checkingForUndefinedBehavior();
1181       }
1182       llvm_unreachable("Missed EvalMode case");
1183     }
1184 
1185     /// Note that we hit something that was technically undefined behavior, but
1186     /// that we can evaluate past it (such as signed overflow or floating-point
1187     /// division by zero.)
1188     bool noteUndefinedBehavior() override {
1189       EvalStatus.HasUndefinedBehavior = true;
1190       return keepEvaluatingAfterUndefinedBehavior();
1191     }
1192 
1193     /// Should we continue evaluation as much as possible after encountering a
1194     /// construct which can't be reduced to a value?
1195     bool keepEvaluatingAfterFailure() const override {
1196       if (!StepsLeft)
1197         return false;
1198 
1199       switch (EvalMode) {
1200       case EM_ConstantExpression:
1201       case EM_ConstantExpressionUnevaluated:
1202       case EM_ConstantFold:
1203       case EM_IgnoreSideEffects:
1204         return checkingPotentialConstantExpression() ||
1205                checkingForUndefinedBehavior();
1206       }
1207       llvm_unreachable("Missed EvalMode case");
1208     }
1209 
1210     /// Notes that we failed to evaluate an expression that other expressions
1211     /// directly depend on, and determine if we should keep evaluating. This
1212     /// should only be called if we actually intend to keep evaluating.
1213     ///
1214     /// Call noteSideEffect() instead if we may be able to ignore the value that
1215     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1216     ///
1217     /// (Foo(), 1)      // use noteSideEffect
1218     /// (Foo() || true) // use noteSideEffect
1219     /// Foo() + 1       // use noteFailure
1220     LLVM_NODISCARD bool noteFailure() {
1221       // Failure when evaluating some expression often means there is some
1222       // subexpression whose evaluation was skipped. Therefore, (because we
1223       // don't track whether we skipped an expression when unwinding after an
1224       // evaluation failure) every evaluation failure that bubbles up from a
1225       // subexpression implies that a side-effect has potentially happened. We
1226       // skip setting the HasSideEffects flag to true until we decide to
1227       // continue evaluating after that point, which happens here.
1228       bool KeepGoing = keepEvaluatingAfterFailure();
1229       EvalStatus.HasSideEffects |= KeepGoing;
1230       return KeepGoing;
1231     }
1232 
1233     class ArrayInitLoopIndex {
1234       EvalInfo &Info;
1235       uint64_t OuterIndex;
1236 
1237     public:
1238       ArrayInitLoopIndex(EvalInfo &Info)
1239           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1240         Info.ArrayInitIndex = 0;
1241       }
1242       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1243 
1244       operator uint64_t&() { return Info.ArrayInitIndex; }
1245     };
1246   };
1247 
1248   /// Object used to treat all foldable expressions as constant expressions.
1249   struct FoldConstant {
1250     EvalInfo &Info;
1251     bool Enabled;
1252     bool HadNoPriorDiags;
1253     EvalInfo::EvaluationMode OldMode;
1254 
1255     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1256       : Info(Info),
1257         Enabled(Enabled),
1258         HadNoPriorDiags(Info.EvalStatus.Diag &&
1259                         Info.EvalStatus.Diag->empty() &&
1260                         !Info.EvalStatus.HasSideEffects),
1261         OldMode(Info.EvalMode) {
1262       if (Enabled)
1263         Info.EvalMode = EvalInfo::EM_ConstantFold;
1264     }
1265     void keepDiagnostics() { Enabled = false; }
1266     ~FoldConstant() {
1267       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1268           !Info.EvalStatus.HasSideEffects)
1269         Info.EvalStatus.Diag->clear();
1270       Info.EvalMode = OldMode;
1271     }
1272   };
1273 
1274   /// RAII object used to set the current evaluation mode to ignore
1275   /// side-effects.
1276   struct IgnoreSideEffectsRAII {
1277     EvalInfo &Info;
1278     EvalInfo::EvaluationMode OldMode;
1279     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1280         : Info(Info), OldMode(Info.EvalMode) {
1281       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1282     }
1283 
1284     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1285   };
1286 
1287   /// RAII object used to optionally suppress diagnostics and side-effects from
1288   /// a speculative evaluation.
1289   class SpeculativeEvaluationRAII {
1290     EvalInfo *Info = nullptr;
1291     Expr::EvalStatus OldStatus;
1292     unsigned OldSpeculativeEvaluationDepth;
1293 
1294     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1295       Info = Other.Info;
1296       OldStatus = Other.OldStatus;
1297       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1298       Other.Info = nullptr;
1299     }
1300 
1301     void maybeRestoreState() {
1302       if (!Info)
1303         return;
1304 
1305       Info->EvalStatus = OldStatus;
1306       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1307     }
1308 
1309   public:
1310     SpeculativeEvaluationRAII() = default;
1311 
1312     SpeculativeEvaluationRAII(
1313         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1314         : Info(&Info), OldStatus(Info.EvalStatus),
1315           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1316       Info.EvalStatus.Diag = NewDiag;
1317       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1318     }
1319 
1320     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1321     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1322       moveFromAndCancel(std::move(Other));
1323     }
1324 
1325     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1326       maybeRestoreState();
1327       moveFromAndCancel(std::move(Other));
1328       return *this;
1329     }
1330 
1331     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1332   };
1333 
1334   /// RAII object wrapping a full-expression or block scope, and handling
1335   /// the ending of the lifetime of temporaries created within it.
1336   template<ScopeKind Kind>
1337   class ScopeRAII {
1338     EvalInfo &Info;
1339     unsigned OldStackSize;
1340   public:
1341     ScopeRAII(EvalInfo &Info)
1342         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1343       // Push a new temporary version. This is needed to distinguish between
1344       // temporaries created in different iterations of a loop.
1345       Info.CurrentCall->pushTempVersion();
1346     }
1347     bool destroy(bool RunDestructors = true) {
1348       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1349       OldStackSize = -1U;
1350       return OK;
1351     }
1352     ~ScopeRAII() {
1353       if (OldStackSize != -1U)
1354         destroy(false);
1355       // Body moved to a static method to encourage the compiler to inline away
1356       // instances of this class.
1357       Info.CurrentCall->popTempVersion();
1358     }
1359   private:
1360     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1361                         unsigned OldStackSize) {
1362       assert(OldStackSize <= Info.CleanupStack.size() &&
1363              "running cleanups out of order?");
1364 
1365       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1366       // for a full-expression scope.
1367       bool Success = true;
1368       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1369         if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1370           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1371             Success = false;
1372             break;
1373           }
1374         }
1375       }
1376 
1377       // Compact any retained cleanups.
1378       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1379       if (Kind != ScopeKind::Block)
1380         NewEnd =
1381             std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1382               return C.isDestroyedAtEndOf(Kind);
1383             });
1384       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1385       return Success;
1386     }
1387   };
1388   typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1389   typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1390   typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1391 }
1392 
1393 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1394                                          CheckSubobjectKind CSK) {
1395   if (Invalid)
1396     return false;
1397   if (isOnePastTheEnd()) {
1398     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1399       << CSK;
1400     setInvalid();
1401     return false;
1402   }
1403   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1404   // must actually be at least one array element; even a VLA cannot have a
1405   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1406   return true;
1407 }
1408 
1409 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1410                                                                 const Expr *E) {
1411   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1412   // Do not set the designator as invalid: we can represent this situation,
1413   // and correct handling of __builtin_object_size requires us to do so.
1414 }
1415 
1416 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1417                                                     const Expr *E,
1418                                                     const APSInt &N) {
1419   // If we're complaining, we must be able to statically determine the size of
1420   // the most derived array.
1421   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1422     Info.CCEDiag(E, diag::note_constexpr_array_index)
1423       << N << /*array*/ 0
1424       << static_cast<unsigned>(getMostDerivedArraySize());
1425   else
1426     Info.CCEDiag(E, diag::note_constexpr_array_index)
1427       << N << /*non-array*/ 1;
1428   setInvalid();
1429 }
1430 
1431 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1432                                const FunctionDecl *Callee, const LValue *This,
1433                                CallRef Call)
1434     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1435       Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1436   Info.CurrentCall = this;
1437   ++Info.CallStackDepth;
1438 }
1439 
1440 CallStackFrame::~CallStackFrame() {
1441   assert(Info.CurrentCall == this && "calls retired out of order");
1442   --Info.CallStackDepth;
1443   Info.CurrentCall = Caller;
1444 }
1445 
1446 static bool isRead(AccessKinds AK) {
1447   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1448 }
1449 
1450 static bool isModification(AccessKinds AK) {
1451   switch (AK) {
1452   case AK_Read:
1453   case AK_ReadObjectRepresentation:
1454   case AK_MemberCall:
1455   case AK_DynamicCast:
1456   case AK_TypeId:
1457     return false;
1458   case AK_Assign:
1459   case AK_Increment:
1460   case AK_Decrement:
1461   case AK_Construct:
1462   case AK_Destroy:
1463     return true;
1464   }
1465   llvm_unreachable("unknown access kind");
1466 }
1467 
1468 static bool isAnyAccess(AccessKinds AK) {
1469   return isRead(AK) || isModification(AK);
1470 }
1471 
1472 /// Is this an access per the C++ definition?
1473 static bool isFormalAccess(AccessKinds AK) {
1474   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1475 }
1476 
1477 /// Is this kind of axcess valid on an indeterminate object value?
1478 static bool isValidIndeterminateAccess(AccessKinds AK) {
1479   switch (AK) {
1480   case AK_Read:
1481   case AK_Increment:
1482   case AK_Decrement:
1483     // These need the object's value.
1484     return false;
1485 
1486   case AK_ReadObjectRepresentation:
1487   case AK_Assign:
1488   case AK_Construct:
1489   case AK_Destroy:
1490     // Construction and destruction don't need the value.
1491     return true;
1492 
1493   case AK_MemberCall:
1494   case AK_DynamicCast:
1495   case AK_TypeId:
1496     // These aren't really meaningful on scalars.
1497     return true;
1498   }
1499   llvm_unreachable("unknown access kind");
1500 }
1501 
1502 namespace {
1503   struct ComplexValue {
1504   private:
1505     bool IsInt;
1506 
1507   public:
1508     APSInt IntReal, IntImag;
1509     APFloat FloatReal, FloatImag;
1510 
1511     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1512 
1513     void makeComplexFloat() { IsInt = false; }
1514     bool isComplexFloat() const { return !IsInt; }
1515     APFloat &getComplexFloatReal() { return FloatReal; }
1516     APFloat &getComplexFloatImag() { return FloatImag; }
1517 
1518     void makeComplexInt() { IsInt = true; }
1519     bool isComplexInt() const { return IsInt; }
1520     APSInt &getComplexIntReal() { return IntReal; }
1521     APSInt &getComplexIntImag() { return IntImag; }
1522 
1523     void moveInto(APValue &v) const {
1524       if (isComplexFloat())
1525         v = APValue(FloatReal, FloatImag);
1526       else
1527         v = APValue(IntReal, IntImag);
1528     }
1529     void setFrom(const APValue &v) {
1530       assert(v.isComplexFloat() || v.isComplexInt());
1531       if (v.isComplexFloat()) {
1532         makeComplexFloat();
1533         FloatReal = v.getComplexFloatReal();
1534         FloatImag = v.getComplexFloatImag();
1535       } else {
1536         makeComplexInt();
1537         IntReal = v.getComplexIntReal();
1538         IntImag = v.getComplexIntImag();
1539       }
1540     }
1541   };
1542 
1543   struct LValue {
1544     APValue::LValueBase Base;
1545     CharUnits Offset;
1546     SubobjectDesignator Designator;
1547     bool IsNullPtr : 1;
1548     bool InvalidBase : 1;
1549 
1550     const APValue::LValueBase getLValueBase() const { return Base; }
1551     CharUnits &getLValueOffset() { return Offset; }
1552     const CharUnits &getLValueOffset() const { return Offset; }
1553     SubobjectDesignator &getLValueDesignator() { return Designator; }
1554     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1555     bool isNullPointer() const { return IsNullPtr;}
1556 
1557     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1558     unsigned getLValueVersion() const { return Base.getVersion(); }
1559 
1560     void moveInto(APValue &V) const {
1561       if (Designator.Invalid)
1562         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1563       else {
1564         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1565         V = APValue(Base, Offset, Designator.Entries,
1566                     Designator.IsOnePastTheEnd, IsNullPtr);
1567       }
1568     }
1569     void setFrom(ASTContext &Ctx, const APValue &V) {
1570       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1571       Base = V.getLValueBase();
1572       Offset = V.getLValueOffset();
1573       InvalidBase = false;
1574       Designator = SubobjectDesignator(Ctx, V);
1575       IsNullPtr = V.isNullPointer();
1576     }
1577 
1578     void set(APValue::LValueBase B, bool BInvalid = false) {
1579 #ifndef NDEBUG
1580       // We only allow a few types of invalid bases. Enforce that here.
1581       if (BInvalid) {
1582         const auto *E = B.get<const Expr *>();
1583         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1584                "Unexpected type of invalid base");
1585       }
1586 #endif
1587 
1588       Base = B;
1589       Offset = CharUnits::fromQuantity(0);
1590       InvalidBase = BInvalid;
1591       Designator = SubobjectDesignator(getType(B));
1592       IsNullPtr = false;
1593     }
1594 
1595     void setNull(ASTContext &Ctx, QualType PointerTy) {
1596       Base = (const ValueDecl *)nullptr;
1597       Offset =
1598           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1599       InvalidBase = false;
1600       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1601       IsNullPtr = true;
1602     }
1603 
1604     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1605       set(B, true);
1606     }
1607 
1608     std::string toString(ASTContext &Ctx, QualType T) const {
1609       APValue Printable;
1610       moveInto(Printable);
1611       return Printable.getAsString(Ctx, T);
1612     }
1613 
1614   private:
1615     // Check that this LValue is not based on a null pointer. If it is, produce
1616     // a diagnostic and mark the designator as invalid.
1617     template <typename GenDiagType>
1618     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1619       if (Designator.Invalid)
1620         return false;
1621       if (IsNullPtr) {
1622         GenDiag();
1623         Designator.setInvalid();
1624         return false;
1625       }
1626       return true;
1627     }
1628 
1629   public:
1630     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1631                           CheckSubobjectKind CSK) {
1632       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1633         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1634       });
1635     }
1636 
1637     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1638                                        AccessKinds AK) {
1639       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1640         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1641       });
1642     }
1643 
1644     // Check this LValue refers to an object. If not, set the designator to be
1645     // invalid and emit a diagnostic.
1646     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1647       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1648              Designator.checkSubobject(Info, E, CSK);
1649     }
1650 
1651     void addDecl(EvalInfo &Info, const Expr *E,
1652                  const Decl *D, bool Virtual = false) {
1653       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1654         Designator.addDeclUnchecked(D, Virtual);
1655     }
1656     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1657       if (!Designator.Entries.empty()) {
1658         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1659         Designator.setInvalid();
1660         return;
1661       }
1662       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1663         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1664         Designator.FirstEntryIsAnUnsizedArray = true;
1665         Designator.addUnsizedArrayUnchecked(ElemTy);
1666       }
1667     }
1668     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1669       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1670         Designator.addArrayUnchecked(CAT);
1671     }
1672     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1673       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1674         Designator.addComplexUnchecked(EltTy, Imag);
1675     }
1676     void clearIsNullPointer() {
1677       IsNullPtr = false;
1678     }
1679     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1680                               const APSInt &Index, CharUnits ElementSize) {
1681       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1682       // but we're not required to diagnose it and it's valid in C++.)
1683       if (!Index)
1684         return;
1685 
1686       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1687       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1688       // offsets.
1689       uint64_t Offset64 = Offset.getQuantity();
1690       uint64_t ElemSize64 = ElementSize.getQuantity();
1691       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1692       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1693 
1694       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1695         Designator.adjustIndex(Info, E, Index);
1696       clearIsNullPointer();
1697     }
1698     void adjustOffset(CharUnits N) {
1699       Offset += N;
1700       if (N.getQuantity())
1701         clearIsNullPointer();
1702     }
1703   };
1704 
1705   struct MemberPtr {
1706     MemberPtr() {}
1707     explicit MemberPtr(const ValueDecl *Decl) :
1708       DeclAndIsDerivedMember(Decl, false), Path() {}
1709 
1710     /// The member or (direct or indirect) field referred to by this member
1711     /// pointer, or 0 if this is a null member pointer.
1712     const ValueDecl *getDecl() const {
1713       return DeclAndIsDerivedMember.getPointer();
1714     }
1715     /// Is this actually a member of some type derived from the relevant class?
1716     bool isDerivedMember() const {
1717       return DeclAndIsDerivedMember.getInt();
1718     }
1719     /// Get the class which the declaration actually lives in.
1720     const CXXRecordDecl *getContainingRecord() const {
1721       return cast<CXXRecordDecl>(
1722           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1723     }
1724 
1725     void moveInto(APValue &V) const {
1726       V = APValue(getDecl(), isDerivedMember(), Path);
1727     }
1728     void setFrom(const APValue &V) {
1729       assert(V.isMemberPointer());
1730       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1731       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1732       Path.clear();
1733       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1734       Path.insert(Path.end(), P.begin(), P.end());
1735     }
1736 
1737     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1738     /// whether the member is a member of some class derived from the class type
1739     /// of the member pointer.
1740     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1741     /// Path - The path of base/derived classes from the member declaration's
1742     /// class (exclusive) to the class type of the member pointer (inclusive).
1743     SmallVector<const CXXRecordDecl*, 4> Path;
1744 
1745     /// Perform a cast towards the class of the Decl (either up or down the
1746     /// hierarchy).
1747     bool castBack(const CXXRecordDecl *Class) {
1748       assert(!Path.empty());
1749       const CXXRecordDecl *Expected;
1750       if (Path.size() >= 2)
1751         Expected = Path[Path.size() - 2];
1752       else
1753         Expected = getContainingRecord();
1754       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1755         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1756         // if B does not contain the original member and is not a base or
1757         // derived class of the class containing the original member, the result
1758         // of the cast is undefined.
1759         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1760         // (D::*). We consider that to be a language defect.
1761         return false;
1762       }
1763       Path.pop_back();
1764       return true;
1765     }
1766     /// Perform a base-to-derived member pointer cast.
1767     bool castToDerived(const CXXRecordDecl *Derived) {
1768       if (!getDecl())
1769         return true;
1770       if (!isDerivedMember()) {
1771         Path.push_back(Derived);
1772         return true;
1773       }
1774       if (!castBack(Derived))
1775         return false;
1776       if (Path.empty())
1777         DeclAndIsDerivedMember.setInt(false);
1778       return true;
1779     }
1780     /// Perform a derived-to-base member pointer cast.
1781     bool castToBase(const CXXRecordDecl *Base) {
1782       if (!getDecl())
1783         return true;
1784       if (Path.empty())
1785         DeclAndIsDerivedMember.setInt(true);
1786       if (isDerivedMember()) {
1787         Path.push_back(Base);
1788         return true;
1789       }
1790       return castBack(Base);
1791     }
1792   };
1793 
1794   /// Compare two member pointers, which are assumed to be of the same type.
1795   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1796     if (!LHS.getDecl() || !RHS.getDecl())
1797       return !LHS.getDecl() && !RHS.getDecl();
1798     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1799       return false;
1800     return LHS.Path == RHS.Path;
1801   }
1802 }
1803 
1804 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1805 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1806                             const LValue &This, const Expr *E,
1807                             bool AllowNonLiteralTypes = false);
1808 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1809                            bool InvalidBaseOK = false);
1810 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1811                             bool InvalidBaseOK = false);
1812 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1813                                   EvalInfo &Info);
1814 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1815 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1816 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1817                                     EvalInfo &Info);
1818 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1819 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1820 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1821                            EvalInfo &Info);
1822 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1823 
1824 /// Evaluate an integer or fixed point expression into an APResult.
1825 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1826                                         EvalInfo &Info);
1827 
1828 /// Evaluate only a fixed point expression into an APResult.
1829 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1830                                EvalInfo &Info);
1831 
1832 //===----------------------------------------------------------------------===//
1833 // Misc utilities
1834 //===----------------------------------------------------------------------===//
1835 
1836 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1837 /// preserving its value (by extending by up to one bit as needed).
1838 static void negateAsSigned(APSInt &Int) {
1839   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1840     Int = Int.extend(Int.getBitWidth() + 1);
1841     Int.setIsSigned(true);
1842   }
1843   Int = -Int;
1844 }
1845 
1846 template<typename KeyT>
1847 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1848                                          ScopeKind Scope, LValue &LV) {
1849   unsigned Version = getTempVersion();
1850   APValue::LValueBase Base(Key, Index, Version);
1851   LV.set(Base);
1852   return createLocal(Base, Key, T, Scope);
1853 }
1854 
1855 /// Allocate storage for a parameter of a function call made in this frame.
1856 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1857                                      LValue &LV) {
1858   assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1859   APValue::LValueBase Base(PVD, Index, Args.Version);
1860   LV.set(Base);
1861   // We always destroy parameters at the end of the call, even if we'd allow
1862   // them to live to the end of the full-expression at runtime, in order to
1863   // give portable results and match other compilers.
1864   return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1865 }
1866 
1867 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1868                                      QualType T, ScopeKind Scope) {
1869   assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1870   unsigned Version = Base.getVersion();
1871   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1872   assert(Result.isAbsent() && "local created multiple times");
1873 
1874   // If we're creating a local immediately in the operand of a speculative
1875   // evaluation, don't register a cleanup to be run outside the speculative
1876   // evaluation context, since we won't actually be able to initialize this
1877   // object.
1878   if (Index <= Info.SpeculativeEvaluationDepth) {
1879     if (T.isDestructedType())
1880       Info.noteSideEffect();
1881   } else {
1882     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1883   }
1884   return Result;
1885 }
1886 
1887 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1888   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1889     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1890     return nullptr;
1891   }
1892 
1893   DynamicAllocLValue DA(NumHeapAllocs++);
1894   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1895   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1896                                    std::forward_as_tuple(DA), std::tuple<>());
1897   assert(Result.second && "reused a heap alloc index?");
1898   Result.first->second.AllocExpr = E;
1899   return &Result.first->second.Value;
1900 }
1901 
1902 /// Produce a string describing the given constexpr call.
1903 void CallStackFrame::describe(raw_ostream &Out) {
1904   unsigned ArgIndex = 0;
1905   bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1906                       !isa<CXXConstructorDecl>(Callee) &&
1907                       cast<CXXMethodDecl>(Callee)->isInstance();
1908 
1909   if (!IsMemberCall)
1910     Out << *Callee << '(';
1911 
1912   if (This && IsMemberCall) {
1913     APValue Val;
1914     This->moveInto(Val);
1915     Val.printPretty(Out, Info.Ctx,
1916                     This->Designator.MostDerivedType);
1917     // FIXME: Add parens around Val if needed.
1918     Out << "->" << *Callee << '(';
1919     IsMemberCall = false;
1920   }
1921 
1922   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1923        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1924     if (ArgIndex > (unsigned)IsMemberCall)
1925       Out << ", ";
1926 
1927     const ParmVarDecl *Param = *I;
1928     APValue *V = Info.getParamSlot(Arguments, Param);
1929     if (V)
1930       V->printPretty(Out, Info.Ctx, Param->getType());
1931     else
1932       Out << "<...>";
1933 
1934     if (ArgIndex == 0 && IsMemberCall)
1935       Out << "->" << *Callee << '(';
1936   }
1937 
1938   Out << ')';
1939 }
1940 
1941 /// Evaluate an expression to see if it had side-effects, and discard its
1942 /// result.
1943 /// \return \c true if the caller should keep evaluating.
1944 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1945   assert(!E->isValueDependent());
1946   APValue Scratch;
1947   if (!Evaluate(Scratch, Info, E))
1948     // We don't need the value, but we might have skipped a side effect here.
1949     return Info.noteSideEffect();
1950   return true;
1951 }
1952 
1953 /// Should this call expression be treated as a string literal?
1954 static bool IsStringLiteralCall(const CallExpr *E) {
1955   unsigned Builtin = E->getBuiltinCallee();
1956   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1957           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1958 }
1959 
1960 static bool IsGlobalLValue(APValue::LValueBase B) {
1961   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1962   // constant expression of pointer type that evaluates to...
1963 
1964   // ... a null pointer value, or a prvalue core constant expression of type
1965   // std::nullptr_t.
1966   if (!B) return true;
1967 
1968   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1969     // ... the address of an object with static storage duration,
1970     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1971       return VD->hasGlobalStorage();
1972     if (isa<TemplateParamObjectDecl>(D))
1973       return true;
1974     // ... the address of a function,
1975     // ... the address of a GUID [MS extension],
1976     return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D);
1977   }
1978 
1979   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1980     return true;
1981 
1982   const Expr *E = B.get<const Expr*>();
1983   switch (E->getStmtClass()) {
1984   default:
1985     return false;
1986   case Expr::CompoundLiteralExprClass: {
1987     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1988     return CLE->isFileScope() && CLE->isLValue();
1989   }
1990   case Expr::MaterializeTemporaryExprClass:
1991     // A materialized temporary might have been lifetime-extended to static
1992     // storage duration.
1993     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1994   // A string literal has static storage duration.
1995   case Expr::StringLiteralClass:
1996   case Expr::PredefinedExprClass:
1997   case Expr::ObjCStringLiteralClass:
1998   case Expr::ObjCEncodeExprClass:
1999     return true;
2000   case Expr::ObjCBoxedExprClass:
2001     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2002   case Expr::CallExprClass:
2003     return IsStringLiteralCall(cast<CallExpr>(E));
2004   // For GCC compatibility, &&label has static storage duration.
2005   case Expr::AddrLabelExprClass:
2006     return true;
2007   // A Block literal expression may be used as the initialization value for
2008   // Block variables at global or local static scope.
2009   case Expr::BlockExprClass:
2010     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2011   case Expr::ImplicitValueInitExprClass:
2012     // FIXME:
2013     // We can never form an lvalue with an implicit value initialization as its
2014     // base through expression evaluation, so these only appear in one case: the
2015     // implicit variable declaration we invent when checking whether a constexpr
2016     // constructor can produce a constant expression. We must assume that such
2017     // an expression might be a global lvalue.
2018     return true;
2019   }
2020 }
2021 
2022 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2023   return LVal.Base.dyn_cast<const ValueDecl*>();
2024 }
2025 
2026 static bool IsLiteralLValue(const LValue &Value) {
2027   if (Value.getLValueCallIndex())
2028     return false;
2029   const Expr *E = Value.Base.dyn_cast<const Expr*>();
2030   return E && !isa<MaterializeTemporaryExpr>(E);
2031 }
2032 
2033 static bool IsWeakLValue(const LValue &Value) {
2034   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2035   return Decl && Decl->isWeak();
2036 }
2037 
2038 static bool isZeroSized(const LValue &Value) {
2039   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2040   if (Decl && isa<VarDecl>(Decl)) {
2041     QualType Ty = Decl->getType();
2042     if (Ty->isArrayType())
2043       return Ty->isIncompleteType() ||
2044              Decl->getASTContext().getTypeSize(Ty) == 0;
2045   }
2046   return false;
2047 }
2048 
2049 static bool HasSameBase(const LValue &A, const LValue &B) {
2050   if (!A.getLValueBase())
2051     return !B.getLValueBase();
2052   if (!B.getLValueBase())
2053     return false;
2054 
2055   if (A.getLValueBase().getOpaqueValue() !=
2056       B.getLValueBase().getOpaqueValue())
2057     return false;
2058 
2059   return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2060          A.getLValueVersion() == B.getLValueVersion();
2061 }
2062 
2063 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2064   assert(Base && "no location for a null lvalue");
2065   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2066 
2067   // For a parameter, find the corresponding call stack frame (if it still
2068   // exists), and point at the parameter of the function definition we actually
2069   // invoked.
2070   if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2071     unsigned Idx = PVD->getFunctionScopeIndex();
2072     for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2073       if (F->Arguments.CallIndex == Base.getCallIndex() &&
2074           F->Arguments.Version == Base.getVersion() && F->Callee &&
2075           Idx < F->Callee->getNumParams()) {
2076         VD = F->Callee->getParamDecl(Idx);
2077         break;
2078       }
2079     }
2080   }
2081 
2082   if (VD)
2083     Info.Note(VD->getLocation(), diag::note_declared_at);
2084   else if (const Expr *E = Base.dyn_cast<const Expr*>())
2085     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2086   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2087     // FIXME: Produce a note for dangling pointers too.
2088     if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
2089       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2090                 diag::note_constexpr_dynamic_alloc_here);
2091   }
2092   // We have no information to show for a typeid(T) object.
2093 }
2094 
2095 enum class CheckEvaluationResultKind {
2096   ConstantExpression,
2097   FullyInitialized,
2098 };
2099 
2100 /// Materialized temporaries that we've already checked to determine if they're
2101 /// initializsed by a constant expression.
2102 using CheckedTemporaries =
2103     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2104 
2105 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2106                                   EvalInfo &Info, SourceLocation DiagLoc,
2107                                   QualType Type, const APValue &Value,
2108                                   ConstantExprKind Kind,
2109                                   SourceLocation SubobjectLoc,
2110                                   CheckedTemporaries &CheckedTemps);
2111 
2112 /// Check that this reference or pointer core constant expression is a valid
2113 /// value for an address or reference constant expression. Return true if we
2114 /// can fold this expression, whether or not it's a constant expression.
2115 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2116                                           QualType Type, const LValue &LVal,
2117                                           ConstantExprKind Kind,
2118                                           CheckedTemporaries &CheckedTemps) {
2119   bool IsReferenceType = Type->isReferenceType();
2120 
2121   APValue::LValueBase Base = LVal.getLValueBase();
2122   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2123 
2124   const Expr *BaseE = Base.dyn_cast<const Expr *>();
2125   const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2126 
2127   // Additional restrictions apply in a template argument. We only enforce the
2128   // C++20 restrictions here; additional syntactic and semantic restrictions
2129   // are applied elsewhere.
2130   if (isTemplateArgument(Kind)) {
2131     int InvalidBaseKind = -1;
2132     StringRef Ident;
2133     if (Base.is<TypeInfoLValue>())
2134       InvalidBaseKind = 0;
2135     else if (isa_and_nonnull<StringLiteral>(BaseE))
2136       InvalidBaseKind = 1;
2137     else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2138              isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2139       InvalidBaseKind = 2;
2140     else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2141       InvalidBaseKind = 3;
2142       Ident = PE->getIdentKindName();
2143     }
2144 
2145     if (InvalidBaseKind != -1) {
2146       Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2147           << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2148           << Ident;
2149       return false;
2150     }
2151   }
2152 
2153   if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) {
2154     if (FD->isConsteval()) {
2155       Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2156           << !Type->isAnyPointerType();
2157       Info.Note(FD->getLocation(), diag::note_declared_at);
2158       return false;
2159     }
2160   }
2161 
2162   // Check that the object is a global. Note that the fake 'this' object we
2163   // manufacture when checking potential constant expressions is conservatively
2164   // assumed to be global here.
2165   if (!IsGlobalLValue(Base)) {
2166     if (Info.getLangOpts().CPlusPlus11) {
2167       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2168       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2169         << IsReferenceType << !Designator.Entries.empty()
2170         << !!VD << VD;
2171 
2172       auto *VarD = dyn_cast_or_null<VarDecl>(VD);
2173       if (VarD && VarD->isConstexpr()) {
2174         // Non-static local constexpr variables have unintuitive semantics:
2175         //   constexpr int a = 1;
2176         //   constexpr const int *p = &a;
2177         // ... is invalid because the address of 'a' is not constant. Suggest
2178         // adding a 'static' in this case.
2179         Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2180             << VarD
2181             << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2182       } else {
2183         NoteLValueLocation(Info, Base);
2184       }
2185     } else {
2186       Info.FFDiag(Loc);
2187     }
2188     // Don't allow references to temporaries to escape.
2189     return false;
2190   }
2191   assert((Info.checkingPotentialConstantExpression() ||
2192           LVal.getLValueCallIndex() == 0) &&
2193          "have call index for global lvalue");
2194 
2195   if (Base.is<DynamicAllocLValue>()) {
2196     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2197         << IsReferenceType << !Designator.Entries.empty();
2198     NoteLValueLocation(Info, Base);
2199     return false;
2200   }
2201 
2202   if (BaseVD) {
2203     if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2204       // Check if this is a thread-local variable.
2205       if (Var->getTLSKind())
2206         // FIXME: Diagnostic!
2207         return false;
2208 
2209       // A dllimport variable never acts like a constant, unless we're
2210       // evaluating a value for use only in name mangling.
2211       if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2212         // FIXME: Diagnostic!
2213         return false;
2214     }
2215     if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2216       // __declspec(dllimport) must be handled very carefully:
2217       // We must never initialize an expression with the thunk in C++.
2218       // Doing otherwise would allow the same id-expression to yield
2219       // different addresses for the same function in different translation
2220       // units.  However, this means that we must dynamically initialize the
2221       // expression with the contents of the import address table at runtime.
2222       //
2223       // The C language has no notion of ODR; furthermore, it has no notion of
2224       // dynamic initialization.  This means that we are permitted to
2225       // perform initialization with the address of the thunk.
2226       if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2227           FD->hasAttr<DLLImportAttr>())
2228         // FIXME: Diagnostic!
2229         return false;
2230     }
2231   } else if (const auto *MTE =
2232                  dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2233     if (CheckedTemps.insert(MTE).second) {
2234       QualType TempType = getType(Base);
2235       if (TempType.isDestructedType()) {
2236         Info.FFDiag(MTE->getExprLoc(),
2237                     diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2238             << TempType;
2239         return false;
2240       }
2241 
2242       APValue *V = MTE->getOrCreateValue(false);
2243       assert(V && "evasluation result refers to uninitialised temporary");
2244       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2245                                  Info, MTE->getExprLoc(), TempType, *V,
2246                                  Kind, SourceLocation(), CheckedTemps))
2247         return false;
2248     }
2249   }
2250 
2251   // Allow address constant expressions to be past-the-end pointers. This is
2252   // an extension: the standard requires them to point to an object.
2253   if (!IsReferenceType)
2254     return true;
2255 
2256   // A reference constant expression must refer to an object.
2257   if (!Base) {
2258     // FIXME: diagnostic
2259     Info.CCEDiag(Loc);
2260     return true;
2261   }
2262 
2263   // Does this refer one past the end of some object?
2264   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2265     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2266       << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2267     NoteLValueLocation(Info, Base);
2268   }
2269 
2270   return true;
2271 }
2272 
2273 /// Member pointers are constant expressions unless they point to a
2274 /// non-virtual dllimport member function.
2275 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2276                                                  SourceLocation Loc,
2277                                                  QualType Type,
2278                                                  const APValue &Value,
2279                                                  ConstantExprKind Kind) {
2280   const ValueDecl *Member = Value.getMemberPointerDecl();
2281   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2282   if (!FD)
2283     return true;
2284   if (FD->isConsteval()) {
2285     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2286     Info.Note(FD->getLocation(), diag::note_declared_at);
2287     return false;
2288   }
2289   return isForManglingOnly(Kind) || FD->isVirtual() ||
2290          !FD->hasAttr<DLLImportAttr>();
2291 }
2292 
2293 /// Check that this core constant expression is of literal type, and if not,
2294 /// produce an appropriate diagnostic.
2295 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2296                              const LValue *This = nullptr) {
2297   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
2298     return true;
2299 
2300   // C++1y: A constant initializer for an object o [...] may also invoke
2301   // constexpr constructors for o and its subobjects even if those objects
2302   // are of non-literal class types.
2303   //
2304   // C++11 missed this detail for aggregates, so classes like this:
2305   //   struct foo_t { union { int i; volatile int j; } u; };
2306   // are not (obviously) initializable like so:
2307   //   __attribute__((__require_constant_initialization__))
2308   //   static const foo_t x = {{0}};
2309   // because "i" is a subobject with non-literal initialization (due to the
2310   // volatile member of the union). See:
2311   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2312   // Therefore, we use the C++1y behavior.
2313   if (This && Info.EvaluatingDecl == This->getLValueBase())
2314     return true;
2315 
2316   // Prvalue constant expressions must be of literal types.
2317   if (Info.getLangOpts().CPlusPlus11)
2318     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2319       << E->getType();
2320   else
2321     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2322   return false;
2323 }
2324 
2325 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2326                                   EvalInfo &Info, SourceLocation DiagLoc,
2327                                   QualType Type, const APValue &Value,
2328                                   ConstantExprKind Kind,
2329                                   SourceLocation SubobjectLoc,
2330                                   CheckedTemporaries &CheckedTemps) {
2331   if (!Value.hasValue()) {
2332     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2333       << true << Type;
2334     if (SubobjectLoc.isValid())
2335       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2336     return false;
2337   }
2338 
2339   // We allow _Atomic(T) to be initialized from anything that T can be
2340   // initialized from.
2341   if (const AtomicType *AT = Type->getAs<AtomicType>())
2342     Type = AT->getValueType();
2343 
2344   // Core issue 1454: For a literal constant expression of array or class type,
2345   // each subobject of its value shall have been initialized by a constant
2346   // expression.
2347   if (Value.isArray()) {
2348     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2349     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2350       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2351                                  Value.getArrayInitializedElt(I), Kind,
2352                                  SubobjectLoc, CheckedTemps))
2353         return false;
2354     }
2355     if (!Value.hasArrayFiller())
2356       return true;
2357     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2358                                  Value.getArrayFiller(), Kind, SubobjectLoc,
2359                                  CheckedTemps);
2360   }
2361   if (Value.isUnion() && Value.getUnionField()) {
2362     return CheckEvaluationResult(
2363         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2364         Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(),
2365         CheckedTemps);
2366   }
2367   if (Value.isStruct()) {
2368     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2369     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2370       unsigned BaseIndex = 0;
2371       for (const CXXBaseSpecifier &BS : CD->bases()) {
2372         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2373                                    Value.getStructBase(BaseIndex), Kind,
2374                                    BS.getBeginLoc(), CheckedTemps))
2375           return false;
2376         ++BaseIndex;
2377       }
2378     }
2379     for (const auto *I : RD->fields()) {
2380       if (I->isUnnamedBitfield())
2381         continue;
2382 
2383       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2384                                  Value.getStructField(I->getFieldIndex()),
2385                                  Kind, I->getLocation(), CheckedTemps))
2386         return false;
2387     }
2388   }
2389 
2390   if (Value.isLValue() &&
2391       CERK == CheckEvaluationResultKind::ConstantExpression) {
2392     LValue LVal;
2393     LVal.setFrom(Info.Ctx, Value);
2394     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2395                                          CheckedTemps);
2396   }
2397 
2398   if (Value.isMemberPointer() &&
2399       CERK == CheckEvaluationResultKind::ConstantExpression)
2400     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2401 
2402   // Everything else is fine.
2403   return true;
2404 }
2405 
2406 /// Check that this core constant expression value is a valid value for a
2407 /// constant expression. If not, report an appropriate diagnostic. Does not
2408 /// check that the expression is of literal type.
2409 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2410                                     QualType Type, const APValue &Value,
2411                                     ConstantExprKind Kind) {
2412   // Nothing to check for a constant expression of type 'cv void'.
2413   if (Type->isVoidType())
2414     return true;
2415 
2416   CheckedTemporaries CheckedTemps;
2417   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2418                                Info, DiagLoc, Type, Value, Kind,
2419                                SourceLocation(), CheckedTemps);
2420 }
2421 
2422 /// Check that this evaluated value is fully-initialized and can be loaded by
2423 /// an lvalue-to-rvalue conversion.
2424 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2425                                   QualType Type, const APValue &Value) {
2426   CheckedTemporaries CheckedTemps;
2427   return CheckEvaluationResult(
2428       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2429       ConstantExprKind::Normal, SourceLocation(), CheckedTemps);
2430 }
2431 
2432 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2433 /// "the allocated storage is deallocated within the evaluation".
2434 static bool CheckMemoryLeaks(EvalInfo &Info) {
2435   if (!Info.HeapAllocs.empty()) {
2436     // We can still fold to a constant despite a compile-time memory leak,
2437     // so long as the heap allocation isn't referenced in the result (we check
2438     // that in CheckConstantExpression).
2439     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2440                  diag::note_constexpr_memory_leak)
2441         << unsigned(Info.HeapAllocs.size() - 1);
2442   }
2443   return true;
2444 }
2445 
2446 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2447   // A null base expression indicates a null pointer.  These are always
2448   // evaluatable, and they are false unless the offset is zero.
2449   if (!Value.getLValueBase()) {
2450     Result = !Value.getLValueOffset().isZero();
2451     return true;
2452   }
2453 
2454   // We have a non-null base.  These are generally known to be true, but if it's
2455   // a weak declaration it can be null at runtime.
2456   Result = true;
2457   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2458   return !Decl || !Decl->isWeak();
2459 }
2460 
2461 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2462   switch (Val.getKind()) {
2463   case APValue::None:
2464   case APValue::Indeterminate:
2465     return false;
2466   case APValue::Int:
2467     Result = Val.getInt().getBoolValue();
2468     return true;
2469   case APValue::FixedPoint:
2470     Result = Val.getFixedPoint().getBoolValue();
2471     return true;
2472   case APValue::Float:
2473     Result = !Val.getFloat().isZero();
2474     return true;
2475   case APValue::ComplexInt:
2476     Result = Val.getComplexIntReal().getBoolValue() ||
2477              Val.getComplexIntImag().getBoolValue();
2478     return true;
2479   case APValue::ComplexFloat:
2480     Result = !Val.getComplexFloatReal().isZero() ||
2481              !Val.getComplexFloatImag().isZero();
2482     return true;
2483   case APValue::LValue:
2484     return EvalPointerValueAsBool(Val, Result);
2485   case APValue::MemberPointer:
2486     Result = Val.getMemberPointerDecl();
2487     return true;
2488   case APValue::Vector:
2489   case APValue::Array:
2490   case APValue::Struct:
2491   case APValue::Union:
2492   case APValue::AddrLabelDiff:
2493     return false;
2494   }
2495 
2496   llvm_unreachable("unknown APValue kind");
2497 }
2498 
2499 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2500                                        EvalInfo &Info) {
2501   assert(!E->isValueDependent());
2502   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2503   APValue Val;
2504   if (!Evaluate(Val, Info, E))
2505     return false;
2506   return HandleConversionToBool(Val, Result);
2507 }
2508 
2509 template<typename T>
2510 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2511                            const T &SrcValue, QualType DestType) {
2512   Info.CCEDiag(E, diag::note_constexpr_overflow)
2513     << SrcValue << DestType;
2514   return Info.noteUndefinedBehavior();
2515 }
2516 
2517 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2518                                  QualType SrcType, const APFloat &Value,
2519                                  QualType DestType, APSInt &Result) {
2520   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2521   // Determine whether we are converting to unsigned or signed.
2522   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2523 
2524   Result = APSInt(DestWidth, !DestSigned);
2525   bool ignored;
2526   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2527       & APFloat::opInvalidOp)
2528     return HandleOverflow(Info, E, Value, DestType);
2529   return true;
2530 }
2531 
2532 /// Get rounding mode used for evaluation of the specified expression.
2533 /// \param[out] DynamicRM Is set to true is the requested rounding mode is
2534 ///                       dynamic.
2535 /// If rounding mode is unknown at compile time, still try to evaluate the
2536 /// expression. If the result is exact, it does not depend on rounding mode.
2537 /// So return "tonearest" mode instead of "dynamic".
2538 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E,
2539                                                 bool &DynamicRM) {
2540   llvm::RoundingMode RM =
2541       E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2542   DynamicRM = (RM == llvm::RoundingMode::Dynamic);
2543   if (DynamicRM)
2544     RM = llvm::RoundingMode::NearestTiesToEven;
2545   return RM;
2546 }
2547 
2548 /// Check if the given evaluation result is allowed for constant evaluation.
2549 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2550                                      APFloat::opStatus St) {
2551   // In a constant context, assume that any dynamic rounding mode or FP
2552   // exception state matches the default floating-point environment.
2553   if (Info.InConstantContext)
2554     return true;
2555 
2556   FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2557   if ((St & APFloat::opInexact) &&
2558       FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2559     // Inexact result means that it depends on rounding mode. If the requested
2560     // mode is dynamic, the evaluation cannot be made in compile time.
2561     Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2562     return false;
2563   }
2564 
2565   if ((St != APFloat::opOK) &&
2566       (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2567        FPO.getFPExceptionMode() != LangOptions::FPE_Ignore ||
2568        FPO.getAllowFEnvAccess())) {
2569     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2570     return false;
2571   }
2572 
2573   if ((St & APFloat::opStatus::opInvalidOp) &&
2574       FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) {
2575     // There is no usefully definable result.
2576     Info.FFDiag(E);
2577     return false;
2578   }
2579 
2580   // FIXME: if:
2581   // - evaluation triggered other FP exception, and
2582   // - exception mode is not "ignore", and
2583   // - the expression being evaluated is not a part of global variable
2584   //   initializer,
2585   // the evaluation probably need to be rejected.
2586   return true;
2587 }
2588 
2589 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2590                                    QualType SrcType, QualType DestType,
2591                                    APFloat &Result) {
2592   assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2593   bool DynamicRM;
2594   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2595   APFloat::opStatus St;
2596   APFloat Value = Result;
2597   bool ignored;
2598   St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2599   return checkFloatingPointResult(Info, E, St);
2600 }
2601 
2602 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2603                                  QualType DestType, QualType SrcType,
2604                                  const APSInt &Value) {
2605   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2606   // Figure out if this is a truncate, extend or noop cast.
2607   // If the input is signed, do a sign extend, noop, or truncate.
2608   APSInt Result = Value.extOrTrunc(DestWidth);
2609   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2610   if (DestType->isBooleanType())
2611     Result = Value.getBoolValue();
2612   return Result;
2613 }
2614 
2615 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2616                                  const FPOptions FPO,
2617                                  QualType SrcType, const APSInt &Value,
2618                                  QualType DestType, APFloat &Result) {
2619   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2620   APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(),
2621        APFloat::rmNearestTiesToEven);
2622   if (!Info.InConstantContext && St != llvm::APFloatBase::opOK &&
2623       FPO.isFPConstrained()) {
2624     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2625     return false;
2626   }
2627   return true;
2628 }
2629 
2630 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2631                                   APValue &Value, const FieldDecl *FD) {
2632   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2633 
2634   if (!Value.isInt()) {
2635     // Trying to store a pointer-cast-to-integer into a bitfield.
2636     // FIXME: In this case, we should provide the diagnostic for casting
2637     // a pointer to an integer.
2638     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2639     Info.FFDiag(E);
2640     return false;
2641   }
2642 
2643   APSInt &Int = Value.getInt();
2644   unsigned OldBitWidth = Int.getBitWidth();
2645   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2646   if (NewBitWidth < OldBitWidth)
2647     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2648   return true;
2649 }
2650 
2651 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2652                                   llvm::APInt &Res) {
2653   APValue SVal;
2654   if (!Evaluate(SVal, Info, E))
2655     return false;
2656   if (SVal.isInt()) {
2657     Res = SVal.getInt();
2658     return true;
2659   }
2660   if (SVal.isFloat()) {
2661     Res = SVal.getFloat().bitcastToAPInt();
2662     return true;
2663   }
2664   if (SVal.isVector()) {
2665     QualType VecTy = E->getType();
2666     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2667     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2668     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2669     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2670     Res = llvm::APInt::getNullValue(VecSize);
2671     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2672       APValue &Elt = SVal.getVectorElt(i);
2673       llvm::APInt EltAsInt;
2674       if (Elt.isInt()) {
2675         EltAsInt = Elt.getInt();
2676       } else if (Elt.isFloat()) {
2677         EltAsInt = Elt.getFloat().bitcastToAPInt();
2678       } else {
2679         // Don't try to handle vectors of anything other than int or float
2680         // (not sure if it's possible to hit this case).
2681         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2682         return false;
2683       }
2684       unsigned BaseEltSize = EltAsInt.getBitWidth();
2685       if (BigEndian)
2686         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2687       else
2688         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2689     }
2690     return true;
2691   }
2692   // Give up if the input isn't an int, float, or vector.  For example, we
2693   // reject "(v4i16)(intptr_t)&a".
2694   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2695   return false;
2696 }
2697 
2698 /// Perform the given integer operation, which is known to need at most BitWidth
2699 /// bits, and check for overflow in the original type (if that type was not an
2700 /// unsigned type).
2701 template<typename Operation>
2702 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2703                                  const APSInt &LHS, const APSInt &RHS,
2704                                  unsigned BitWidth, Operation Op,
2705                                  APSInt &Result) {
2706   if (LHS.isUnsigned()) {
2707     Result = Op(LHS, RHS);
2708     return true;
2709   }
2710 
2711   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2712   Result = Value.trunc(LHS.getBitWidth());
2713   if (Result.extend(BitWidth) != Value) {
2714     if (Info.checkingForUndefinedBehavior())
2715       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2716                                        diag::warn_integer_constant_overflow)
2717           << Result.toString(10) << E->getType();
2718     else
2719       return HandleOverflow(Info, E, Value, E->getType());
2720   }
2721   return true;
2722 }
2723 
2724 /// Perform the given binary integer operation.
2725 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2726                               BinaryOperatorKind Opcode, APSInt RHS,
2727                               APSInt &Result) {
2728   switch (Opcode) {
2729   default:
2730     Info.FFDiag(E);
2731     return false;
2732   case BO_Mul:
2733     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2734                                 std::multiplies<APSInt>(), Result);
2735   case BO_Add:
2736     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2737                                 std::plus<APSInt>(), Result);
2738   case BO_Sub:
2739     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2740                                 std::minus<APSInt>(), Result);
2741   case BO_And: Result = LHS & RHS; return true;
2742   case BO_Xor: Result = LHS ^ RHS; return true;
2743   case BO_Or:  Result = LHS | RHS; return true;
2744   case BO_Div:
2745   case BO_Rem:
2746     if (RHS == 0) {
2747       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2748       return false;
2749     }
2750     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2751     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2752     // this operation and gives the two's complement result.
2753     if (RHS.isNegative() && RHS.isAllOnesValue() &&
2754         LHS.isSigned() && LHS.isMinSignedValue())
2755       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2756                             E->getType());
2757     return true;
2758   case BO_Shl: {
2759     if (Info.getLangOpts().OpenCL)
2760       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2761       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2762                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2763                     RHS.isUnsigned());
2764     else if (RHS.isSigned() && RHS.isNegative()) {
2765       // During constant-folding, a negative shift is an opposite shift. Such
2766       // a shift is not a constant expression.
2767       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2768       RHS = -RHS;
2769       goto shift_right;
2770     }
2771   shift_left:
2772     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2773     // the shifted type.
2774     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2775     if (SA != RHS) {
2776       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2777         << RHS << E->getType() << LHS.getBitWidth();
2778     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2779       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2780       // operand, and must not overflow the corresponding unsigned type.
2781       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2782       // E1 x 2^E2 module 2^N.
2783       if (LHS.isNegative())
2784         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2785       else if (LHS.countLeadingZeros() < SA)
2786         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2787     }
2788     Result = LHS << SA;
2789     return true;
2790   }
2791   case BO_Shr: {
2792     if (Info.getLangOpts().OpenCL)
2793       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2794       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2795                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2796                     RHS.isUnsigned());
2797     else if (RHS.isSigned() && RHS.isNegative()) {
2798       // During constant-folding, a negative shift is an opposite shift. Such a
2799       // shift is not a constant expression.
2800       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2801       RHS = -RHS;
2802       goto shift_left;
2803     }
2804   shift_right:
2805     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2806     // shifted type.
2807     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2808     if (SA != RHS)
2809       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2810         << RHS << E->getType() << LHS.getBitWidth();
2811     Result = LHS >> SA;
2812     return true;
2813   }
2814 
2815   case BO_LT: Result = LHS < RHS; return true;
2816   case BO_GT: Result = LHS > RHS; return true;
2817   case BO_LE: Result = LHS <= RHS; return true;
2818   case BO_GE: Result = LHS >= RHS; return true;
2819   case BO_EQ: Result = LHS == RHS; return true;
2820   case BO_NE: Result = LHS != RHS; return true;
2821   case BO_Cmp:
2822     llvm_unreachable("BO_Cmp should be handled elsewhere");
2823   }
2824 }
2825 
2826 /// Perform the given binary floating-point operation, in-place, on LHS.
2827 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2828                                   APFloat &LHS, BinaryOperatorKind Opcode,
2829                                   const APFloat &RHS) {
2830   bool DynamicRM;
2831   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2832   APFloat::opStatus St;
2833   switch (Opcode) {
2834   default:
2835     Info.FFDiag(E);
2836     return false;
2837   case BO_Mul:
2838     St = LHS.multiply(RHS, RM);
2839     break;
2840   case BO_Add:
2841     St = LHS.add(RHS, RM);
2842     break;
2843   case BO_Sub:
2844     St = LHS.subtract(RHS, RM);
2845     break;
2846   case BO_Div:
2847     // [expr.mul]p4:
2848     //   If the second operand of / or % is zero the behavior is undefined.
2849     if (RHS.isZero())
2850       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2851     St = LHS.divide(RHS, RM);
2852     break;
2853   }
2854 
2855   // [expr.pre]p4:
2856   //   If during the evaluation of an expression, the result is not
2857   //   mathematically defined [...], the behavior is undefined.
2858   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2859   if (LHS.isNaN()) {
2860     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2861     return Info.noteUndefinedBehavior();
2862   }
2863 
2864   return checkFloatingPointResult(Info, E, St);
2865 }
2866 
2867 static bool handleLogicalOpForVector(const APInt &LHSValue,
2868                                      BinaryOperatorKind Opcode,
2869                                      const APInt &RHSValue, APInt &Result) {
2870   bool LHS = (LHSValue != 0);
2871   bool RHS = (RHSValue != 0);
2872 
2873   if (Opcode == BO_LAnd)
2874     Result = LHS && RHS;
2875   else
2876     Result = LHS || RHS;
2877   return true;
2878 }
2879 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2880                                      BinaryOperatorKind Opcode,
2881                                      const APFloat &RHSValue, APInt &Result) {
2882   bool LHS = !LHSValue.isZero();
2883   bool RHS = !RHSValue.isZero();
2884 
2885   if (Opcode == BO_LAnd)
2886     Result = LHS && RHS;
2887   else
2888     Result = LHS || RHS;
2889   return true;
2890 }
2891 
2892 static bool handleLogicalOpForVector(const APValue &LHSValue,
2893                                      BinaryOperatorKind Opcode,
2894                                      const APValue &RHSValue, APInt &Result) {
2895   // The result is always an int type, however operands match the first.
2896   if (LHSValue.getKind() == APValue::Int)
2897     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2898                                     RHSValue.getInt(), Result);
2899   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2900   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2901                                   RHSValue.getFloat(), Result);
2902 }
2903 
2904 template <typename APTy>
2905 static bool
2906 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2907                                const APTy &RHSValue, APInt &Result) {
2908   switch (Opcode) {
2909   default:
2910     llvm_unreachable("unsupported binary operator");
2911   case BO_EQ:
2912     Result = (LHSValue == RHSValue);
2913     break;
2914   case BO_NE:
2915     Result = (LHSValue != RHSValue);
2916     break;
2917   case BO_LT:
2918     Result = (LHSValue < RHSValue);
2919     break;
2920   case BO_GT:
2921     Result = (LHSValue > RHSValue);
2922     break;
2923   case BO_LE:
2924     Result = (LHSValue <= RHSValue);
2925     break;
2926   case BO_GE:
2927     Result = (LHSValue >= RHSValue);
2928     break;
2929   }
2930 
2931   return true;
2932 }
2933 
2934 static bool handleCompareOpForVector(const APValue &LHSValue,
2935                                      BinaryOperatorKind Opcode,
2936                                      const APValue &RHSValue, APInt &Result) {
2937   // The result is always an int type, however operands match the first.
2938   if (LHSValue.getKind() == APValue::Int)
2939     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2940                                           RHSValue.getInt(), Result);
2941   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2942   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2943                                         RHSValue.getFloat(), Result);
2944 }
2945 
2946 // Perform binary operations for vector types, in place on the LHS.
2947 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2948                                     BinaryOperatorKind Opcode,
2949                                     APValue &LHSValue,
2950                                     const APValue &RHSValue) {
2951   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2952          "Operation not supported on vector types");
2953 
2954   const auto *VT = E->getType()->castAs<VectorType>();
2955   unsigned NumElements = VT->getNumElements();
2956   QualType EltTy = VT->getElementType();
2957 
2958   // In the cases (typically C as I've observed) where we aren't evaluating
2959   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2960   // just give up.
2961   if (!LHSValue.isVector()) {
2962     assert(LHSValue.isLValue() &&
2963            "A vector result that isn't a vector OR uncalculated LValue");
2964     Info.FFDiag(E);
2965     return false;
2966   }
2967 
2968   assert(LHSValue.getVectorLength() == NumElements &&
2969          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2970 
2971   SmallVector<APValue, 4> ResultElements;
2972 
2973   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
2974     APValue LHSElt = LHSValue.getVectorElt(EltNum);
2975     APValue RHSElt = RHSValue.getVectorElt(EltNum);
2976 
2977     if (EltTy->isIntegerType()) {
2978       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
2979                        EltTy->isUnsignedIntegerType()};
2980       bool Success = true;
2981 
2982       if (BinaryOperator::isLogicalOp(Opcode))
2983         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2984       else if (BinaryOperator::isComparisonOp(Opcode))
2985         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2986       else
2987         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
2988                                     RHSElt.getInt(), EltResult);
2989 
2990       if (!Success) {
2991         Info.FFDiag(E);
2992         return false;
2993       }
2994       ResultElements.emplace_back(EltResult);
2995 
2996     } else if (EltTy->isFloatingType()) {
2997       assert(LHSElt.getKind() == APValue::Float &&
2998              RHSElt.getKind() == APValue::Float &&
2999              "Mismatched LHS/RHS/Result Type");
3000       APFloat LHSFloat = LHSElt.getFloat();
3001 
3002       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3003                                  RHSElt.getFloat())) {
3004         Info.FFDiag(E);
3005         return false;
3006       }
3007 
3008       ResultElements.emplace_back(LHSFloat);
3009     }
3010   }
3011 
3012   LHSValue = APValue(ResultElements.data(), ResultElements.size());
3013   return true;
3014 }
3015 
3016 /// Cast an lvalue referring to a base subobject to a derived class, by
3017 /// truncating the lvalue's path to the given length.
3018 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3019                                const RecordDecl *TruncatedType,
3020                                unsigned TruncatedElements) {
3021   SubobjectDesignator &D = Result.Designator;
3022 
3023   // Check we actually point to a derived class object.
3024   if (TruncatedElements == D.Entries.size())
3025     return true;
3026   assert(TruncatedElements >= D.MostDerivedPathLength &&
3027          "not casting to a derived class");
3028   if (!Result.checkSubobject(Info, E, CSK_Derived))
3029     return false;
3030 
3031   // Truncate the path to the subobject, and remove any derived-to-base offsets.
3032   const RecordDecl *RD = TruncatedType;
3033   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3034     if (RD->isInvalidDecl()) return false;
3035     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3036     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3037     if (isVirtualBaseClass(D.Entries[I]))
3038       Result.Offset -= Layout.getVBaseClassOffset(Base);
3039     else
3040       Result.Offset -= Layout.getBaseClassOffset(Base);
3041     RD = Base;
3042   }
3043   D.Entries.resize(TruncatedElements);
3044   return true;
3045 }
3046 
3047 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3048                                    const CXXRecordDecl *Derived,
3049                                    const CXXRecordDecl *Base,
3050                                    const ASTRecordLayout *RL = nullptr) {
3051   if (!RL) {
3052     if (Derived->isInvalidDecl()) return false;
3053     RL = &Info.Ctx.getASTRecordLayout(Derived);
3054   }
3055 
3056   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3057   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3058   return true;
3059 }
3060 
3061 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3062                              const CXXRecordDecl *DerivedDecl,
3063                              const CXXBaseSpecifier *Base) {
3064   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3065 
3066   if (!Base->isVirtual())
3067     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3068 
3069   SubobjectDesignator &D = Obj.Designator;
3070   if (D.Invalid)
3071     return false;
3072 
3073   // Extract most-derived object and corresponding type.
3074   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3075   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3076     return false;
3077 
3078   // Find the virtual base class.
3079   if (DerivedDecl->isInvalidDecl()) return false;
3080   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3081   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3082   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3083   return true;
3084 }
3085 
3086 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3087                                  QualType Type, LValue &Result) {
3088   for (CastExpr::path_const_iterator PathI = E->path_begin(),
3089                                      PathE = E->path_end();
3090        PathI != PathE; ++PathI) {
3091     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3092                           *PathI))
3093       return false;
3094     Type = (*PathI)->getType();
3095   }
3096   return true;
3097 }
3098 
3099 /// Cast an lvalue referring to a derived class to a known base subobject.
3100 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3101                             const CXXRecordDecl *DerivedRD,
3102                             const CXXRecordDecl *BaseRD) {
3103   CXXBasePaths Paths(/*FindAmbiguities=*/false,
3104                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
3105   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3106     llvm_unreachable("Class must be derived from the passed in base class!");
3107 
3108   for (CXXBasePathElement &Elem : Paths.front())
3109     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3110       return false;
3111   return true;
3112 }
3113 
3114 /// Update LVal to refer to the given field, which must be a member of the type
3115 /// currently described by LVal.
3116 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3117                                const FieldDecl *FD,
3118                                const ASTRecordLayout *RL = nullptr) {
3119   if (!RL) {
3120     if (FD->getParent()->isInvalidDecl()) return false;
3121     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3122   }
3123 
3124   unsigned I = FD->getFieldIndex();
3125   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3126   LVal.addDecl(Info, E, FD);
3127   return true;
3128 }
3129 
3130 /// Update LVal to refer to the given indirect field.
3131 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3132                                        LValue &LVal,
3133                                        const IndirectFieldDecl *IFD) {
3134   for (const auto *C : IFD->chain())
3135     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3136       return false;
3137   return true;
3138 }
3139 
3140 /// Get the size of the given type in char units.
3141 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3142                          QualType Type, CharUnits &Size) {
3143   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3144   // extension.
3145   if (Type->isVoidType() || Type->isFunctionType()) {
3146     Size = CharUnits::One();
3147     return true;
3148   }
3149 
3150   if (Type->isDependentType()) {
3151     Info.FFDiag(Loc);
3152     return false;
3153   }
3154 
3155   if (!Type->isConstantSizeType()) {
3156     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3157     // FIXME: Better diagnostic.
3158     Info.FFDiag(Loc);
3159     return false;
3160   }
3161 
3162   Size = Info.Ctx.getTypeSizeInChars(Type);
3163   return true;
3164 }
3165 
3166 /// Update a pointer value to model pointer arithmetic.
3167 /// \param Info - Information about the ongoing evaluation.
3168 /// \param E - The expression being evaluated, for diagnostic purposes.
3169 /// \param LVal - The pointer value to be updated.
3170 /// \param EltTy - The pointee type represented by LVal.
3171 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3172 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3173                                         LValue &LVal, QualType EltTy,
3174                                         APSInt Adjustment) {
3175   CharUnits SizeOfPointee;
3176   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3177     return false;
3178 
3179   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3180   return true;
3181 }
3182 
3183 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3184                                         LValue &LVal, QualType EltTy,
3185                                         int64_t Adjustment) {
3186   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3187                                      APSInt::get(Adjustment));
3188 }
3189 
3190 /// Update an lvalue to refer to a component of a complex number.
3191 /// \param Info - Information about the ongoing evaluation.
3192 /// \param LVal - The lvalue to be updated.
3193 /// \param EltTy - The complex number's component type.
3194 /// \param Imag - False for the real component, true for the imaginary.
3195 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3196                                        LValue &LVal, QualType EltTy,
3197                                        bool Imag) {
3198   if (Imag) {
3199     CharUnits SizeOfComponent;
3200     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3201       return false;
3202     LVal.Offset += SizeOfComponent;
3203   }
3204   LVal.addComplex(Info, E, EltTy, Imag);
3205   return true;
3206 }
3207 
3208 /// Try to evaluate the initializer for a variable declaration.
3209 ///
3210 /// \param Info   Information about the ongoing evaluation.
3211 /// \param E      An expression to be used when printing diagnostics.
3212 /// \param VD     The variable whose initializer should be obtained.
3213 /// \param Version The version of the variable within the frame.
3214 /// \param Frame  The frame in which the variable was created. Must be null
3215 ///               if this variable is not local to the evaluation.
3216 /// \param Result Filled in with a pointer to the value of the variable.
3217 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3218                                 const VarDecl *VD, CallStackFrame *Frame,
3219                                 unsigned Version, APValue *&Result) {
3220   APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3221 
3222   // If this is a local variable, dig out its value.
3223   if (Frame) {
3224     Result = Frame->getTemporary(VD, Version);
3225     if (Result)
3226       return true;
3227 
3228     if (!isa<ParmVarDecl>(VD)) {
3229       // Assume variables referenced within a lambda's call operator that were
3230       // not declared within the call operator are captures and during checking
3231       // of a potential constant expression, assume they are unknown constant
3232       // expressions.
3233       assert(isLambdaCallOperator(Frame->Callee) &&
3234              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3235              "missing value for local variable");
3236       if (Info.checkingPotentialConstantExpression())
3237         return false;
3238       // FIXME: This diagnostic is bogus; we do support captures. Is this code
3239       // still reachable at all?
3240       Info.FFDiag(E->getBeginLoc(),
3241                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3242           << "captures not currently allowed";
3243       return false;
3244     }
3245   }
3246 
3247   // If we're currently evaluating the initializer of this declaration, use that
3248   // in-flight value.
3249   if (Info.EvaluatingDecl == Base) {
3250     Result = Info.EvaluatingDeclValue;
3251     return true;
3252   }
3253 
3254   if (isa<ParmVarDecl>(VD)) {
3255     // Assume parameters of a potential constant expression are usable in
3256     // constant expressions.
3257     if (!Info.checkingPotentialConstantExpression() ||
3258         !Info.CurrentCall->Callee ||
3259         !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3260       if (Info.getLangOpts().CPlusPlus11) {
3261         Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3262             << VD;
3263         NoteLValueLocation(Info, Base);
3264       } else {
3265         Info.FFDiag(E);
3266       }
3267     }
3268     return false;
3269   }
3270 
3271   // Dig out the initializer, and use the declaration which it's attached to.
3272   // FIXME: We should eventually check whether the variable has a reachable
3273   // initializing declaration.
3274   const Expr *Init = VD->getAnyInitializer(VD);
3275   if (!Init) {
3276     // Don't diagnose during potential constant expression checking; an
3277     // initializer might be added later.
3278     if (!Info.checkingPotentialConstantExpression()) {
3279       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3280         << VD;
3281       NoteLValueLocation(Info, Base);
3282     }
3283     return false;
3284   }
3285 
3286   if (Init->isValueDependent()) {
3287     // The DeclRefExpr is not value-dependent, but the variable it refers to
3288     // has a value-dependent initializer. This should only happen in
3289     // constant-folding cases, where the variable is not actually of a suitable
3290     // type for use in a constant expression (otherwise the DeclRefExpr would
3291     // have been value-dependent too), so diagnose that.
3292     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3293     if (!Info.checkingPotentialConstantExpression()) {
3294       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3295                          ? diag::note_constexpr_ltor_non_constexpr
3296                          : diag::note_constexpr_ltor_non_integral, 1)
3297           << VD << VD->getType();
3298       NoteLValueLocation(Info, Base);
3299     }
3300     return false;
3301   }
3302 
3303   // Check that we can fold the initializer. In C++, we will have already done
3304   // this in the cases where it matters for conformance.
3305   SmallVector<PartialDiagnosticAt, 8> Notes;
3306   if (!VD->evaluateValue(Notes)) {
3307     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
3308               Notes.size() + 1) << VD;
3309     NoteLValueLocation(Info, Base);
3310     Info.addNotes(Notes);
3311     return false;
3312   }
3313 
3314   // Check that the variable is actually usable in constant expressions. For a
3315   // const integral variable or a reference, we might have a non-constant
3316   // initializer that we can nonetheless evaluate the initializer for. Such
3317   // variables are not usable in constant expressions. In C++98, the
3318   // initializer also syntactically needs to be an ICE.
3319   //
3320   // FIXME: We don't diagnose cases that aren't potentially usable in constant
3321   // expressions here; doing so would regress diagnostics for things like
3322   // reading from a volatile constexpr variable.
3323   if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3324        VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3325       ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3326        !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3327     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3328     NoteLValueLocation(Info, Base);
3329   }
3330 
3331   // Never use the initializer of a weak variable, not even for constant
3332   // folding. We can't be sure that this is the definition that will be used.
3333   if (VD->isWeak()) {
3334     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3335     NoteLValueLocation(Info, Base);
3336     return false;
3337   }
3338 
3339   Result = VD->getEvaluatedValue();
3340   return true;
3341 }
3342 
3343 /// Get the base index of the given base class within an APValue representing
3344 /// the given derived class.
3345 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3346                              const CXXRecordDecl *Base) {
3347   Base = Base->getCanonicalDecl();
3348   unsigned Index = 0;
3349   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3350          E = Derived->bases_end(); I != E; ++I, ++Index) {
3351     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3352       return Index;
3353   }
3354 
3355   llvm_unreachable("base class missing from derived class's bases list");
3356 }
3357 
3358 /// Extract the value of a character from a string literal.
3359 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3360                                             uint64_t Index) {
3361   assert(!isa<SourceLocExpr>(Lit) &&
3362          "SourceLocExpr should have already been converted to a StringLiteral");
3363 
3364   // FIXME: Support MakeStringConstant
3365   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3366     std::string Str;
3367     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3368     assert(Index <= Str.size() && "Index too large");
3369     return APSInt::getUnsigned(Str.c_str()[Index]);
3370   }
3371 
3372   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3373     Lit = PE->getFunctionName();
3374   const StringLiteral *S = cast<StringLiteral>(Lit);
3375   const ConstantArrayType *CAT =
3376       Info.Ctx.getAsConstantArrayType(S->getType());
3377   assert(CAT && "string literal isn't an array");
3378   QualType CharType = CAT->getElementType();
3379   assert(CharType->isIntegerType() && "unexpected character type");
3380 
3381   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3382                CharType->isUnsignedIntegerType());
3383   if (Index < S->getLength())
3384     Value = S->getCodeUnit(Index);
3385   return Value;
3386 }
3387 
3388 // Expand a string literal into an array of characters.
3389 //
3390 // FIXME: This is inefficient; we should probably introduce something similar
3391 // to the LLVM ConstantDataArray to make this cheaper.
3392 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3393                                 APValue &Result,
3394                                 QualType AllocType = QualType()) {
3395   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3396       AllocType.isNull() ? S->getType() : AllocType);
3397   assert(CAT && "string literal isn't an array");
3398   QualType CharType = CAT->getElementType();
3399   assert(CharType->isIntegerType() && "unexpected character type");
3400 
3401   unsigned Elts = CAT->getSize().getZExtValue();
3402   Result = APValue(APValue::UninitArray(),
3403                    std::min(S->getLength(), Elts), Elts);
3404   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3405                CharType->isUnsignedIntegerType());
3406   if (Result.hasArrayFiller())
3407     Result.getArrayFiller() = APValue(Value);
3408   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3409     Value = S->getCodeUnit(I);
3410     Result.getArrayInitializedElt(I) = APValue(Value);
3411   }
3412 }
3413 
3414 // Expand an array so that it has more than Index filled elements.
3415 static void expandArray(APValue &Array, unsigned Index) {
3416   unsigned Size = Array.getArraySize();
3417   assert(Index < Size);
3418 
3419   // Always at least double the number of elements for which we store a value.
3420   unsigned OldElts = Array.getArrayInitializedElts();
3421   unsigned NewElts = std::max(Index+1, OldElts * 2);
3422   NewElts = std::min(Size, std::max(NewElts, 8u));
3423 
3424   // Copy the data across.
3425   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3426   for (unsigned I = 0; I != OldElts; ++I)
3427     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3428   for (unsigned I = OldElts; I != NewElts; ++I)
3429     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3430   if (NewValue.hasArrayFiller())
3431     NewValue.getArrayFiller() = Array.getArrayFiller();
3432   Array.swap(NewValue);
3433 }
3434 
3435 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3436 /// conversion. If it's of class type, we may assume that the copy operation
3437 /// is trivial. Note that this is never true for a union type with fields
3438 /// (because the copy always "reads" the active member) and always true for
3439 /// a non-class type.
3440 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3441 static bool isReadByLvalueToRvalueConversion(QualType T) {
3442   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3443   return !RD || isReadByLvalueToRvalueConversion(RD);
3444 }
3445 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3446   // FIXME: A trivial copy of a union copies the object representation, even if
3447   // the union is empty.
3448   if (RD->isUnion())
3449     return !RD->field_empty();
3450   if (RD->isEmpty())
3451     return false;
3452 
3453   for (auto *Field : RD->fields())
3454     if (!Field->isUnnamedBitfield() &&
3455         isReadByLvalueToRvalueConversion(Field->getType()))
3456       return true;
3457 
3458   for (auto &BaseSpec : RD->bases())
3459     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3460       return true;
3461 
3462   return false;
3463 }
3464 
3465 /// Diagnose an attempt to read from any unreadable field within the specified
3466 /// type, which might be a class type.
3467 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3468                                   QualType T) {
3469   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3470   if (!RD)
3471     return false;
3472 
3473   if (!RD->hasMutableFields())
3474     return false;
3475 
3476   for (auto *Field : RD->fields()) {
3477     // If we're actually going to read this field in some way, then it can't
3478     // be mutable. If we're in a union, then assigning to a mutable field
3479     // (even an empty one) can change the active member, so that's not OK.
3480     // FIXME: Add core issue number for the union case.
3481     if (Field->isMutable() &&
3482         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3483       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3484       Info.Note(Field->getLocation(), diag::note_declared_at);
3485       return true;
3486     }
3487 
3488     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3489       return true;
3490   }
3491 
3492   for (auto &BaseSpec : RD->bases())
3493     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3494       return true;
3495 
3496   // All mutable fields were empty, and thus not actually read.
3497   return false;
3498 }
3499 
3500 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3501                                         APValue::LValueBase Base,
3502                                         bool MutableSubobject = false) {
3503   // A temporary or transient heap allocation we created.
3504   if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3505     return true;
3506 
3507   switch (Info.IsEvaluatingDecl) {
3508   case EvalInfo::EvaluatingDeclKind::None:
3509     return false;
3510 
3511   case EvalInfo::EvaluatingDeclKind::Ctor:
3512     // The variable whose initializer we're evaluating.
3513     if (Info.EvaluatingDecl == Base)
3514       return true;
3515 
3516     // A temporary lifetime-extended by the variable whose initializer we're
3517     // evaluating.
3518     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3519       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3520         return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3521     return false;
3522 
3523   case EvalInfo::EvaluatingDeclKind::Dtor:
3524     // C++2a [expr.const]p6:
3525     //   [during constant destruction] the lifetime of a and its non-mutable
3526     //   subobjects (but not its mutable subobjects) [are] considered to start
3527     //   within e.
3528     if (MutableSubobject || Base != Info.EvaluatingDecl)
3529       return false;
3530     // FIXME: We can meaningfully extend this to cover non-const objects, but
3531     // we will need special handling: we should be able to access only
3532     // subobjects of such objects that are themselves declared const.
3533     QualType T = getType(Base);
3534     return T.isConstQualified() || T->isReferenceType();
3535   }
3536 
3537   llvm_unreachable("unknown evaluating decl kind");
3538 }
3539 
3540 namespace {
3541 /// A handle to a complete object (an object that is not a subobject of
3542 /// another object).
3543 struct CompleteObject {
3544   /// The identity of the object.
3545   APValue::LValueBase Base;
3546   /// The value of the complete object.
3547   APValue *Value;
3548   /// The type of the complete object.
3549   QualType Type;
3550 
3551   CompleteObject() : Value(nullptr) {}
3552   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3553       : Base(Base), Value(Value), Type(Type) {}
3554 
3555   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3556     // If this isn't a "real" access (eg, if it's just accessing the type
3557     // info), allow it. We assume the type doesn't change dynamically for
3558     // subobjects of constexpr objects (even though we'd hit UB here if it
3559     // did). FIXME: Is this right?
3560     if (!isAnyAccess(AK))
3561       return true;
3562 
3563     // In C++14 onwards, it is permitted to read a mutable member whose
3564     // lifetime began within the evaluation.
3565     // FIXME: Should we also allow this in C++11?
3566     if (!Info.getLangOpts().CPlusPlus14)
3567       return false;
3568     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3569   }
3570 
3571   explicit operator bool() const { return !Type.isNull(); }
3572 };
3573 } // end anonymous namespace
3574 
3575 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3576                                  bool IsMutable = false) {
3577   // C++ [basic.type.qualifier]p1:
3578   // - A const object is an object of type const T or a non-mutable subobject
3579   //   of a const object.
3580   if (ObjType.isConstQualified() && !IsMutable)
3581     SubobjType.addConst();
3582   // - A volatile object is an object of type const T or a subobject of a
3583   //   volatile object.
3584   if (ObjType.isVolatileQualified())
3585     SubobjType.addVolatile();
3586   return SubobjType;
3587 }
3588 
3589 /// Find the designated sub-object of an rvalue.
3590 template<typename SubobjectHandler>
3591 typename SubobjectHandler::result_type
3592 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3593               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3594   if (Sub.Invalid)
3595     // A diagnostic will have already been produced.
3596     return handler.failed();
3597   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3598     if (Info.getLangOpts().CPlusPlus11)
3599       Info.FFDiag(E, Sub.isOnePastTheEnd()
3600                          ? diag::note_constexpr_access_past_end
3601                          : diag::note_constexpr_access_unsized_array)
3602           << handler.AccessKind;
3603     else
3604       Info.FFDiag(E);
3605     return handler.failed();
3606   }
3607 
3608   APValue *O = Obj.Value;
3609   QualType ObjType = Obj.Type;
3610   const FieldDecl *LastField = nullptr;
3611   const FieldDecl *VolatileField = nullptr;
3612 
3613   // Walk the designator's path to find the subobject.
3614   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3615     // Reading an indeterminate value is undefined, but assigning over one is OK.
3616     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3617         (O->isIndeterminate() &&
3618          !isValidIndeterminateAccess(handler.AccessKind))) {
3619       if (!Info.checkingPotentialConstantExpression())
3620         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3621             << handler.AccessKind << O->isIndeterminate();
3622       return handler.failed();
3623     }
3624 
3625     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3626     //    const and volatile semantics are not applied on an object under
3627     //    {con,de}struction.
3628     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3629         ObjType->isRecordType() &&
3630         Info.isEvaluatingCtorDtor(
3631             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3632                                          Sub.Entries.begin() + I)) !=
3633                           ConstructionPhase::None) {
3634       ObjType = Info.Ctx.getCanonicalType(ObjType);
3635       ObjType.removeLocalConst();
3636       ObjType.removeLocalVolatile();
3637     }
3638 
3639     // If this is our last pass, check that the final object type is OK.
3640     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3641       // Accesses to volatile objects are prohibited.
3642       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3643         if (Info.getLangOpts().CPlusPlus) {
3644           int DiagKind;
3645           SourceLocation Loc;
3646           const NamedDecl *Decl = nullptr;
3647           if (VolatileField) {
3648             DiagKind = 2;
3649             Loc = VolatileField->getLocation();
3650             Decl = VolatileField;
3651           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3652             DiagKind = 1;
3653             Loc = VD->getLocation();
3654             Decl = VD;
3655           } else {
3656             DiagKind = 0;
3657             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3658               Loc = E->getExprLoc();
3659           }
3660           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3661               << handler.AccessKind << DiagKind << Decl;
3662           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3663         } else {
3664           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3665         }
3666         return handler.failed();
3667       }
3668 
3669       // If we are reading an object of class type, there may still be more
3670       // things we need to check: if there are any mutable subobjects, we
3671       // cannot perform this read. (This only happens when performing a trivial
3672       // copy or assignment.)
3673       if (ObjType->isRecordType() &&
3674           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3675           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3676         return handler.failed();
3677     }
3678 
3679     if (I == N) {
3680       if (!handler.found(*O, ObjType))
3681         return false;
3682 
3683       // If we modified a bit-field, truncate it to the right width.
3684       if (isModification(handler.AccessKind) &&
3685           LastField && LastField->isBitField() &&
3686           !truncateBitfieldValue(Info, E, *O, LastField))
3687         return false;
3688 
3689       return true;
3690     }
3691 
3692     LastField = nullptr;
3693     if (ObjType->isArrayType()) {
3694       // Next subobject is an array element.
3695       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3696       assert(CAT && "vla in literal type?");
3697       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3698       if (CAT->getSize().ule(Index)) {
3699         // Note, it should not be possible to form a pointer with a valid
3700         // designator which points more than one past the end of the array.
3701         if (Info.getLangOpts().CPlusPlus11)
3702           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3703             << handler.AccessKind;
3704         else
3705           Info.FFDiag(E);
3706         return handler.failed();
3707       }
3708 
3709       ObjType = CAT->getElementType();
3710 
3711       if (O->getArrayInitializedElts() > Index)
3712         O = &O->getArrayInitializedElt(Index);
3713       else if (!isRead(handler.AccessKind)) {
3714         expandArray(*O, Index);
3715         O = &O->getArrayInitializedElt(Index);
3716       } else
3717         O = &O->getArrayFiller();
3718     } else if (ObjType->isAnyComplexType()) {
3719       // Next subobject is a complex number.
3720       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3721       if (Index > 1) {
3722         if (Info.getLangOpts().CPlusPlus11)
3723           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3724             << handler.AccessKind;
3725         else
3726           Info.FFDiag(E);
3727         return handler.failed();
3728       }
3729 
3730       ObjType = getSubobjectType(
3731           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3732 
3733       assert(I == N - 1 && "extracting subobject of scalar?");
3734       if (O->isComplexInt()) {
3735         return handler.found(Index ? O->getComplexIntImag()
3736                                    : O->getComplexIntReal(), ObjType);
3737       } else {
3738         assert(O->isComplexFloat());
3739         return handler.found(Index ? O->getComplexFloatImag()
3740                                    : O->getComplexFloatReal(), ObjType);
3741       }
3742     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3743       if (Field->isMutable() &&
3744           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3745         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3746           << handler.AccessKind << Field;
3747         Info.Note(Field->getLocation(), diag::note_declared_at);
3748         return handler.failed();
3749       }
3750 
3751       // Next subobject is a class, struct or union field.
3752       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3753       if (RD->isUnion()) {
3754         const FieldDecl *UnionField = O->getUnionField();
3755         if (!UnionField ||
3756             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3757           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3758             // Placement new onto an inactive union member makes it active.
3759             O->setUnion(Field, APValue());
3760           } else {
3761             // FIXME: If O->getUnionValue() is absent, report that there's no
3762             // active union member rather than reporting the prior active union
3763             // member. We'll need to fix nullptr_t to not use APValue() as its
3764             // representation first.
3765             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3766                 << handler.AccessKind << Field << !UnionField << UnionField;
3767             return handler.failed();
3768           }
3769         }
3770         O = &O->getUnionValue();
3771       } else
3772         O = &O->getStructField(Field->getFieldIndex());
3773 
3774       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3775       LastField = Field;
3776       if (Field->getType().isVolatileQualified())
3777         VolatileField = Field;
3778     } else {
3779       // Next subobject is a base class.
3780       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3781       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3782       O = &O->getStructBase(getBaseIndex(Derived, Base));
3783 
3784       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3785     }
3786   }
3787 }
3788 
3789 namespace {
3790 struct ExtractSubobjectHandler {
3791   EvalInfo &Info;
3792   const Expr *E;
3793   APValue &Result;
3794   const AccessKinds AccessKind;
3795 
3796   typedef bool result_type;
3797   bool failed() { return false; }
3798   bool found(APValue &Subobj, QualType SubobjType) {
3799     Result = Subobj;
3800     if (AccessKind == AK_ReadObjectRepresentation)
3801       return true;
3802     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3803   }
3804   bool found(APSInt &Value, QualType SubobjType) {
3805     Result = APValue(Value);
3806     return true;
3807   }
3808   bool found(APFloat &Value, QualType SubobjType) {
3809     Result = APValue(Value);
3810     return true;
3811   }
3812 };
3813 } // end anonymous namespace
3814 
3815 /// Extract the designated sub-object of an rvalue.
3816 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3817                              const CompleteObject &Obj,
3818                              const SubobjectDesignator &Sub, APValue &Result,
3819                              AccessKinds AK = AK_Read) {
3820   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3821   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3822   return findSubobject(Info, E, Obj, Sub, Handler);
3823 }
3824 
3825 namespace {
3826 struct ModifySubobjectHandler {
3827   EvalInfo &Info;
3828   APValue &NewVal;
3829   const Expr *E;
3830 
3831   typedef bool result_type;
3832   static const AccessKinds AccessKind = AK_Assign;
3833 
3834   bool checkConst(QualType QT) {
3835     // Assigning to a const object has undefined behavior.
3836     if (QT.isConstQualified()) {
3837       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3838       return false;
3839     }
3840     return true;
3841   }
3842 
3843   bool failed() { return false; }
3844   bool found(APValue &Subobj, QualType SubobjType) {
3845     if (!checkConst(SubobjType))
3846       return false;
3847     // We've been given ownership of NewVal, so just swap it in.
3848     Subobj.swap(NewVal);
3849     return true;
3850   }
3851   bool found(APSInt &Value, QualType SubobjType) {
3852     if (!checkConst(SubobjType))
3853       return false;
3854     if (!NewVal.isInt()) {
3855       // Maybe trying to write a cast pointer value into a complex?
3856       Info.FFDiag(E);
3857       return false;
3858     }
3859     Value = NewVal.getInt();
3860     return true;
3861   }
3862   bool found(APFloat &Value, QualType SubobjType) {
3863     if (!checkConst(SubobjType))
3864       return false;
3865     Value = NewVal.getFloat();
3866     return true;
3867   }
3868 };
3869 } // end anonymous namespace
3870 
3871 const AccessKinds ModifySubobjectHandler::AccessKind;
3872 
3873 /// Update the designated sub-object of an rvalue to the given value.
3874 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3875                             const CompleteObject &Obj,
3876                             const SubobjectDesignator &Sub,
3877                             APValue &NewVal) {
3878   ModifySubobjectHandler Handler = { Info, NewVal, E };
3879   return findSubobject(Info, E, Obj, Sub, Handler);
3880 }
3881 
3882 /// Find the position where two subobject designators diverge, or equivalently
3883 /// the length of the common initial subsequence.
3884 static unsigned FindDesignatorMismatch(QualType ObjType,
3885                                        const SubobjectDesignator &A,
3886                                        const SubobjectDesignator &B,
3887                                        bool &WasArrayIndex) {
3888   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3889   for (/**/; I != N; ++I) {
3890     if (!ObjType.isNull() &&
3891         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3892       // Next subobject is an array element.
3893       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3894         WasArrayIndex = true;
3895         return I;
3896       }
3897       if (ObjType->isAnyComplexType())
3898         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3899       else
3900         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3901     } else {
3902       if (A.Entries[I].getAsBaseOrMember() !=
3903           B.Entries[I].getAsBaseOrMember()) {
3904         WasArrayIndex = false;
3905         return I;
3906       }
3907       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3908         // Next subobject is a field.
3909         ObjType = FD->getType();
3910       else
3911         // Next subobject is a base class.
3912         ObjType = QualType();
3913     }
3914   }
3915   WasArrayIndex = false;
3916   return I;
3917 }
3918 
3919 /// Determine whether the given subobject designators refer to elements of the
3920 /// same array object.
3921 static bool AreElementsOfSameArray(QualType ObjType,
3922                                    const SubobjectDesignator &A,
3923                                    const SubobjectDesignator &B) {
3924   if (A.Entries.size() != B.Entries.size())
3925     return false;
3926 
3927   bool IsArray = A.MostDerivedIsArrayElement;
3928   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3929     // A is a subobject of the array element.
3930     return false;
3931 
3932   // If A (and B) designates an array element, the last entry will be the array
3933   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3934   // of length 1' case, and the entire path must match.
3935   bool WasArrayIndex;
3936   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3937   return CommonLength >= A.Entries.size() - IsArray;
3938 }
3939 
3940 /// Find the complete object to which an LValue refers.
3941 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3942                                          AccessKinds AK, const LValue &LVal,
3943                                          QualType LValType) {
3944   if (LVal.InvalidBase) {
3945     Info.FFDiag(E);
3946     return CompleteObject();
3947   }
3948 
3949   if (!LVal.Base) {
3950     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3951     return CompleteObject();
3952   }
3953 
3954   CallStackFrame *Frame = nullptr;
3955   unsigned Depth = 0;
3956   if (LVal.getLValueCallIndex()) {
3957     std::tie(Frame, Depth) =
3958         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3959     if (!Frame) {
3960       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3961         << AK << LVal.Base.is<const ValueDecl*>();
3962       NoteLValueLocation(Info, LVal.Base);
3963       return CompleteObject();
3964     }
3965   }
3966 
3967   bool IsAccess = isAnyAccess(AK);
3968 
3969   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3970   // is not a constant expression (even if the object is non-volatile). We also
3971   // apply this rule to C++98, in order to conform to the expected 'volatile'
3972   // semantics.
3973   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3974     if (Info.getLangOpts().CPlusPlus)
3975       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3976         << AK << LValType;
3977     else
3978       Info.FFDiag(E);
3979     return CompleteObject();
3980   }
3981 
3982   // Compute value storage location and type of base object.
3983   APValue *BaseVal = nullptr;
3984   QualType BaseType = getType(LVal.Base);
3985 
3986   if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
3987       lifetimeStartedInEvaluation(Info, LVal.Base)) {
3988     // This is the object whose initializer we're evaluating, so its lifetime
3989     // started in the current evaluation.
3990     BaseVal = Info.EvaluatingDeclValue;
3991   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
3992     // Allow reading from a GUID declaration.
3993     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
3994       if (isModification(AK)) {
3995         // All the remaining cases do not permit modification of the object.
3996         Info.FFDiag(E, diag::note_constexpr_modify_global);
3997         return CompleteObject();
3998       }
3999       APValue &V = GD->getAsAPValue();
4000       if (V.isAbsent()) {
4001         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4002             << GD->getType();
4003         return CompleteObject();
4004       }
4005       return CompleteObject(LVal.Base, &V, GD->getType());
4006     }
4007 
4008     // Allow reading from template parameter objects.
4009     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4010       if (isModification(AK)) {
4011         Info.FFDiag(E, diag::note_constexpr_modify_global);
4012         return CompleteObject();
4013       }
4014       return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4015                             TPO->getType());
4016     }
4017 
4018     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4019     // In C++11, constexpr, non-volatile variables initialized with constant
4020     // expressions are constant expressions too. Inside constexpr functions,
4021     // parameters are constant expressions even if they're non-const.
4022     // In C++1y, objects local to a constant expression (those with a Frame) are
4023     // both readable and writable inside constant expressions.
4024     // In C, such things can also be folded, although they are not ICEs.
4025     const VarDecl *VD = dyn_cast<VarDecl>(D);
4026     if (VD) {
4027       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4028         VD = VDef;
4029     }
4030     if (!VD || VD->isInvalidDecl()) {
4031       Info.FFDiag(E);
4032       return CompleteObject();
4033     }
4034 
4035     bool IsConstant = BaseType.isConstant(Info.Ctx);
4036 
4037     // Unless we're looking at a local variable or argument in a constexpr call,
4038     // the variable we're reading must be const.
4039     if (!Frame) {
4040       if (IsAccess && isa<ParmVarDecl>(VD)) {
4041         // Access of a parameter that's not associated with a frame isn't going
4042         // to work out, but we can leave it to evaluateVarDeclInit to provide a
4043         // suitable diagnostic.
4044       } else if (Info.getLangOpts().CPlusPlus14 &&
4045                  lifetimeStartedInEvaluation(Info, LVal.Base)) {
4046         // OK, we can read and modify an object if we're in the process of
4047         // evaluating its initializer, because its lifetime began in this
4048         // evaluation.
4049       } else if (isModification(AK)) {
4050         // All the remaining cases do not permit modification of the object.
4051         Info.FFDiag(E, diag::note_constexpr_modify_global);
4052         return CompleteObject();
4053       } else if (VD->isConstexpr()) {
4054         // OK, we can read this variable.
4055       } else if (BaseType->isIntegralOrEnumerationType()) {
4056         if (!IsConstant) {
4057           if (!IsAccess)
4058             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4059           if (Info.getLangOpts().CPlusPlus) {
4060             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4061             Info.Note(VD->getLocation(), diag::note_declared_at);
4062           } else {
4063             Info.FFDiag(E);
4064           }
4065           return CompleteObject();
4066         }
4067       } else if (!IsAccess) {
4068         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4069       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4070                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4071         // This variable might end up being constexpr. Don't diagnose it yet.
4072       } else if (IsConstant) {
4073         // Keep evaluating to see what we can do. In particular, we support
4074         // folding of const floating-point types, in order to make static const
4075         // data members of such types (supported as an extension) more useful.
4076         if (Info.getLangOpts().CPlusPlus) {
4077           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4078                               ? diag::note_constexpr_ltor_non_constexpr
4079                               : diag::note_constexpr_ltor_non_integral, 1)
4080               << VD << BaseType;
4081           Info.Note(VD->getLocation(), diag::note_declared_at);
4082         } else {
4083           Info.CCEDiag(E);
4084         }
4085       } else {
4086         // Never allow reading a non-const value.
4087         if (Info.getLangOpts().CPlusPlus) {
4088           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4089                              ? diag::note_constexpr_ltor_non_constexpr
4090                              : diag::note_constexpr_ltor_non_integral, 1)
4091               << VD << BaseType;
4092           Info.Note(VD->getLocation(), diag::note_declared_at);
4093         } else {
4094           Info.FFDiag(E);
4095         }
4096         return CompleteObject();
4097       }
4098     }
4099 
4100     if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4101       return CompleteObject();
4102   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4103     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
4104     if (!Alloc) {
4105       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4106       return CompleteObject();
4107     }
4108     return CompleteObject(LVal.Base, &(*Alloc)->Value,
4109                           LVal.Base.getDynamicAllocType());
4110   } else {
4111     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4112 
4113     if (!Frame) {
4114       if (const MaterializeTemporaryExpr *MTE =
4115               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4116         assert(MTE->getStorageDuration() == SD_Static &&
4117                "should have a frame for a non-global materialized temporary");
4118 
4119         // C++20 [expr.const]p4: [DR2126]
4120         //   An object or reference is usable in constant expressions if it is
4121         //   - a temporary object of non-volatile const-qualified literal type
4122         //     whose lifetime is extended to that of a variable that is usable
4123         //     in constant expressions
4124         //
4125         // C++20 [expr.const]p5:
4126         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4127         //   - a non-volatile glvalue that refers to an object that is usable
4128         //     in constant expressions, or
4129         //   - a non-volatile glvalue of literal type that refers to a
4130         //     non-volatile object whose lifetime began within the evaluation
4131         //     of E;
4132         //
4133         // C++11 misses the 'began within the evaluation of e' check and
4134         // instead allows all temporaries, including things like:
4135         //   int &&r = 1;
4136         //   int x = ++r;
4137         //   constexpr int k = r;
4138         // Therefore we use the C++14-onwards rules in C++11 too.
4139         //
4140         // Note that temporaries whose lifetimes began while evaluating a
4141         // variable's constructor are not usable while evaluating the
4142         // corresponding destructor, not even if they're of const-qualified
4143         // types.
4144         if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4145             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4146           if (!IsAccess)
4147             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4148           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4149           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4150           return CompleteObject();
4151         }
4152 
4153         BaseVal = MTE->getOrCreateValue(false);
4154         assert(BaseVal && "got reference to unevaluated temporary");
4155       } else {
4156         if (!IsAccess)
4157           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4158         APValue Val;
4159         LVal.moveInto(Val);
4160         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4161             << AK
4162             << Val.getAsString(Info.Ctx,
4163                                Info.Ctx.getLValueReferenceType(LValType));
4164         NoteLValueLocation(Info, LVal.Base);
4165         return CompleteObject();
4166       }
4167     } else {
4168       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4169       assert(BaseVal && "missing value for temporary");
4170     }
4171   }
4172 
4173   // In C++14, we can't safely access any mutable state when we might be
4174   // evaluating after an unmodeled side effect. Parameters are modeled as state
4175   // in the caller, but aren't visible once the call returns, so they can be
4176   // modified in a speculatively-evaluated call.
4177   //
4178   // FIXME: Not all local state is mutable. Allow local constant subobjects
4179   // to be read here (but take care with 'mutable' fields).
4180   unsigned VisibleDepth = Depth;
4181   if (llvm::isa_and_nonnull<ParmVarDecl>(
4182           LVal.Base.dyn_cast<const ValueDecl *>()))
4183     ++VisibleDepth;
4184   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4185        Info.EvalStatus.HasSideEffects) ||
4186       (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4187     return CompleteObject();
4188 
4189   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4190 }
4191 
4192 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4193 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4194 /// glvalue referred to by an entity of reference type.
4195 ///
4196 /// \param Info - Information about the ongoing evaluation.
4197 /// \param Conv - The expression for which we are performing the conversion.
4198 ///               Used for diagnostics.
4199 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4200 ///               case of a non-class type).
4201 /// \param LVal - The glvalue on which we are attempting to perform this action.
4202 /// \param RVal - The produced value will be placed here.
4203 /// \param WantObjectRepresentation - If true, we're looking for the object
4204 ///               representation rather than the value, and in particular,
4205 ///               there is no requirement that the result be fully initialized.
4206 static bool
4207 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4208                                const LValue &LVal, APValue &RVal,
4209                                bool WantObjectRepresentation = false) {
4210   if (LVal.Designator.Invalid)
4211     return false;
4212 
4213   // Check for special cases where there is no existing APValue to look at.
4214   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4215 
4216   AccessKinds AK =
4217       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4218 
4219   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4220     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4221       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4222       // initializer until now for such expressions. Such an expression can't be
4223       // an ICE in C, so this only matters for fold.
4224       if (Type.isVolatileQualified()) {
4225         Info.FFDiag(Conv);
4226         return false;
4227       }
4228       APValue Lit;
4229       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4230         return false;
4231       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4232       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4233     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4234       // Special-case character extraction so we don't have to construct an
4235       // APValue for the whole string.
4236       assert(LVal.Designator.Entries.size() <= 1 &&
4237              "Can only read characters from string literals");
4238       if (LVal.Designator.Entries.empty()) {
4239         // Fail for now for LValue to RValue conversion of an array.
4240         // (This shouldn't show up in C/C++, but it could be triggered by a
4241         // weird EvaluateAsRValue call from a tool.)
4242         Info.FFDiag(Conv);
4243         return false;
4244       }
4245       if (LVal.Designator.isOnePastTheEnd()) {
4246         if (Info.getLangOpts().CPlusPlus11)
4247           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4248         else
4249           Info.FFDiag(Conv);
4250         return false;
4251       }
4252       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4253       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4254       return true;
4255     }
4256   }
4257 
4258   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4259   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4260 }
4261 
4262 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4263 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4264                              QualType LValType, APValue &Val) {
4265   if (LVal.Designator.Invalid)
4266     return false;
4267 
4268   if (!Info.getLangOpts().CPlusPlus14) {
4269     Info.FFDiag(E);
4270     return false;
4271   }
4272 
4273   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4274   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4275 }
4276 
4277 namespace {
4278 struct CompoundAssignSubobjectHandler {
4279   EvalInfo &Info;
4280   const CompoundAssignOperator *E;
4281   QualType PromotedLHSType;
4282   BinaryOperatorKind Opcode;
4283   const APValue &RHS;
4284 
4285   static const AccessKinds AccessKind = AK_Assign;
4286 
4287   typedef bool result_type;
4288 
4289   bool checkConst(QualType QT) {
4290     // Assigning to a const object has undefined behavior.
4291     if (QT.isConstQualified()) {
4292       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4293       return false;
4294     }
4295     return true;
4296   }
4297 
4298   bool failed() { return false; }
4299   bool found(APValue &Subobj, QualType SubobjType) {
4300     switch (Subobj.getKind()) {
4301     case APValue::Int:
4302       return found(Subobj.getInt(), SubobjType);
4303     case APValue::Float:
4304       return found(Subobj.getFloat(), SubobjType);
4305     case APValue::ComplexInt:
4306     case APValue::ComplexFloat:
4307       // FIXME: Implement complex compound assignment.
4308       Info.FFDiag(E);
4309       return false;
4310     case APValue::LValue:
4311       return foundPointer(Subobj, SubobjType);
4312     case APValue::Vector:
4313       return foundVector(Subobj, SubobjType);
4314     default:
4315       // FIXME: can this happen?
4316       Info.FFDiag(E);
4317       return false;
4318     }
4319   }
4320 
4321   bool foundVector(APValue &Value, QualType SubobjType) {
4322     if (!checkConst(SubobjType))
4323       return false;
4324 
4325     if (!SubobjType->isVectorType()) {
4326       Info.FFDiag(E);
4327       return false;
4328     }
4329     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4330   }
4331 
4332   bool found(APSInt &Value, QualType SubobjType) {
4333     if (!checkConst(SubobjType))
4334       return false;
4335 
4336     if (!SubobjType->isIntegerType()) {
4337       // We don't support compound assignment on integer-cast-to-pointer
4338       // values.
4339       Info.FFDiag(E);
4340       return false;
4341     }
4342 
4343     if (RHS.isInt()) {
4344       APSInt LHS =
4345           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4346       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4347         return false;
4348       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4349       return true;
4350     } else if (RHS.isFloat()) {
4351       const FPOptions FPO = E->getFPFeaturesInEffect(
4352                                     Info.Ctx.getLangOpts());
4353       APFloat FValue(0.0);
4354       return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4355                                   PromotedLHSType, FValue) &&
4356              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4357              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4358                                   Value);
4359     }
4360 
4361     Info.FFDiag(E);
4362     return false;
4363   }
4364   bool found(APFloat &Value, QualType SubobjType) {
4365     return checkConst(SubobjType) &&
4366            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4367                                   Value) &&
4368            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4369            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4370   }
4371   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4372     if (!checkConst(SubobjType))
4373       return false;
4374 
4375     QualType PointeeType;
4376     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4377       PointeeType = PT->getPointeeType();
4378 
4379     if (PointeeType.isNull() || !RHS.isInt() ||
4380         (Opcode != BO_Add && Opcode != BO_Sub)) {
4381       Info.FFDiag(E);
4382       return false;
4383     }
4384 
4385     APSInt Offset = RHS.getInt();
4386     if (Opcode == BO_Sub)
4387       negateAsSigned(Offset);
4388 
4389     LValue LVal;
4390     LVal.setFrom(Info.Ctx, Subobj);
4391     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4392       return false;
4393     LVal.moveInto(Subobj);
4394     return true;
4395   }
4396 };
4397 } // end anonymous namespace
4398 
4399 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4400 
4401 /// Perform a compound assignment of LVal <op>= RVal.
4402 static bool handleCompoundAssignment(EvalInfo &Info,
4403                                      const CompoundAssignOperator *E,
4404                                      const LValue &LVal, QualType LValType,
4405                                      QualType PromotedLValType,
4406                                      BinaryOperatorKind Opcode,
4407                                      const APValue &RVal) {
4408   if (LVal.Designator.Invalid)
4409     return false;
4410 
4411   if (!Info.getLangOpts().CPlusPlus14) {
4412     Info.FFDiag(E);
4413     return false;
4414   }
4415 
4416   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4417   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4418                                              RVal };
4419   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4420 }
4421 
4422 namespace {
4423 struct IncDecSubobjectHandler {
4424   EvalInfo &Info;
4425   const UnaryOperator *E;
4426   AccessKinds AccessKind;
4427   APValue *Old;
4428 
4429   typedef bool result_type;
4430 
4431   bool checkConst(QualType QT) {
4432     // Assigning to a const object has undefined behavior.
4433     if (QT.isConstQualified()) {
4434       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4435       return false;
4436     }
4437     return true;
4438   }
4439 
4440   bool failed() { return false; }
4441   bool found(APValue &Subobj, QualType SubobjType) {
4442     // Stash the old value. Also clear Old, so we don't clobber it later
4443     // if we're post-incrementing a complex.
4444     if (Old) {
4445       *Old = Subobj;
4446       Old = nullptr;
4447     }
4448 
4449     switch (Subobj.getKind()) {
4450     case APValue::Int:
4451       return found(Subobj.getInt(), SubobjType);
4452     case APValue::Float:
4453       return found(Subobj.getFloat(), SubobjType);
4454     case APValue::ComplexInt:
4455       return found(Subobj.getComplexIntReal(),
4456                    SubobjType->castAs<ComplexType>()->getElementType()
4457                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4458     case APValue::ComplexFloat:
4459       return found(Subobj.getComplexFloatReal(),
4460                    SubobjType->castAs<ComplexType>()->getElementType()
4461                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4462     case APValue::LValue:
4463       return foundPointer(Subobj, SubobjType);
4464     default:
4465       // FIXME: can this happen?
4466       Info.FFDiag(E);
4467       return false;
4468     }
4469   }
4470   bool found(APSInt &Value, QualType SubobjType) {
4471     if (!checkConst(SubobjType))
4472       return false;
4473 
4474     if (!SubobjType->isIntegerType()) {
4475       // We don't support increment / decrement on integer-cast-to-pointer
4476       // values.
4477       Info.FFDiag(E);
4478       return false;
4479     }
4480 
4481     if (Old) *Old = APValue(Value);
4482 
4483     // bool arithmetic promotes to int, and the conversion back to bool
4484     // doesn't reduce mod 2^n, so special-case it.
4485     if (SubobjType->isBooleanType()) {
4486       if (AccessKind == AK_Increment)
4487         Value = 1;
4488       else
4489         Value = !Value;
4490       return true;
4491     }
4492 
4493     bool WasNegative = Value.isNegative();
4494     if (AccessKind == AK_Increment) {
4495       ++Value;
4496 
4497       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4498         APSInt ActualValue(Value, /*IsUnsigned*/true);
4499         return HandleOverflow(Info, E, ActualValue, SubobjType);
4500       }
4501     } else {
4502       --Value;
4503 
4504       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4505         unsigned BitWidth = Value.getBitWidth();
4506         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4507         ActualValue.setBit(BitWidth);
4508         return HandleOverflow(Info, E, ActualValue, SubobjType);
4509       }
4510     }
4511     return true;
4512   }
4513   bool found(APFloat &Value, QualType SubobjType) {
4514     if (!checkConst(SubobjType))
4515       return false;
4516 
4517     if (Old) *Old = APValue(Value);
4518 
4519     APFloat One(Value.getSemantics(), 1);
4520     if (AccessKind == AK_Increment)
4521       Value.add(One, APFloat::rmNearestTiesToEven);
4522     else
4523       Value.subtract(One, APFloat::rmNearestTiesToEven);
4524     return true;
4525   }
4526   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4527     if (!checkConst(SubobjType))
4528       return false;
4529 
4530     QualType PointeeType;
4531     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4532       PointeeType = PT->getPointeeType();
4533     else {
4534       Info.FFDiag(E);
4535       return false;
4536     }
4537 
4538     LValue LVal;
4539     LVal.setFrom(Info.Ctx, Subobj);
4540     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4541                                      AccessKind == AK_Increment ? 1 : -1))
4542       return false;
4543     LVal.moveInto(Subobj);
4544     return true;
4545   }
4546 };
4547 } // end anonymous namespace
4548 
4549 /// Perform an increment or decrement on LVal.
4550 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4551                          QualType LValType, bool IsIncrement, APValue *Old) {
4552   if (LVal.Designator.Invalid)
4553     return false;
4554 
4555   if (!Info.getLangOpts().CPlusPlus14) {
4556     Info.FFDiag(E);
4557     return false;
4558   }
4559 
4560   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4561   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4562   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4563   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4564 }
4565 
4566 /// Build an lvalue for the object argument of a member function call.
4567 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4568                                    LValue &This) {
4569   if (Object->getType()->isPointerType() && Object->isRValue())
4570     return EvaluatePointer(Object, This, Info);
4571 
4572   if (Object->isGLValue())
4573     return EvaluateLValue(Object, This, Info);
4574 
4575   if (Object->getType()->isLiteralType(Info.Ctx))
4576     return EvaluateTemporary(Object, This, Info);
4577 
4578   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4579   return false;
4580 }
4581 
4582 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4583 /// lvalue referring to the result.
4584 ///
4585 /// \param Info - Information about the ongoing evaluation.
4586 /// \param LV - An lvalue referring to the base of the member pointer.
4587 /// \param RHS - The member pointer expression.
4588 /// \param IncludeMember - Specifies whether the member itself is included in
4589 ///        the resulting LValue subobject designator. This is not possible when
4590 ///        creating a bound member function.
4591 /// \return The field or method declaration to which the member pointer refers,
4592 ///         or 0 if evaluation fails.
4593 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4594                                                   QualType LVType,
4595                                                   LValue &LV,
4596                                                   const Expr *RHS,
4597                                                   bool IncludeMember = true) {
4598   MemberPtr MemPtr;
4599   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4600     return nullptr;
4601 
4602   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4603   // member value, the behavior is undefined.
4604   if (!MemPtr.getDecl()) {
4605     // FIXME: Specific diagnostic.
4606     Info.FFDiag(RHS);
4607     return nullptr;
4608   }
4609 
4610   if (MemPtr.isDerivedMember()) {
4611     // This is a member of some derived class. Truncate LV appropriately.
4612     // The end of the derived-to-base path for the base object must match the
4613     // derived-to-base path for the member pointer.
4614     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4615         LV.Designator.Entries.size()) {
4616       Info.FFDiag(RHS);
4617       return nullptr;
4618     }
4619     unsigned PathLengthToMember =
4620         LV.Designator.Entries.size() - MemPtr.Path.size();
4621     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4622       const CXXRecordDecl *LVDecl = getAsBaseClass(
4623           LV.Designator.Entries[PathLengthToMember + I]);
4624       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4625       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4626         Info.FFDiag(RHS);
4627         return nullptr;
4628       }
4629     }
4630 
4631     // Truncate the lvalue to the appropriate derived class.
4632     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4633                             PathLengthToMember))
4634       return nullptr;
4635   } else if (!MemPtr.Path.empty()) {
4636     // Extend the LValue path with the member pointer's path.
4637     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4638                                   MemPtr.Path.size() + IncludeMember);
4639 
4640     // Walk down to the appropriate base class.
4641     if (const PointerType *PT = LVType->getAs<PointerType>())
4642       LVType = PT->getPointeeType();
4643     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4644     assert(RD && "member pointer access on non-class-type expression");
4645     // The first class in the path is that of the lvalue.
4646     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4647       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4648       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4649         return nullptr;
4650       RD = Base;
4651     }
4652     // Finally cast to the class containing the member.
4653     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4654                                 MemPtr.getContainingRecord()))
4655       return nullptr;
4656   }
4657 
4658   // Add the member. Note that we cannot build bound member functions here.
4659   if (IncludeMember) {
4660     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4661       if (!HandleLValueMember(Info, RHS, LV, FD))
4662         return nullptr;
4663     } else if (const IndirectFieldDecl *IFD =
4664                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4665       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4666         return nullptr;
4667     } else {
4668       llvm_unreachable("can't construct reference to bound member function");
4669     }
4670   }
4671 
4672   return MemPtr.getDecl();
4673 }
4674 
4675 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4676                                                   const BinaryOperator *BO,
4677                                                   LValue &LV,
4678                                                   bool IncludeMember = true) {
4679   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4680 
4681   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4682     if (Info.noteFailure()) {
4683       MemberPtr MemPtr;
4684       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4685     }
4686     return nullptr;
4687   }
4688 
4689   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4690                                    BO->getRHS(), IncludeMember);
4691 }
4692 
4693 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4694 /// the provided lvalue, which currently refers to the base object.
4695 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4696                                     LValue &Result) {
4697   SubobjectDesignator &D = Result.Designator;
4698   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4699     return false;
4700 
4701   QualType TargetQT = E->getType();
4702   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4703     TargetQT = PT->getPointeeType();
4704 
4705   // Check this cast lands within the final derived-to-base subobject path.
4706   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4707     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4708       << D.MostDerivedType << TargetQT;
4709     return false;
4710   }
4711 
4712   // Check the type of the final cast. We don't need to check the path,
4713   // since a cast can only be formed if the path is unique.
4714   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4715   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4716   const CXXRecordDecl *FinalType;
4717   if (NewEntriesSize == D.MostDerivedPathLength)
4718     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4719   else
4720     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4721   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4722     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4723       << D.MostDerivedType << TargetQT;
4724     return false;
4725   }
4726 
4727   // Truncate the lvalue to the appropriate derived class.
4728   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4729 }
4730 
4731 /// Get the value to use for a default-initialized object of type T.
4732 /// Return false if it encounters something invalid.
4733 static bool getDefaultInitValue(QualType T, APValue &Result) {
4734   bool Success = true;
4735   if (auto *RD = T->getAsCXXRecordDecl()) {
4736     if (RD->isInvalidDecl()) {
4737       Result = APValue();
4738       return false;
4739     }
4740     if (RD->isUnion()) {
4741       Result = APValue((const FieldDecl *)nullptr);
4742       return true;
4743     }
4744     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4745                      std::distance(RD->field_begin(), RD->field_end()));
4746 
4747     unsigned Index = 0;
4748     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4749                                                   End = RD->bases_end();
4750          I != End; ++I, ++Index)
4751       Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4752 
4753     for (const auto *I : RD->fields()) {
4754       if (I->isUnnamedBitfield())
4755         continue;
4756       Success &= getDefaultInitValue(I->getType(),
4757                                      Result.getStructField(I->getFieldIndex()));
4758     }
4759     return Success;
4760   }
4761 
4762   if (auto *AT =
4763           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4764     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4765     if (Result.hasArrayFiller())
4766       Success &=
4767           getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4768 
4769     return Success;
4770   }
4771 
4772   Result = APValue::IndeterminateValue();
4773   return true;
4774 }
4775 
4776 namespace {
4777 enum EvalStmtResult {
4778   /// Evaluation failed.
4779   ESR_Failed,
4780   /// Hit a 'return' statement.
4781   ESR_Returned,
4782   /// Evaluation succeeded.
4783   ESR_Succeeded,
4784   /// Hit a 'continue' statement.
4785   ESR_Continue,
4786   /// Hit a 'break' statement.
4787   ESR_Break,
4788   /// Still scanning for 'case' or 'default' statement.
4789   ESR_CaseNotFound
4790 };
4791 }
4792 
4793 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4794   // We don't need to evaluate the initializer for a static local.
4795   if (!VD->hasLocalStorage())
4796     return true;
4797 
4798   LValue Result;
4799   APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4800                                                    ScopeKind::Block, Result);
4801 
4802   const Expr *InitE = VD->getInit();
4803   if (!InitE) {
4804     if (VD->getType()->isDependentType())
4805       return Info.noteSideEffect();
4806     return getDefaultInitValue(VD->getType(), Val);
4807   }
4808   if (InitE->isValueDependent())
4809     return false;
4810 
4811   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4812     // Wipe out any partially-computed value, to allow tracking that this
4813     // evaluation failed.
4814     Val = APValue();
4815     return false;
4816   }
4817 
4818   return true;
4819 }
4820 
4821 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4822   bool OK = true;
4823 
4824   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4825     OK &= EvaluateVarDecl(Info, VD);
4826 
4827   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4828     for (auto *BD : DD->bindings())
4829       if (auto *VD = BD->getHoldingVar())
4830         OK &= EvaluateDecl(Info, VD);
4831 
4832   return OK;
4833 }
4834 
4835 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4836   assert(E->isValueDependent());
4837   if (Info.noteSideEffect())
4838     return true;
4839   assert(E->containsErrors() && "valid value-dependent expression should never "
4840                                 "reach invalid code path.");
4841   return false;
4842 }
4843 
4844 /// Evaluate a condition (either a variable declaration or an expression).
4845 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4846                          const Expr *Cond, bool &Result) {
4847   if (Cond->isValueDependent())
4848     return false;
4849   FullExpressionRAII Scope(Info);
4850   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4851     return false;
4852   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4853     return false;
4854   return Scope.destroy();
4855 }
4856 
4857 namespace {
4858 /// A location where the result (returned value) of evaluating a
4859 /// statement should be stored.
4860 struct StmtResult {
4861   /// The APValue that should be filled in with the returned value.
4862   APValue &Value;
4863   /// The location containing the result, if any (used to support RVO).
4864   const LValue *Slot;
4865 };
4866 
4867 struct TempVersionRAII {
4868   CallStackFrame &Frame;
4869 
4870   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4871     Frame.pushTempVersion();
4872   }
4873 
4874   ~TempVersionRAII() {
4875     Frame.popTempVersion();
4876   }
4877 };
4878 
4879 }
4880 
4881 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4882                                    const Stmt *S,
4883                                    const SwitchCase *SC = nullptr);
4884 
4885 /// Evaluate the body of a loop, and translate the result as appropriate.
4886 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4887                                        const Stmt *Body,
4888                                        const SwitchCase *Case = nullptr) {
4889   BlockScopeRAII Scope(Info);
4890 
4891   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4892   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4893     ESR = ESR_Failed;
4894 
4895   switch (ESR) {
4896   case ESR_Break:
4897     return ESR_Succeeded;
4898   case ESR_Succeeded:
4899   case ESR_Continue:
4900     return ESR_Continue;
4901   case ESR_Failed:
4902   case ESR_Returned:
4903   case ESR_CaseNotFound:
4904     return ESR;
4905   }
4906   llvm_unreachable("Invalid EvalStmtResult!");
4907 }
4908 
4909 /// Evaluate a switch statement.
4910 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4911                                      const SwitchStmt *SS) {
4912   BlockScopeRAII Scope(Info);
4913 
4914   // Evaluate the switch condition.
4915   APSInt Value;
4916   {
4917     if (const Stmt *Init = SS->getInit()) {
4918       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4919       if (ESR != ESR_Succeeded) {
4920         if (ESR != ESR_Failed && !Scope.destroy())
4921           ESR = ESR_Failed;
4922         return ESR;
4923       }
4924     }
4925 
4926     FullExpressionRAII CondScope(Info);
4927     if (SS->getConditionVariable() &&
4928         !EvaluateDecl(Info, SS->getConditionVariable()))
4929       return ESR_Failed;
4930     if (!EvaluateInteger(SS->getCond(), Value, Info))
4931       return ESR_Failed;
4932     if (!CondScope.destroy())
4933       return ESR_Failed;
4934   }
4935 
4936   // Find the switch case corresponding to the value of the condition.
4937   // FIXME: Cache this lookup.
4938   const SwitchCase *Found = nullptr;
4939   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4940        SC = SC->getNextSwitchCase()) {
4941     if (isa<DefaultStmt>(SC)) {
4942       Found = SC;
4943       continue;
4944     }
4945 
4946     const CaseStmt *CS = cast<CaseStmt>(SC);
4947     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4948     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4949                               : LHS;
4950     if (LHS <= Value && Value <= RHS) {
4951       Found = SC;
4952       break;
4953     }
4954   }
4955 
4956   if (!Found)
4957     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4958 
4959   // Search the switch body for the switch case and evaluate it from there.
4960   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4961   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4962     return ESR_Failed;
4963 
4964   switch (ESR) {
4965   case ESR_Break:
4966     return ESR_Succeeded;
4967   case ESR_Succeeded:
4968   case ESR_Continue:
4969   case ESR_Failed:
4970   case ESR_Returned:
4971     return ESR;
4972   case ESR_CaseNotFound:
4973     // This can only happen if the switch case is nested within a statement
4974     // expression. We have no intention of supporting that.
4975     Info.FFDiag(Found->getBeginLoc(),
4976                 diag::note_constexpr_stmt_expr_unsupported);
4977     return ESR_Failed;
4978   }
4979   llvm_unreachable("Invalid EvalStmtResult!");
4980 }
4981 
4982 // Evaluate a statement.
4983 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4984                                    const Stmt *S, const SwitchCase *Case) {
4985   if (!Info.nextStep(S))
4986     return ESR_Failed;
4987 
4988   // If we're hunting down a 'case' or 'default' label, recurse through
4989   // substatements until we hit the label.
4990   if (Case) {
4991     switch (S->getStmtClass()) {
4992     case Stmt::CompoundStmtClass:
4993       // FIXME: Precompute which substatement of a compound statement we
4994       // would jump to, and go straight there rather than performing a
4995       // linear scan each time.
4996     case Stmt::LabelStmtClass:
4997     case Stmt::AttributedStmtClass:
4998     case Stmt::DoStmtClass:
4999       break;
5000 
5001     case Stmt::CaseStmtClass:
5002     case Stmt::DefaultStmtClass:
5003       if (Case == S)
5004         Case = nullptr;
5005       break;
5006 
5007     case Stmt::IfStmtClass: {
5008       // FIXME: Precompute which side of an 'if' we would jump to, and go
5009       // straight there rather than scanning both sides.
5010       const IfStmt *IS = cast<IfStmt>(S);
5011 
5012       // Wrap the evaluation in a block scope, in case it's a DeclStmt
5013       // preceded by our switch label.
5014       BlockScopeRAII Scope(Info);
5015 
5016       // Step into the init statement in case it brings an (uninitialized)
5017       // variable into scope.
5018       if (const Stmt *Init = IS->getInit()) {
5019         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5020         if (ESR != ESR_CaseNotFound) {
5021           assert(ESR != ESR_Succeeded);
5022           return ESR;
5023         }
5024       }
5025 
5026       // Condition variable must be initialized if it exists.
5027       // FIXME: We can skip evaluating the body if there's a condition
5028       // variable, as there can't be any case labels within it.
5029       // (The same is true for 'for' statements.)
5030 
5031       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5032       if (ESR == ESR_Failed)
5033         return ESR;
5034       if (ESR != ESR_CaseNotFound)
5035         return Scope.destroy() ? ESR : ESR_Failed;
5036       if (!IS->getElse())
5037         return ESR_CaseNotFound;
5038 
5039       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5040       if (ESR == ESR_Failed)
5041         return ESR;
5042       if (ESR != ESR_CaseNotFound)
5043         return Scope.destroy() ? ESR : ESR_Failed;
5044       return ESR_CaseNotFound;
5045     }
5046 
5047     case Stmt::WhileStmtClass: {
5048       EvalStmtResult ESR =
5049           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5050       if (ESR != ESR_Continue)
5051         return ESR;
5052       break;
5053     }
5054 
5055     case Stmt::ForStmtClass: {
5056       const ForStmt *FS = cast<ForStmt>(S);
5057       BlockScopeRAII Scope(Info);
5058 
5059       // Step into the init statement in case it brings an (uninitialized)
5060       // variable into scope.
5061       if (const Stmt *Init = FS->getInit()) {
5062         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5063         if (ESR != ESR_CaseNotFound) {
5064           assert(ESR != ESR_Succeeded);
5065           return ESR;
5066         }
5067       }
5068 
5069       EvalStmtResult ESR =
5070           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5071       if (ESR != ESR_Continue)
5072         return ESR;
5073       if (const auto *Inc = FS->getInc()) {
5074         if (Inc->isValueDependent()) {
5075           if (!EvaluateDependentExpr(Inc, Info))
5076             return ESR_Failed;
5077         } else {
5078           FullExpressionRAII IncScope(Info);
5079           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5080             return ESR_Failed;
5081         }
5082       }
5083       break;
5084     }
5085 
5086     case Stmt::DeclStmtClass: {
5087       // Start the lifetime of any uninitialized variables we encounter. They
5088       // might be used by the selected branch of the switch.
5089       const DeclStmt *DS = cast<DeclStmt>(S);
5090       for (const auto *D : DS->decls()) {
5091         if (const auto *VD = dyn_cast<VarDecl>(D)) {
5092           if (VD->hasLocalStorage() && !VD->getInit())
5093             if (!EvaluateVarDecl(Info, VD))
5094               return ESR_Failed;
5095           // FIXME: If the variable has initialization that can't be jumped
5096           // over, bail out of any immediately-surrounding compound-statement
5097           // too. There can't be any case labels here.
5098         }
5099       }
5100       return ESR_CaseNotFound;
5101     }
5102 
5103     default:
5104       return ESR_CaseNotFound;
5105     }
5106   }
5107 
5108   switch (S->getStmtClass()) {
5109   default:
5110     if (const Expr *E = dyn_cast<Expr>(S)) {
5111       if (E->isValueDependent()) {
5112         if (!EvaluateDependentExpr(E, Info))
5113           return ESR_Failed;
5114       } else {
5115         // Don't bother evaluating beyond an expression-statement which couldn't
5116         // be evaluated.
5117         // FIXME: Do we need the FullExpressionRAII object here?
5118         // VisitExprWithCleanups should create one when necessary.
5119         FullExpressionRAII Scope(Info);
5120         if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5121           return ESR_Failed;
5122       }
5123       return ESR_Succeeded;
5124     }
5125 
5126     Info.FFDiag(S->getBeginLoc());
5127     return ESR_Failed;
5128 
5129   case Stmt::NullStmtClass:
5130     return ESR_Succeeded;
5131 
5132   case Stmt::DeclStmtClass: {
5133     const DeclStmt *DS = cast<DeclStmt>(S);
5134     for (const auto *D : DS->decls()) {
5135       // Each declaration initialization is its own full-expression.
5136       FullExpressionRAII Scope(Info);
5137       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5138         return ESR_Failed;
5139       if (!Scope.destroy())
5140         return ESR_Failed;
5141     }
5142     return ESR_Succeeded;
5143   }
5144 
5145   case Stmt::ReturnStmtClass: {
5146     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5147     FullExpressionRAII Scope(Info);
5148     if (RetExpr && RetExpr->isValueDependent()) {
5149       EvaluateDependentExpr(RetExpr, Info);
5150       // We know we returned, but we don't know what the value is.
5151       return ESR_Failed;
5152     }
5153     if (RetExpr &&
5154         !(Result.Slot
5155               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5156               : Evaluate(Result.Value, Info, RetExpr)))
5157       return ESR_Failed;
5158     return Scope.destroy() ? ESR_Returned : ESR_Failed;
5159   }
5160 
5161   case Stmt::CompoundStmtClass: {
5162     BlockScopeRAII Scope(Info);
5163 
5164     const CompoundStmt *CS = cast<CompoundStmt>(S);
5165     for (const auto *BI : CS->body()) {
5166       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5167       if (ESR == ESR_Succeeded)
5168         Case = nullptr;
5169       else if (ESR != ESR_CaseNotFound) {
5170         if (ESR != ESR_Failed && !Scope.destroy())
5171           return ESR_Failed;
5172         return ESR;
5173       }
5174     }
5175     if (Case)
5176       return ESR_CaseNotFound;
5177     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5178   }
5179 
5180   case Stmt::IfStmtClass: {
5181     const IfStmt *IS = cast<IfStmt>(S);
5182 
5183     // Evaluate the condition, as either a var decl or as an expression.
5184     BlockScopeRAII Scope(Info);
5185     if (const Stmt *Init = IS->getInit()) {
5186       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5187       if (ESR != ESR_Succeeded) {
5188         if (ESR != ESR_Failed && !Scope.destroy())
5189           return ESR_Failed;
5190         return ESR;
5191       }
5192     }
5193     bool Cond;
5194     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
5195       return ESR_Failed;
5196 
5197     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5198       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5199       if (ESR != ESR_Succeeded) {
5200         if (ESR != ESR_Failed && !Scope.destroy())
5201           return ESR_Failed;
5202         return ESR;
5203       }
5204     }
5205     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5206   }
5207 
5208   case Stmt::WhileStmtClass: {
5209     const WhileStmt *WS = cast<WhileStmt>(S);
5210     while (true) {
5211       BlockScopeRAII Scope(Info);
5212       bool Continue;
5213       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5214                         Continue))
5215         return ESR_Failed;
5216       if (!Continue)
5217         break;
5218 
5219       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5220       if (ESR != ESR_Continue) {
5221         if (ESR != ESR_Failed && !Scope.destroy())
5222           return ESR_Failed;
5223         return ESR;
5224       }
5225       if (!Scope.destroy())
5226         return ESR_Failed;
5227     }
5228     return ESR_Succeeded;
5229   }
5230 
5231   case Stmt::DoStmtClass: {
5232     const DoStmt *DS = cast<DoStmt>(S);
5233     bool Continue;
5234     do {
5235       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5236       if (ESR != ESR_Continue)
5237         return ESR;
5238       Case = nullptr;
5239 
5240       if (DS->getCond()->isValueDependent()) {
5241         EvaluateDependentExpr(DS->getCond(), Info);
5242         // Bailout as we don't know whether to keep going or terminate the loop.
5243         return ESR_Failed;
5244       }
5245       FullExpressionRAII CondScope(Info);
5246       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5247           !CondScope.destroy())
5248         return ESR_Failed;
5249     } while (Continue);
5250     return ESR_Succeeded;
5251   }
5252 
5253   case Stmt::ForStmtClass: {
5254     const ForStmt *FS = cast<ForStmt>(S);
5255     BlockScopeRAII ForScope(Info);
5256     if (FS->getInit()) {
5257       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5258       if (ESR != ESR_Succeeded) {
5259         if (ESR != ESR_Failed && !ForScope.destroy())
5260           return ESR_Failed;
5261         return ESR;
5262       }
5263     }
5264     while (true) {
5265       BlockScopeRAII IterScope(Info);
5266       bool Continue = true;
5267       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5268                                          FS->getCond(), Continue))
5269         return ESR_Failed;
5270       if (!Continue)
5271         break;
5272 
5273       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5274       if (ESR != ESR_Continue) {
5275         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5276           return ESR_Failed;
5277         return ESR;
5278       }
5279 
5280       if (const auto *Inc = FS->getInc()) {
5281         if (Inc->isValueDependent()) {
5282           if (!EvaluateDependentExpr(Inc, Info))
5283             return ESR_Failed;
5284         } else {
5285           FullExpressionRAII IncScope(Info);
5286           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5287             return ESR_Failed;
5288         }
5289       }
5290 
5291       if (!IterScope.destroy())
5292         return ESR_Failed;
5293     }
5294     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5295   }
5296 
5297   case Stmt::CXXForRangeStmtClass: {
5298     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5299     BlockScopeRAII Scope(Info);
5300 
5301     // Evaluate the init-statement if present.
5302     if (FS->getInit()) {
5303       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5304       if (ESR != ESR_Succeeded) {
5305         if (ESR != ESR_Failed && !Scope.destroy())
5306           return ESR_Failed;
5307         return ESR;
5308       }
5309     }
5310 
5311     // Initialize the __range variable.
5312     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5313     if (ESR != ESR_Succeeded) {
5314       if (ESR != ESR_Failed && !Scope.destroy())
5315         return ESR_Failed;
5316       return ESR;
5317     }
5318 
5319     // Create the __begin and __end iterators.
5320     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5321     if (ESR != ESR_Succeeded) {
5322       if (ESR != ESR_Failed && !Scope.destroy())
5323         return ESR_Failed;
5324       return ESR;
5325     }
5326     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5327     if (ESR != ESR_Succeeded) {
5328       if (ESR != ESR_Failed && !Scope.destroy())
5329         return ESR_Failed;
5330       return ESR;
5331     }
5332 
5333     while (true) {
5334       // Condition: __begin != __end.
5335       {
5336         if (FS->getCond()->isValueDependent()) {
5337           EvaluateDependentExpr(FS->getCond(), Info);
5338           // We don't know whether to keep going or terminate the loop.
5339           return ESR_Failed;
5340         }
5341         bool Continue = true;
5342         FullExpressionRAII CondExpr(Info);
5343         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5344           return ESR_Failed;
5345         if (!Continue)
5346           break;
5347       }
5348 
5349       // User's variable declaration, initialized by *__begin.
5350       BlockScopeRAII InnerScope(Info);
5351       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5352       if (ESR != ESR_Succeeded) {
5353         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5354           return ESR_Failed;
5355         return ESR;
5356       }
5357 
5358       // Loop body.
5359       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5360       if (ESR != ESR_Continue) {
5361         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5362           return ESR_Failed;
5363         return ESR;
5364       }
5365       if (FS->getInc()->isValueDependent()) {
5366         if (!EvaluateDependentExpr(FS->getInc(), Info))
5367           return ESR_Failed;
5368       } else {
5369         // Increment: ++__begin
5370         if (!EvaluateIgnoredValue(Info, FS->getInc()))
5371           return ESR_Failed;
5372       }
5373 
5374       if (!InnerScope.destroy())
5375         return ESR_Failed;
5376     }
5377 
5378     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5379   }
5380 
5381   case Stmt::SwitchStmtClass:
5382     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5383 
5384   case Stmt::ContinueStmtClass:
5385     return ESR_Continue;
5386 
5387   case Stmt::BreakStmtClass:
5388     return ESR_Break;
5389 
5390   case Stmt::LabelStmtClass:
5391     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5392 
5393   case Stmt::AttributedStmtClass:
5394     // As a general principle, C++11 attributes can be ignored without
5395     // any semantic impact.
5396     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5397                         Case);
5398 
5399   case Stmt::CaseStmtClass:
5400   case Stmt::DefaultStmtClass:
5401     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5402   case Stmt::CXXTryStmtClass:
5403     // Evaluate try blocks by evaluating all sub statements.
5404     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5405   }
5406 }
5407 
5408 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5409 /// default constructor. If so, we'll fold it whether or not it's marked as
5410 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5411 /// so we need special handling.
5412 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5413                                            const CXXConstructorDecl *CD,
5414                                            bool IsValueInitialization) {
5415   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5416     return false;
5417 
5418   // Value-initialization does not call a trivial default constructor, so such a
5419   // call is a core constant expression whether or not the constructor is
5420   // constexpr.
5421   if (!CD->isConstexpr() && !IsValueInitialization) {
5422     if (Info.getLangOpts().CPlusPlus11) {
5423       // FIXME: If DiagDecl is an implicitly-declared special member function,
5424       // we should be much more explicit about why it's not constexpr.
5425       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5426         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5427       Info.Note(CD->getLocation(), diag::note_declared_at);
5428     } else {
5429       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5430     }
5431   }
5432   return true;
5433 }
5434 
5435 /// CheckConstexprFunction - Check that a function can be called in a constant
5436 /// expression.
5437 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5438                                    const FunctionDecl *Declaration,
5439                                    const FunctionDecl *Definition,
5440                                    const Stmt *Body) {
5441   // Potential constant expressions can contain calls to declared, but not yet
5442   // defined, constexpr functions.
5443   if (Info.checkingPotentialConstantExpression() && !Definition &&
5444       Declaration->isConstexpr())
5445     return false;
5446 
5447   // Bail out if the function declaration itself is invalid.  We will
5448   // have produced a relevant diagnostic while parsing it, so just
5449   // note the problematic sub-expression.
5450   if (Declaration->isInvalidDecl()) {
5451     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5452     return false;
5453   }
5454 
5455   // DR1872: An instantiated virtual constexpr function can't be called in a
5456   // constant expression (prior to C++20). We can still constant-fold such a
5457   // call.
5458   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5459       cast<CXXMethodDecl>(Declaration)->isVirtual())
5460     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5461 
5462   if (Definition && Definition->isInvalidDecl()) {
5463     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5464     return false;
5465   }
5466 
5467   // Can we evaluate this function call?
5468   if (Definition && Definition->isConstexpr() && Body)
5469     return true;
5470 
5471   if (Info.getLangOpts().CPlusPlus11) {
5472     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5473 
5474     // If this function is not constexpr because it is an inherited
5475     // non-constexpr constructor, diagnose that directly.
5476     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5477     if (CD && CD->isInheritingConstructor()) {
5478       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5479       if (!Inherited->isConstexpr())
5480         DiagDecl = CD = Inherited;
5481     }
5482 
5483     // FIXME: If DiagDecl is an implicitly-declared special member function
5484     // or an inheriting constructor, we should be much more explicit about why
5485     // it's not constexpr.
5486     if (CD && CD->isInheritingConstructor())
5487       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5488         << CD->getInheritedConstructor().getConstructor()->getParent();
5489     else
5490       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5491         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5492     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5493   } else {
5494     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5495   }
5496   return false;
5497 }
5498 
5499 namespace {
5500 struct CheckDynamicTypeHandler {
5501   AccessKinds AccessKind;
5502   typedef bool result_type;
5503   bool failed() { return false; }
5504   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5505   bool found(APSInt &Value, QualType SubobjType) { return true; }
5506   bool found(APFloat &Value, QualType SubobjType) { return true; }
5507 };
5508 } // end anonymous namespace
5509 
5510 /// Check that we can access the notional vptr of an object / determine its
5511 /// dynamic type.
5512 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5513                              AccessKinds AK, bool Polymorphic) {
5514   if (This.Designator.Invalid)
5515     return false;
5516 
5517   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5518 
5519   if (!Obj)
5520     return false;
5521 
5522   if (!Obj.Value) {
5523     // The object is not usable in constant expressions, so we can't inspect
5524     // its value to see if it's in-lifetime or what the active union members
5525     // are. We can still check for a one-past-the-end lvalue.
5526     if (This.Designator.isOnePastTheEnd() ||
5527         This.Designator.isMostDerivedAnUnsizedArray()) {
5528       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5529                          ? diag::note_constexpr_access_past_end
5530                          : diag::note_constexpr_access_unsized_array)
5531           << AK;
5532       return false;
5533     } else if (Polymorphic) {
5534       // Conservatively refuse to perform a polymorphic operation if we would
5535       // not be able to read a notional 'vptr' value.
5536       APValue Val;
5537       This.moveInto(Val);
5538       QualType StarThisType =
5539           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5540       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5541           << AK << Val.getAsString(Info.Ctx, StarThisType);
5542       return false;
5543     }
5544     return true;
5545   }
5546 
5547   CheckDynamicTypeHandler Handler{AK};
5548   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5549 }
5550 
5551 /// Check that the pointee of the 'this' pointer in a member function call is
5552 /// either within its lifetime or in its period of construction or destruction.
5553 static bool
5554 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5555                                      const LValue &This,
5556                                      const CXXMethodDecl *NamedMember) {
5557   return checkDynamicType(
5558       Info, E, This,
5559       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5560 }
5561 
5562 struct DynamicType {
5563   /// The dynamic class type of the object.
5564   const CXXRecordDecl *Type;
5565   /// The corresponding path length in the lvalue.
5566   unsigned PathLength;
5567 };
5568 
5569 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5570                                              unsigned PathLength) {
5571   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5572       Designator.Entries.size() && "invalid path length");
5573   return (PathLength == Designator.MostDerivedPathLength)
5574              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5575              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5576 }
5577 
5578 /// Determine the dynamic type of an object.
5579 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5580                                                 LValue &This, AccessKinds AK) {
5581   // If we don't have an lvalue denoting an object of class type, there is no
5582   // meaningful dynamic type. (We consider objects of non-class type to have no
5583   // dynamic type.)
5584   if (!checkDynamicType(Info, E, This, AK, true))
5585     return None;
5586 
5587   // Refuse to compute a dynamic type in the presence of virtual bases. This
5588   // shouldn't happen other than in constant-folding situations, since literal
5589   // types can't have virtual bases.
5590   //
5591   // Note that consumers of DynamicType assume that the type has no virtual
5592   // bases, and will need modifications if this restriction is relaxed.
5593   const CXXRecordDecl *Class =
5594       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5595   if (!Class || Class->getNumVBases()) {
5596     Info.FFDiag(E);
5597     return None;
5598   }
5599 
5600   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5601   // binary search here instead. But the overwhelmingly common case is that
5602   // we're not in the middle of a constructor, so it probably doesn't matter
5603   // in practice.
5604   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5605   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5606        PathLength <= Path.size(); ++PathLength) {
5607     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5608                                       Path.slice(0, PathLength))) {
5609     case ConstructionPhase::Bases:
5610     case ConstructionPhase::DestroyingBases:
5611       // We're constructing or destroying a base class. This is not the dynamic
5612       // type.
5613       break;
5614 
5615     case ConstructionPhase::None:
5616     case ConstructionPhase::AfterBases:
5617     case ConstructionPhase::AfterFields:
5618     case ConstructionPhase::Destroying:
5619       // We've finished constructing the base classes and not yet started
5620       // destroying them again, so this is the dynamic type.
5621       return DynamicType{getBaseClassType(This.Designator, PathLength),
5622                          PathLength};
5623     }
5624   }
5625 
5626   // CWG issue 1517: we're constructing a base class of the object described by
5627   // 'This', so that object has not yet begun its period of construction and
5628   // any polymorphic operation on it results in undefined behavior.
5629   Info.FFDiag(E);
5630   return None;
5631 }
5632 
5633 /// Perform virtual dispatch.
5634 static const CXXMethodDecl *HandleVirtualDispatch(
5635     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5636     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5637   Optional<DynamicType> DynType = ComputeDynamicType(
5638       Info, E, This,
5639       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5640   if (!DynType)
5641     return nullptr;
5642 
5643   // Find the final overrider. It must be declared in one of the classes on the
5644   // path from the dynamic type to the static type.
5645   // FIXME: If we ever allow literal types to have virtual base classes, that
5646   // won't be true.
5647   const CXXMethodDecl *Callee = Found;
5648   unsigned PathLength = DynType->PathLength;
5649   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5650     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5651     const CXXMethodDecl *Overrider =
5652         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5653     if (Overrider) {
5654       Callee = Overrider;
5655       break;
5656     }
5657   }
5658 
5659   // C++2a [class.abstract]p6:
5660   //   the effect of making a virtual call to a pure virtual function [...] is
5661   //   undefined
5662   if (Callee->isPure()) {
5663     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5664     Info.Note(Callee->getLocation(), diag::note_declared_at);
5665     return nullptr;
5666   }
5667 
5668   // If necessary, walk the rest of the path to determine the sequence of
5669   // covariant adjustment steps to apply.
5670   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5671                                        Found->getReturnType())) {
5672     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5673     for (unsigned CovariantPathLength = PathLength + 1;
5674          CovariantPathLength != This.Designator.Entries.size();
5675          ++CovariantPathLength) {
5676       const CXXRecordDecl *NextClass =
5677           getBaseClassType(This.Designator, CovariantPathLength);
5678       const CXXMethodDecl *Next =
5679           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5680       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5681                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5682         CovariantAdjustmentPath.push_back(Next->getReturnType());
5683     }
5684     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5685                                          CovariantAdjustmentPath.back()))
5686       CovariantAdjustmentPath.push_back(Found->getReturnType());
5687   }
5688 
5689   // Perform 'this' adjustment.
5690   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5691     return nullptr;
5692 
5693   return Callee;
5694 }
5695 
5696 /// Perform the adjustment from a value returned by a virtual function to
5697 /// a value of the statically expected type, which may be a pointer or
5698 /// reference to a base class of the returned type.
5699 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5700                                             APValue &Result,
5701                                             ArrayRef<QualType> Path) {
5702   assert(Result.isLValue() &&
5703          "unexpected kind of APValue for covariant return");
5704   if (Result.isNullPointer())
5705     return true;
5706 
5707   LValue LVal;
5708   LVal.setFrom(Info.Ctx, Result);
5709 
5710   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5711   for (unsigned I = 1; I != Path.size(); ++I) {
5712     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5713     assert(OldClass && NewClass && "unexpected kind of covariant return");
5714     if (OldClass != NewClass &&
5715         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5716       return false;
5717     OldClass = NewClass;
5718   }
5719 
5720   LVal.moveInto(Result);
5721   return true;
5722 }
5723 
5724 /// Determine whether \p Base, which is known to be a direct base class of
5725 /// \p Derived, is a public base class.
5726 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5727                               const CXXRecordDecl *Base) {
5728   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5729     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5730     if (BaseClass && declaresSameEntity(BaseClass, Base))
5731       return BaseSpec.getAccessSpecifier() == AS_public;
5732   }
5733   llvm_unreachable("Base is not a direct base of Derived");
5734 }
5735 
5736 /// Apply the given dynamic cast operation on the provided lvalue.
5737 ///
5738 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5739 /// to find a suitable target subobject.
5740 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5741                               LValue &Ptr) {
5742   // We can't do anything with a non-symbolic pointer value.
5743   SubobjectDesignator &D = Ptr.Designator;
5744   if (D.Invalid)
5745     return false;
5746 
5747   // C++ [expr.dynamic.cast]p6:
5748   //   If v is a null pointer value, the result is a null pointer value.
5749   if (Ptr.isNullPointer() && !E->isGLValue())
5750     return true;
5751 
5752   // For all the other cases, we need the pointer to point to an object within
5753   // its lifetime / period of construction / destruction, and we need to know
5754   // its dynamic type.
5755   Optional<DynamicType> DynType =
5756       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5757   if (!DynType)
5758     return false;
5759 
5760   // C++ [expr.dynamic.cast]p7:
5761   //   If T is "pointer to cv void", then the result is a pointer to the most
5762   //   derived object
5763   if (E->getType()->isVoidPointerType())
5764     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5765 
5766   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5767   assert(C && "dynamic_cast target is not void pointer nor class");
5768   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5769 
5770   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5771     // C++ [expr.dynamic.cast]p9:
5772     if (!E->isGLValue()) {
5773       //   The value of a failed cast to pointer type is the null pointer value
5774       //   of the required result type.
5775       Ptr.setNull(Info.Ctx, E->getType());
5776       return true;
5777     }
5778 
5779     //   A failed cast to reference type throws [...] std::bad_cast.
5780     unsigned DiagKind;
5781     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5782                    DynType->Type->isDerivedFrom(C)))
5783       DiagKind = 0;
5784     else if (!Paths || Paths->begin() == Paths->end())
5785       DiagKind = 1;
5786     else if (Paths->isAmbiguous(CQT))
5787       DiagKind = 2;
5788     else {
5789       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5790       DiagKind = 3;
5791     }
5792     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5793         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5794         << Info.Ctx.getRecordType(DynType->Type)
5795         << E->getType().getUnqualifiedType();
5796     return false;
5797   };
5798 
5799   // Runtime check, phase 1:
5800   //   Walk from the base subobject towards the derived object looking for the
5801   //   target type.
5802   for (int PathLength = Ptr.Designator.Entries.size();
5803        PathLength >= (int)DynType->PathLength; --PathLength) {
5804     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5805     if (declaresSameEntity(Class, C))
5806       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5807     // We can only walk across public inheritance edges.
5808     if (PathLength > (int)DynType->PathLength &&
5809         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5810                            Class))
5811       return RuntimeCheckFailed(nullptr);
5812   }
5813 
5814   // Runtime check, phase 2:
5815   //   Search the dynamic type for an unambiguous public base of type C.
5816   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5817                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5818   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5819       Paths.front().Access == AS_public) {
5820     // Downcast to the dynamic type...
5821     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5822       return false;
5823     // ... then upcast to the chosen base class subobject.
5824     for (CXXBasePathElement &Elem : Paths.front())
5825       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5826         return false;
5827     return true;
5828   }
5829 
5830   // Otherwise, the runtime check fails.
5831   return RuntimeCheckFailed(&Paths);
5832 }
5833 
5834 namespace {
5835 struct StartLifetimeOfUnionMemberHandler {
5836   EvalInfo &Info;
5837   const Expr *LHSExpr;
5838   const FieldDecl *Field;
5839   bool DuringInit;
5840   bool Failed = false;
5841   static const AccessKinds AccessKind = AK_Assign;
5842 
5843   typedef bool result_type;
5844   bool failed() { return Failed; }
5845   bool found(APValue &Subobj, QualType SubobjType) {
5846     // We are supposed to perform no initialization but begin the lifetime of
5847     // the object. We interpret that as meaning to do what default
5848     // initialization of the object would do if all constructors involved were
5849     // trivial:
5850     //  * All base, non-variant member, and array element subobjects' lifetimes
5851     //    begin
5852     //  * No variant members' lifetimes begin
5853     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5854     assert(SubobjType->isUnionType());
5855     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5856       // This union member is already active. If it's also in-lifetime, there's
5857       // nothing to do.
5858       if (Subobj.getUnionValue().hasValue())
5859         return true;
5860     } else if (DuringInit) {
5861       // We're currently in the process of initializing a different union
5862       // member.  If we carried on, that initialization would attempt to
5863       // store to an inactive union member, resulting in undefined behavior.
5864       Info.FFDiag(LHSExpr,
5865                   diag::note_constexpr_union_member_change_during_init);
5866       return false;
5867     }
5868     APValue Result;
5869     Failed = !getDefaultInitValue(Field->getType(), Result);
5870     Subobj.setUnion(Field, Result);
5871     return true;
5872   }
5873   bool found(APSInt &Value, QualType SubobjType) {
5874     llvm_unreachable("wrong value kind for union object");
5875   }
5876   bool found(APFloat &Value, QualType SubobjType) {
5877     llvm_unreachable("wrong value kind for union object");
5878   }
5879 };
5880 } // end anonymous namespace
5881 
5882 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5883 
5884 /// Handle a builtin simple-assignment or a call to a trivial assignment
5885 /// operator whose left-hand side might involve a union member access. If it
5886 /// does, implicitly start the lifetime of any accessed union elements per
5887 /// C++20 [class.union]5.
5888 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5889                                           const LValue &LHS) {
5890   if (LHS.InvalidBase || LHS.Designator.Invalid)
5891     return false;
5892 
5893   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5894   // C++ [class.union]p5:
5895   //   define the set S(E) of subexpressions of E as follows:
5896   unsigned PathLength = LHS.Designator.Entries.size();
5897   for (const Expr *E = LHSExpr; E != nullptr;) {
5898     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5899     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5900       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5901       // Note that we can't implicitly start the lifetime of a reference,
5902       // so we don't need to proceed any further if we reach one.
5903       if (!FD || FD->getType()->isReferenceType())
5904         break;
5905 
5906       //    ... and also contains A.B if B names a union member ...
5907       if (FD->getParent()->isUnion()) {
5908         //    ... of a non-class, non-array type, or of a class type with a
5909         //    trivial default constructor that is not deleted, or an array of
5910         //    such types.
5911         auto *RD =
5912             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5913         if (!RD || RD->hasTrivialDefaultConstructor())
5914           UnionPathLengths.push_back({PathLength - 1, FD});
5915       }
5916 
5917       E = ME->getBase();
5918       --PathLength;
5919       assert(declaresSameEntity(FD,
5920                                 LHS.Designator.Entries[PathLength]
5921                                     .getAsBaseOrMember().getPointer()));
5922 
5923       //   -- If E is of the form A[B] and is interpreted as a built-in array
5924       //      subscripting operator, S(E) is [S(the array operand, if any)].
5925     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5926       // Step over an ArrayToPointerDecay implicit cast.
5927       auto *Base = ASE->getBase()->IgnoreImplicit();
5928       if (!Base->getType()->isArrayType())
5929         break;
5930 
5931       E = Base;
5932       --PathLength;
5933 
5934     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5935       // Step over a derived-to-base conversion.
5936       E = ICE->getSubExpr();
5937       if (ICE->getCastKind() == CK_NoOp)
5938         continue;
5939       if (ICE->getCastKind() != CK_DerivedToBase &&
5940           ICE->getCastKind() != CK_UncheckedDerivedToBase)
5941         break;
5942       // Walk path backwards as we walk up from the base to the derived class.
5943       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5944         --PathLength;
5945         (void)Elt;
5946         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5947                                   LHS.Designator.Entries[PathLength]
5948                                       .getAsBaseOrMember().getPointer()));
5949       }
5950 
5951     //   -- Otherwise, S(E) is empty.
5952     } else {
5953       break;
5954     }
5955   }
5956 
5957   // Common case: no unions' lifetimes are started.
5958   if (UnionPathLengths.empty())
5959     return true;
5960 
5961   //   if modification of X [would access an inactive union member], an object
5962   //   of the type of X is implicitly created
5963   CompleteObject Obj =
5964       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5965   if (!Obj)
5966     return false;
5967   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5968            llvm::reverse(UnionPathLengths)) {
5969     // Form a designator for the union object.
5970     SubobjectDesignator D = LHS.Designator;
5971     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5972 
5973     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
5974                       ConstructionPhase::AfterBases;
5975     StartLifetimeOfUnionMemberHandler StartLifetime{
5976         Info, LHSExpr, LengthAndField.second, DuringInit};
5977     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5978       return false;
5979   }
5980 
5981   return true;
5982 }
5983 
5984 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
5985                             CallRef Call, EvalInfo &Info,
5986                             bool NonNull = false) {
5987   LValue LV;
5988   // Create the parameter slot and register its destruction. For a vararg
5989   // argument, create a temporary.
5990   // FIXME: For calling conventions that destroy parameters in the callee,
5991   // should we consider performing destruction when the function returns
5992   // instead?
5993   APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
5994                    : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
5995                                                        ScopeKind::Call, LV);
5996   if (!EvaluateInPlace(V, Info, LV, Arg))
5997     return false;
5998 
5999   // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6000   // undefined behavior, so is non-constant.
6001   if (NonNull && V.isLValue() && V.isNullPointer()) {
6002     Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6003     return false;
6004   }
6005 
6006   return true;
6007 }
6008 
6009 /// Evaluate the arguments to a function call.
6010 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6011                          EvalInfo &Info, const FunctionDecl *Callee,
6012                          bool RightToLeft = false) {
6013   bool Success = true;
6014   llvm::SmallBitVector ForbiddenNullArgs;
6015   if (Callee->hasAttr<NonNullAttr>()) {
6016     ForbiddenNullArgs.resize(Args.size());
6017     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6018       if (!Attr->args_size()) {
6019         ForbiddenNullArgs.set();
6020         break;
6021       } else
6022         for (auto Idx : Attr->args()) {
6023           unsigned ASTIdx = Idx.getASTIndex();
6024           if (ASTIdx >= Args.size())
6025             continue;
6026           ForbiddenNullArgs[ASTIdx] = 1;
6027         }
6028     }
6029   }
6030   for (unsigned I = 0; I < Args.size(); I++) {
6031     unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6032     const ParmVarDecl *PVD =
6033         Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6034     bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6035     if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6036       // If we're checking for a potential constant expression, evaluate all
6037       // initializers even if some of them fail.
6038       if (!Info.noteFailure())
6039         return false;
6040       Success = false;
6041     }
6042   }
6043   return Success;
6044 }
6045 
6046 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6047 /// constructor or assignment operator.
6048 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6049                               const Expr *E, APValue &Result,
6050                               bool CopyObjectRepresentation) {
6051   // Find the reference argument.
6052   CallStackFrame *Frame = Info.CurrentCall;
6053   APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6054   if (!RefValue) {
6055     Info.FFDiag(E);
6056     return false;
6057   }
6058 
6059   // Copy out the contents of the RHS object.
6060   LValue RefLValue;
6061   RefLValue.setFrom(Info.Ctx, *RefValue);
6062   return handleLValueToRValueConversion(
6063       Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6064       CopyObjectRepresentation);
6065 }
6066 
6067 /// Evaluate a function call.
6068 static bool HandleFunctionCall(SourceLocation CallLoc,
6069                                const FunctionDecl *Callee, const LValue *This,
6070                                ArrayRef<const Expr *> Args, CallRef Call,
6071                                const Stmt *Body, EvalInfo &Info,
6072                                APValue &Result, const LValue *ResultSlot) {
6073   if (!Info.CheckCallLimit(CallLoc))
6074     return false;
6075 
6076   CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
6077 
6078   // For a trivial copy or move assignment, perform an APValue copy. This is
6079   // essential for unions, where the operations performed by the assignment
6080   // operator cannot be represented as statements.
6081   //
6082   // Skip this for non-union classes with no fields; in that case, the defaulted
6083   // copy/move does not actually read the object.
6084   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6085   if (MD && MD->isDefaulted() &&
6086       (MD->getParent()->isUnion() ||
6087        (MD->isTrivial() &&
6088         isReadByLvalueToRvalueConversion(MD->getParent())))) {
6089     assert(This &&
6090            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6091     APValue RHSValue;
6092     if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6093                            MD->getParent()->isUnion()))
6094       return false;
6095     if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() &&
6096         !HandleUnionActiveMemberChange(Info, Args[0], *This))
6097       return false;
6098     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6099                           RHSValue))
6100       return false;
6101     This->moveInto(Result);
6102     return true;
6103   } else if (MD && isLambdaCallOperator(MD)) {
6104     // We're in a lambda; determine the lambda capture field maps unless we're
6105     // just constexpr checking a lambda's call operator. constexpr checking is
6106     // done before the captures have been added to the closure object (unless
6107     // we're inferring constexpr-ness), so we don't have access to them in this
6108     // case. But since we don't need the captures to constexpr check, we can
6109     // just ignore them.
6110     if (!Info.checkingPotentialConstantExpression())
6111       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6112                                         Frame.LambdaThisCaptureField);
6113   }
6114 
6115   StmtResult Ret = {Result, ResultSlot};
6116   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6117   if (ESR == ESR_Succeeded) {
6118     if (Callee->getReturnType()->isVoidType())
6119       return true;
6120     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6121   }
6122   return ESR == ESR_Returned;
6123 }
6124 
6125 /// Evaluate a constructor call.
6126 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6127                                   CallRef Call,
6128                                   const CXXConstructorDecl *Definition,
6129                                   EvalInfo &Info, APValue &Result) {
6130   SourceLocation CallLoc = E->getExprLoc();
6131   if (!Info.CheckCallLimit(CallLoc))
6132     return false;
6133 
6134   const CXXRecordDecl *RD = Definition->getParent();
6135   if (RD->getNumVBases()) {
6136     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6137     return false;
6138   }
6139 
6140   EvalInfo::EvaluatingConstructorRAII EvalObj(
6141       Info,
6142       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6143       RD->getNumBases());
6144   CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
6145 
6146   // FIXME: Creating an APValue just to hold a nonexistent return value is
6147   // wasteful.
6148   APValue RetVal;
6149   StmtResult Ret = {RetVal, nullptr};
6150 
6151   // If it's a delegating constructor, delegate.
6152   if (Definition->isDelegatingConstructor()) {
6153     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6154     if ((*I)->getInit()->isValueDependent()) {
6155       if (!EvaluateDependentExpr((*I)->getInit(), Info))
6156         return false;
6157     } else {
6158       FullExpressionRAII InitScope(Info);
6159       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6160           !InitScope.destroy())
6161         return false;
6162     }
6163     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6164   }
6165 
6166   // For a trivial copy or move constructor, perform an APValue copy. This is
6167   // essential for unions (or classes with anonymous union members), where the
6168   // operations performed by the constructor cannot be represented by
6169   // ctor-initializers.
6170   //
6171   // Skip this for empty non-union classes; we should not perform an
6172   // lvalue-to-rvalue conversion on them because their copy constructor does not
6173   // actually read them.
6174   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6175       (Definition->getParent()->isUnion() ||
6176        (Definition->isTrivial() &&
6177         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6178     return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6179                              Definition->getParent()->isUnion());
6180   }
6181 
6182   // Reserve space for the struct members.
6183   if (!Result.hasValue()) {
6184     if (!RD->isUnion())
6185       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6186                        std::distance(RD->field_begin(), RD->field_end()));
6187     else
6188       // A union starts with no active member.
6189       Result = APValue((const FieldDecl*)nullptr);
6190   }
6191 
6192   if (RD->isInvalidDecl()) return false;
6193   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6194 
6195   // A scope for temporaries lifetime-extended by reference members.
6196   BlockScopeRAII LifetimeExtendedScope(Info);
6197 
6198   bool Success = true;
6199   unsigned BasesSeen = 0;
6200 #ifndef NDEBUG
6201   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6202 #endif
6203   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6204   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6205     // We might be initializing the same field again if this is an indirect
6206     // field initialization.
6207     if (FieldIt == RD->field_end() ||
6208         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6209       assert(Indirect && "fields out of order?");
6210       return;
6211     }
6212 
6213     // Default-initialize any fields with no explicit initializer.
6214     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6215       assert(FieldIt != RD->field_end() && "missing field?");
6216       if (!FieldIt->isUnnamedBitfield())
6217         Success &= getDefaultInitValue(
6218             FieldIt->getType(),
6219             Result.getStructField(FieldIt->getFieldIndex()));
6220     }
6221     ++FieldIt;
6222   };
6223   for (const auto *I : Definition->inits()) {
6224     LValue Subobject = This;
6225     LValue SubobjectParent = This;
6226     APValue *Value = &Result;
6227 
6228     // Determine the subobject to initialize.
6229     FieldDecl *FD = nullptr;
6230     if (I->isBaseInitializer()) {
6231       QualType BaseType(I->getBaseClass(), 0);
6232 #ifndef NDEBUG
6233       // Non-virtual base classes are initialized in the order in the class
6234       // definition. We have already checked for virtual base classes.
6235       assert(!BaseIt->isVirtual() && "virtual base for literal type");
6236       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6237              "base class initializers not in expected order");
6238       ++BaseIt;
6239 #endif
6240       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6241                                   BaseType->getAsCXXRecordDecl(), &Layout))
6242         return false;
6243       Value = &Result.getStructBase(BasesSeen++);
6244     } else if ((FD = I->getMember())) {
6245       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6246         return false;
6247       if (RD->isUnion()) {
6248         Result = APValue(FD);
6249         Value = &Result.getUnionValue();
6250       } else {
6251         SkipToField(FD, false);
6252         Value = &Result.getStructField(FD->getFieldIndex());
6253       }
6254     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6255       // Walk the indirect field decl's chain to find the object to initialize,
6256       // and make sure we've initialized every step along it.
6257       auto IndirectFieldChain = IFD->chain();
6258       for (auto *C : IndirectFieldChain) {
6259         FD = cast<FieldDecl>(C);
6260         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6261         // Switch the union field if it differs. This happens if we had
6262         // preceding zero-initialization, and we're now initializing a union
6263         // subobject other than the first.
6264         // FIXME: In this case, the values of the other subobjects are
6265         // specified, since zero-initialization sets all padding bits to zero.
6266         if (!Value->hasValue() ||
6267             (Value->isUnion() && Value->getUnionField() != FD)) {
6268           if (CD->isUnion())
6269             *Value = APValue(FD);
6270           else
6271             // FIXME: This immediately starts the lifetime of all members of
6272             // an anonymous struct. It would be preferable to strictly start
6273             // member lifetime in initialization order.
6274             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6275         }
6276         // Store Subobject as its parent before updating it for the last element
6277         // in the chain.
6278         if (C == IndirectFieldChain.back())
6279           SubobjectParent = Subobject;
6280         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6281           return false;
6282         if (CD->isUnion())
6283           Value = &Value->getUnionValue();
6284         else {
6285           if (C == IndirectFieldChain.front() && !RD->isUnion())
6286             SkipToField(FD, true);
6287           Value = &Value->getStructField(FD->getFieldIndex());
6288         }
6289       }
6290     } else {
6291       llvm_unreachable("unknown base initializer kind");
6292     }
6293 
6294     // Need to override This for implicit field initializers as in this case
6295     // This refers to innermost anonymous struct/union containing initializer,
6296     // not to currently constructed class.
6297     const Expr *Init = I->getInit();
6298     if (Init->isValueDependent()) {
6299       if (!EvaluateDependentExpr(Init, Info))
6300         return false;
6301     } else {
6302       ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6303                                     isa<CXXDefaultInitExpr>(Init));
6304       FullExpressionRAII InitScope(Info);
6305       if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6306           (FD && FD->isBitField() &&
6307            !truncateBitfieldValue(Info, Init, *Value, FD))) {
6308         // If we're checking for a potential constant expression, evaluate all
6309         // initializers even if some of them fail.
6310         if (!Info.noteFailure())
6311           return false;
6312         Success = false;
6313       }
6314     }
6315 
6316     // This is the point at which the dynamic type of the object becomes this
6317     // class type.
6318     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6319       EvalObj.finishedConstructingBases();
6320   }
6321 
6322   // Default-initialize any remaining fields.
6323   if (!RD->isUnion()) {
6324     for (; FieldIt != RD->field_end(); ++FieldIt) {
6325       if (!FieldIt->isUnnamedBitfield())
6326         Success &= getDefaultInitValue(
6327             FieldIt->getType(),
6328             Result.getStructField(FieldIt->getFieldIndex()));
6329     }
6330   }
6331 
6332   EvalObj.finishedConstructingFields();
6333 
6334   return Success &&
6335          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6336          LifetimeExtendedScope.destroy();
6337 }
6338 
6339 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6340                                   ArrayRef<const Expr*> Args,
6341                                   const CXXConstructorDecl *Definition,
6342                                   EvalInfo &Info, APValue &Result) {
6343   CallScopeRAII CallScope(Info);
6344   CallRef Call = Info.CurrentCall->createCall(Definition);
6345   if (!EvaluateArgs(Args, Call, Info, Definition))
6346     return false;
6347 
6348   return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6349          CallScope.destroy();
6350 }
6351 
6352 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6353                                   const LValue &This, APValue &Value,
6354                                   QualType T) {
6355   // Objects can only be destroyed while they're within their lifetimes.
6356   // FIXME: We have no representation for whether an object of type nullptr_t
6357   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6358   // as indeterminate instead?
6359   if (Value.isAbsent() && !T->isNullPtrType()) {
6360     APValue Printable;
6361     This.moveInto(Printable);
6362     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6363       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6364     return false;
6365   }
6366 
6367   // Invent an expression for location purposes.
6368   // FIXME: We shouldn't need to do this.
6369   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_RValue);
6370 
6371   // For arrays, destroy elements right-to-left.
6372   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6373     uint64_t Size = CAT->getSize().getZExtValue();
6374     QualType ElemT = CAT->getElementType();
6375 
6376     LValue ElemLV = This;
6377     ElemLV.addArray(Info, &LocE, CAT);
6378     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6379       return false;
6380 
6381     // Ensure that we have actual array elements available to destroy; the
6382     // destructors might mutate the value, so we can't run them on the array
6383     // filler.
6384     if (Size && Size > Value.getArrayInitializedElts())
6385       expandArray(Value, Value.getArraySize() - 1);
6386 
6387     for (; Size != 0; --Size) {
6388       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6389       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6390           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6391         return false;
6392     }
6393 
6394     // End the lifetime of this array now.
6395     Value = APValue();
6396     return true;
6397   }
6398 
6399   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6400   if (!RD) {
6401     if (T.isDestructedType()) {
6402       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6403       return false;
6404     }
6405 
6406     Value = APValue();
6407     return true;
6408   }
6409 
6410   if (RD->getNumVBases()) {
6411     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6412     return false;
6413   }
6414 
6415   const CXXDestructorDecl *DD = RD->getDestructor();
6416   if (!DD && !RD->hasTrivialDestructor()) {
6417     Info.FFDiag(CallLoc);
6418     return false;
6419   }
6420 
6421   if (!DD || DD->isTrivial() ||
6422       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6423     // A trivial destructor just ends the lifetime of the object. Check for
6424     // this case before checking for a body, because we might not bother
6425     // building a body for a trivial destructor. Note that it doesn't matter
6426     // whether the destructor is constexpr in this case; all trivial
6427     // destructors are constexpr.
6428     //
6429     // If an anonymous union would be destroyed, some enclosing destructor must
6430     // have been explicitly defined, and the anonymous union destruction should
6431     // have no effect.
6432     Value = APValue();
6433     return true;
6434   }
6435 
6436   if (!Info.CheckCallLimit(CallLoc))
6437     return false;
6438 
6439   const FunctionDecl *Definition = nullptr;
6440   const Stmt *Body = DD->getBody(Definition);
6441 
6442   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6443     return false;
6444 
6445   CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
6446 
6447   // We're now in the period of destruction of this object.
6448   unsigned BasesLeft = RD->getNumBases();
6449   EvalInfo::EvaluatingDestructorRAII EvalObj(
6450       Info,
6451       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6452   if (!EvalObj.DidInsert) {
6453     // C++2a [class.dtor]p19:
6454     //   the behavior is undefined if the destructor is invoked for an object
6455     //   whose lifetime has ended
6456     // (Note that formally the lifetime ends when the period of destruction
6457     // begins, even though certain uses of the object remain valid until the
6458     // period of destruction ends.)
6459     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6460     return false;
6461   }
6462 
6463   // FIXME: Creating an APValue just to hold a nonexistent return value is
6464   // wasteful.
6465   APValue RetVal;
6466   StmtResult Ret = {RetVal, nullptr};
6467   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6468     return false;
6469 
6470   // A union destructor does not implicitly destroy its members.
6471   if (RD->isUnion())
6472     return true;
6473 
6474   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6475 
6476   // We don't have a good way to iterate fields in reverse, so collect all the
6477   // fields first and then walk them backwards.
6478   SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
6479   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6480     if (FD->isUnnamedBitfield())
6481       continue;
6482 
6483     LValue Subobject = This;
6484     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6485       return false;
6486 
6487     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6488     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6489                                FD->getType()))
6490       return false;
6491   }
6492 
6493   if (BasesLeft != 0)
6494     EvalObj.startedDestroyingBases();
6495 
6496   // Destroy base classes in reverse order.
6497   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6498     --BasesLeft;
6499 
6500     QualType BaseType = Base.getType();
6501     LValue Subobject = This;
6502     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6503                                 BaseType->getAsCXXRecordDecl(), &Layout))
6504       return false;
6505 
6506     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6507     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6508                                BaseType))
6509       return false;
6510   }
6511   assert(BasesLeft == 0 && "NumBases was wrong?");
6512 
6513   // The period of destruction ends now. The object is gone.
6514   Value = APValue();
6515   return true;
6516 }
6517 
6518 namespace {
6519 struct DestroyObjectHandler {
6520   EvalInfo &Info;
6521   const Expr *E;
6522   const LValue &This;
6523   const AccessKinds AccessKind;
6524 
6525   typedef bool result_type;
6526   bool failed() { return false; }
6527   bool found(APValue &Subobj, QualType SubobjType) {
6528     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6529                                  SubobjType);
6530   }
6531   bool found(APSInt &Value, QualType SubobjType) {
6532     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6533     return false;
6534   }
6535   bool found(APFloat &Value, QualType SubobjType) {
6536     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6537     return false;
6538   }
6539 };
6540 }
6541 
6542 /// Perform a destructor or pseudo-destructor call on the given object, which
6543 /// might in general not be a complete object.
6544 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6545                               const LValue &This, QualType ThisType) {
6546   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6547   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6548   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6549 }
6550 
6551 /// Destroy and end the lifetime of the given complete object.
6552 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6553                               APValue::LValueBase LVBase, APValue &Value,
6554                               QualType T) {
6555   // If we've had an unmodeled side-effect, we can't rely on mutable state
6556   // (such as the object we're about to destroy) being correct.
6557   if (Info.EvalStatus.HasSideEffects)
6558     return false;
6559 
6560   LValue LV;
6561   LV.set({LVBase});
6562   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6563 }
6564 
6565 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6566 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6567                                   LValue &Result) {
6568   if (Info.checkingPotentialConstantExpression() ||
6569       Info.SpeculativeEvaluationDepth)
6570     return false;
6571 
6572   // This is permitted only within a call to std::allocator<T>::allocate.
6573   auto Caller = Info.getStdAllocatorCaller("allocate");
6574   if (!Caller) {
6575     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6576                                      ? diag::note_constexpr_new_untyped
6577                                      : diag::note_constexpr_new);
6578     return false;
6579   }
6580 
6581   QualType ElemType = Caller.ElemType;
6582   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6583     Info.FFDiag(E->getExprLoc(),
6584                 diag::note_constexpr_new_not_complete_object_type)
6585         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6586     return false;
6587   }
6588 
6589   APSInt ByteSize;
6590   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6591     return false;
6592   bool IsNothrow = false;
6593   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6594     EvaluateIgnoredValue(Info, E->getArg(I));
6595     IsNothrow |= E->getType()->isNothrowT();
6596   }
6597 
6598   CharUnits ElemSize;
6599   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6600     return false;
6601   APInt Size, Remainder;
6602   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6603   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6604   if (Remainder != 0) {
6605     // This likely indicates a bug in the implementation of 'std::allocator'.
6606     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6607         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6608     return false;
6609   }
6610 
6611   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6612     if (IsNothrow) {
6613       Result.setNull(Info.Ctx, E->getType());
6614       return true;
6615     }
6616 
6617     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6618     return false;
6619   }
6620 
6621   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6622                                                      ArrayType::Normal, 0);
6623   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6624   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6625   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6626   return true;
6627 }
6628 
6629 static bool hasVirtualDestructor(QualType T) {
6630   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6631     if (CXXDestructorDecl *DD = RD->getDestructor())
6632       return DD->isVirtual();
6633   return false;
6634 }
6635 
6636 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6637   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6638     if (CXXDestructorDecl *DD = RD->getDestructor())
6639       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6640   return nullptr;
6641 }
6642 
6643 /// Check that the given object is a suitable pointer to a heap allocation that
6644 /// still exists and is of the right kind for the purpose of a deletion.
6645 ///
6646 /// On success, returns the heap allocation to deallocate. On failure, produces
6647 /// a diagnostic and returns None.
6648 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6649                                             const LValue &Pointer,
6650                                             DynAlloc::Kind DeallocKind) {
6651   auto PointerAsString = [&] {
6652     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6653   };
6654 
6655   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6656   if (!DA) {
6657     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6658         << PointerAsString();
6659     if (Pointer.Base)
6660       NoteLValueLocation(Info, Pointer.Base);
6661     return None;
6662   }
6663 
6664   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6665   if (!Alloc) {
6666     Info.FFDiag(E, diag::note_constexpr_double_delete);
6667     return None;
6668   }
6669 
6670   QualType AllocType = Pointer.Base.getDynamicAllocType();
6671   if (DeallocKind != (*Alloc)->getKind()) {
6672     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6673         << DeallocKind << (*Alloc)->getKind() << AllocType;
6674     NoteLValueLocation(Info, Pointer.Base);
6675     return None;
6676   }
6677 
6678   bool Subobject = false;
6679   if (DeallocKind == DynAlloc::New) {
6680     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6681                 Pointer.Designator.isOnePastTheEnd();
6682   } else {
6683     Subobject = Pointer.Designator.Entries.size() != 1 ||
6684                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6685   }
6686   if (Subobject) {
6687     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6688         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6689     return None;
6690   }
6691 
6692   return Alloc;
6693 }
6694 
6695 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6696 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6697   if (Info.checkingPotentialConstantExpression() ||
6698       Info.SpeculativeEvaluationDepth)
6699     return false;
6700 
6701   // This is permitted only within a call to std::allocator<T>::deallocate.
6702   if (!Info.getStdAllocatorCaller("deallocate")) {
6703     Info.FFDiag(E->getExprLoc());
6704     return true;
6705   }
6706 
6707   LValue Pointer;
6708   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6709     return false;
6710   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6711     EvaluateIgnoredValue(Info, E->getArg(I));
6712 
6713   if (Pointer.Designator.Invalid)
6714     return false;
6715 
6716   // Deleting a null pointer has no effect.
6717   if (Pointer.isNullPointer())
6718     return true;
6719 
6720   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6721     return false;
6722 
6723   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6724   return true;
6725 }
6726 
6727 //===----------------------------------------------------------------------===//
6728 // Generic Evaluation
6729 //===----------------------------------------------------------------------===//
6730 namespace {
6731 
6732 class BitCastBuffer {
6733   // FIXME: We're going to need bit-level granularity when we support
6734   // bit-fields.
6735   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6736   // we don't support a host or target where that is the case. Still, we should
6737   // use a more generic type in case we ever do.
6738   SmallVector<Optional<unsigned char>, 32> Bytes;
6739 
6740   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6741                 "Need at least 8 bit unsigned char");
6742 
6743   bool TargetIsLittleEndian;
6744 
6745 public:
6746   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6747       : Bytes(Width.getQuantity()),
6748         TargetIsLittleEndian(TargetIsLittleEndian) {}
6749 
6750   LLVM_NODISCARD
6751   bool readObject(CharUnits Offset, CharUnits Width,
6752                   SmallVectorImpl<unsigned char> &Output) const {
6753     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6754       // If a byte of an integer is uninitialized, then the whole integer is
6755       // uninitalized.
6756       if (!Bytes[I.getQuantity()])
6757         return false;
6758       Output.push_back(*Bytes[I.getQuantity()]);
6759     }
6760     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6761       std::reverse(Output.begin(), Output.end());
6762     return true;
6763   }
6764 
6765   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6766     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6767       std::reverse(Input.begin(), Input.end());
6768 
6769     size_t Index = 0;
6770     for (unsigned char Byte : Input) {
6771       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6772       Bytes[Offset.getQuantity() + Index] = Byte;
6773       ++Index;
6774     }
6775   }
6776 
6777   size_t size() { return Bytes.size(); }
6778 };
6779 
6780 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6781 /// target would represent the value at runtime.
6782 class APValueToBufferConverter {
6783   EvalInfo &Info;
6784   BitCastBuffer Buffer;
6785   const CastExpr *BCE;
6786 
6787   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6788                            const CastExpr *BCE)
6789       : Info(Info),
6790         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6791         BCE(BCE) {}
6792 
6793   bool visit(const APValue &Val, QualType Ty) {
6794     return visit(Val, Ty, CharUnits::fromQuantity(0));
6795   }
6796 
6797   // Write out Val with type Ty into Buffer starting at Offset.
6798   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6799     assert((size_t)Offset.getQuantity() <= Buffer.size());
6800 
6801     // As a special case, nullptr_t has an indeterminate value.
6802     if (Ty->isNullPtrType())
6803       return true;
6804 
6805     // Dig through Src to find the byte at SrcOffset.
6806     switch (Val.getKind()) {
6807     case APValue::Indeterminate:
6808     case APValue::None:
6809       return true;
6810 
6811     case APValue::Int:
6812       return visitInt(Val.getInt(), Ty, Offset);
6813     case APValue::Float:
6814       return visitFloat(Val.getFloat(), Ty, Offset);
6815     case APValue::Array:
6816       return visitArray(Val, Ty, Offset);
6817     case APValue::Struct:
6818       return visitRecord(Val, Ty, Offset);
6819 
6820     case APValue::ComplexInt:
6821     case APValue::ComplexFloat:
6822     case APValue::Vector:
6823     case APValue::FixedPoint:
6824       // FIXME: We should support these.
6825 
6826     case APValue::Union:
6827     case APValue::MemberPointer:
6828     case APValue::AddrLabelDiff: {
6829       Info.FFDiag(BCE->getBeginLoc(),
6830                   diag::note_constexpr_bit_cast_unsupported_type)
6831           << Ty;
6832       return false;
6833     }
6834 
6835     case APValue::LValue:
6836       llvm_unreachable("LValue subobject in bit_cast?");
6837     }
6838     llvm_unreachable("Unhandled APValue::ValueKind");
6839   }
6840 
6841   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6842     const RecordDecl *RD = Ty->getAsRecordDecl();
6843     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6844 
6845     // Visit the base classes.
6846     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6847       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6848         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6849         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6850 
6851         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6852                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6853           return false;
6854       }
6855     }
6856 
6857     // Visit the fields.
6858     unsigned FieldIdx = 0;
6859     for (FieldDecl *FD : RD->fields()) {
6860       if (FD->isBitField()) {
6861         Info.FFDiag(BCE->getBeginLoc(),
6862                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6863         return false;
6864       }
6865 
6866       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6867 
6868       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6869              "only bit-fields can have sub-char alignment");
6870       CharUnits FieldOffset =
6871           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6872       QualType FieldTy = FD->getType();
6873       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6874         return false;
6875       ++FieldIdx;
6876     }
6877 
6878     return true;
6879   }
6880 
6881   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6882     const auto *CAT =
6883         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6884     if (!CAT)
6885       return false;
6886 
6887     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6888     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6889     unsigned ArraySize = Val.getArraySize();
6890     // First, initialize the initialized elements.
6891     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6892       const APValue &SubObj = Val.getArrayInitializedElt(I);
6893       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6894         return false;
6895     }
6896 
6897     // Next, initialize the rest of the array using the filler.
6898     if (Val.hasArrayFiller()) {
6899       const APValue &Filler = Val.getArrayFiller();
6900       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6901         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6902           return false;
6903       }
6904     }
6905 
6906     return true;
6907   }
6908 
6909   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6910     APSInt AdjustedVal = Val;
6911     unsigned Width = AdjustedVal.getBitWidth();
6912     if (Ty->isBooleanType()) {
6913       Width = Info.Ctx.getTypeSize(Ty);
6914       AdjustedVal = AdjustedVal.extend(Width);
6915     }
6916 
6917     SmallVector<unsigned char, 8> Bytes(Width / 8);
6918     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
6919     Buffer.writeObject(Offset, Bytes);
6920     return true;
6921   }
6922 
6923   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6924     APSInt AsInt(Val.bitcastToAPInt());
6925     return visitInt(AsInt, Ty, Offset);
6926   }
6927 
6928 public:
6929   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6930                                          const CastExpr *BCE) {
6931     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6932     APValueToBufferConverter Converter(Info, DstSize, BCE);
6933     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6934       return None;
6935     return Converter.Buffer;
6936   }
6937 };
6938 
6939 /// Write an BitCastBuffer into an APValue.
6940 class BufferToAPValueConverter {
6941   EvalInfo &Info;
6942   const BitCastBuffer &Buffer;
6943   const CastExpr *BCE;
6944 
6945   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6946                            const CastExpr *BCE)
6947       : Info(Info), Buffer(Buffer), BCE(BCE) {}
6948 
6949   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6950   // with an invalid type, so anything left is a deficiency on our part (FIXME).
6951   // Ideally this will be unreachable.
6952   llvm::NoneType unsupportedType(QualType Ty) {
6953     Info.FFDiag(BCE->getBeginLoc(),
6954                 diag::note_constexpr_bit_cast_unsupported_type)
6955         << Ty;
6956     return None;
6957   }
6958 
6959   llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) {
6960     Info.FFDiag(BCE->getBeginLoc(),
6961                 diag::note_constexpr_bit_cast_unrepresentable_value)
6962         << Ty << Val.toString(/*Radix=*/10);
6963     return None;
6964   }
6965 
6966   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6967                           const EnumType *EnumSugar = nullptr) {
6968     if (T->isNullPtrType()) {
6969       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6970       return APValue((Expr *)nullptr,
6971                      /*Offset=*/CharUnits::fromQuantity(NullValue),
6972                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6973     }
6974 
6975     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6976 
6977     // Work around floating point types that contain unused padding bytes. This
6978     // is really just `long double` on x86, which is the only fundamental type
6979     // with padding bytes.
6980     if (T->isRealFloatingType()) {
6981       const llvm::fltSemantics &Semantics =
6982           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6983       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
6984       assert(NumBits % 8 == 0);
6985       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
6986       if (NumBytes != SizeOf)
6987         SizeOf = NumBytes;
6988     }
6989 
6990     SmallVector<uint8_t, 8> Bytes;
6991     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
6992       // If this is std::byte or unsigned char, then its okay to store an
6993       // indeterminate value.
6994       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
6995       bool IsUChar =
6996           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
6997                          T->isSpecificBuiltinType(BuiltinType::Char_U));
6998       if (!IsStdByte && !IsUChar) {
6999         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7000         Info.FFDiag(BCE->getExprLoc(),
7001                     diag::note_constexpr_bit_cast_indet_dest)
7002             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7003         return None;
7004       }
7005 
7006       return APValue::IndeterminateValue();
7007     }
7008 
7009     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7010     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7011 
7012     if (T->isIntegralOrEnumerationType()) {
7013       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7014 
7015       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7016       if (IntWidth != Val.getBitWidth()) {
7017         APSInt Truncated = Val.trunc(IntWidth);
7018         if (Truncated.extend(Val.getBitWidth()) != Val)
7019           return unrepresentableValue(QualType(T, 0), Val);
7020         Val = Truncated;
7021       }
7022 
7023       return APValue(Val);
7024     }
7025 
7026     if (T->isRealFloatingType()) {
7027       const llvm::fltSemantics &Semantics =
7028           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7029       return APValue(APFloat(Semantics, Val));
7030     }
7031 
7032     return unsupportedType(QualType(T, 0));
7033   }
7034 
7035   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7036     const RecordDecl *RD = RTy->getAsRecordDecl();
7037     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7038 
7039     unsigned NumBases = 0;
7040     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7041       NumBases = CXXRD->getNumBases();
7042 
7043     APValue ResultVal(APValue::UninitStruct(), NumBases,
7044                       std::distance(RD->field_begin(), RD->field_end()));
7045 
7046     // Visit the base classes.
7047     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7048       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7049         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7050         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7051         if (BaseDecl->isEmpty() ||
7052             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7053           continue;
7054 
7055         Optional<APValue> SubObj = visitType(
7056             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7057         if (!SubObj)
7058           return None;
7059         ResultVal.getStructBase(I) = *SubObj;
7060       }
7061     }
7062 
7063     // Visit the fields.
7064     unsigned FieldIdx = 0;
7065     for (FieldDecl *FD : RD->fields()) {
7066       // FIXME: We don't currently support bit-fields. A lot of the logic for
7067       // this is in CodeGen, so we need to factor it around.
7068       if (FD->isBitField()) {
7069         Info.FFDiag(BCE->getBeginLoc(),
7070                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7071         return None;
7072       }
7073 
7074       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7075       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7076 
7077       CharUnits FieldOffset =
7078           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7079           Offset;
7080       QualType FieldTy = FD->getType();
7081       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7082       if (!SubObj)
7083         return None;
7084       ResultVal.getStructField(FieldIdx) = *SubObj;
7085       ++FieldIdx;
7086     }
7087 
7088     return ResultVal;
7089   }
7090 
7091   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7092     QualType RepresentationType = Ty->getDecl()->getIntegerType();
7093     assert(!RepresentationType.isNull() &&
7094            "enum forward decl should be caught by Sema");
7095     const auto *AsBuiltin =
7096         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7097     // Recurse into the underlying type. Treat std::byte transparently as
7098     // unsigned char.
7099     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7100   }
7101 
7102   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7103     size_t Size = Ty->getSize().getLimitedValue();
7104     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7105 
7106     APValue ArrayValue(APValue::UninitArray(), Size, Size);
7107     for (size_t I = 0; I != Size; ++I) {
7108       Optional<APValue> ElementValue =
7109           visitType(Ty->getElementType(), Offset + I * ElementWidth);
7110       if (!ElementValue)
7111         return None;
7112       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7113     }
7114 
7115     return ArrayValue;
7116   }
7117 
7118   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7119     return unsupportedType(QualType(Ty, 0));
7120   }
7121 
7122   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7123     QualType Can = Ty.getCanonicalType();
7124 
7125     switch (Can->getTypeClass()) {
7126 #define TYPE(Class, Base)                                                      \
7127   case Type::Class:                                                            \
7128     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7129 #define ABSTRACT_TYPE(Class, Base)
7130 #define NON_CANONICAL_TYPE(Class, Base)                                        \
7131   case Type::Class:                                                            \
7132     llvm_unreachable("non-canonical type should be impossible!");
7133 #define DEPENDENT_TYPE(Class, Base)                                            \
7134   case Type::Class:                                                            \
7135     llvm_unreachable(                                                          \
7136         "dependent types aren't supported in the constant evaluator!");
7137 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7138   case Type::Class:                                                            \
7139     llvm_unreachable("either dependent or not canonical!");
7140 #include "clang/AST/TypeNodes.inc"
7141     }
7142     llvm_unreachable("Unhandled Type::TypeClass");
7143   }
7144 
7145 public:
7146   // Pull out a full value of type DstType.
7147   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7148                                    const CastExpr *BCE) {
7149     BufferToAPValueConverter Converter(Info, Buffer, BCE);
7150     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7151   }
7152 };
7153 
7154 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7155                                                  QualType Ty, EvalInfo *Info,
7156                                                  const ASTContext &Ctx,
7157                                                  bool CheckingDest) {
7158   Ty = Ty.getCanonicalType();
7159 
7160   auto diag = [&](int Reason) {
7161     if (Info)
7162       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7163           << CheckingDest << (Reason == 4) << Reason;
7164     return false;
7165   };
7166   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7167     if (Info)
7168       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7169           << NoteTy << Construct << Ty;
7170     return false;
7171   };
7172 
7173   if (Ty->isUnionType())
7174     return diag(0);
7175   if (Ty->isPointerType())
7176     return diag(1);
7177   if (Ty->isMemberPointerType())
7178     return diag(2);
7179   if (Ty.isVolatileQualified())
7180     return diag(3);
7181 
7182   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7183     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7184       for (CXXBaseSpecifier &BS : CXXRD->bases())
7185         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7186                                                   CheckingDest))
7187           return note(1, BS.getType(), BS.getBeginLoc());
7188     }
7189     for (FieldDecl *FD : Record->fields()) {
7190       if (FD->getType()->isReferenceType())
7191         return diag(4);
7192       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7193                                                 CheckingDest))
7194         return note(0, FD->getType(), FD->getBeginLoc());
7195     }
7196   }
7197 
7198   if (Ty->isArrayType() &&
7199       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7200                                             Info, Ctx, CheckingDest))
7201     return false;
7202 
7203   return true;
7204 }
7205 
7206 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7207                                              const ASTContext &Ctx,
7208                                              const CastExpr *BCE) {
7209   bool DestOK = checkBitCastConstexprEligibilityType(
7210       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7211   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7212                                 BCE->getBeginLoc(),
7213                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
7214   return SourceOK;
7215 }
7216 
7217 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7218                                         APValue &SourceValue,
7219                                         const CastExpr *BCE) {
7220   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7221          "no host or target supports non 8-bit chars");
7222   assert(SourceValue.isLValue() &&
7223          "LValueToRValueBitcast requires an lvalue operand!");
7224 
7225   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7226     return false;
7227 
7228   LValue SourceLValue;
7229   APValue SourceRValue;
7230   SourceLValue.setFrom(Info.Ctx, SourceValue);
7231   if (!handleLValueToRValueConversion(
7232           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7233           SourceRValue, /*WantObjectRepresentation=*/true))
7234     return false;
7235 
7236   // Read out SourceValue into a char buffer.
7237   Optional<BitCastBuffer> Buffer =
7238       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7239   if (!Buffer)
7240     return false;
7241 
7242   // Write out the buffer into a new APValue.
7243   Optional<APValue> MaybeDestValue =
7244       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7245   if (!MaybeDestValue)
7246     return false;
7247 
7248   DestValue = std::move(*MaybeDestValue);
7249   return true;
7250 }
7251 
7252 template <class Derived>
7253 class ExprEvaluatorBase
7254   : public ConstStmtVisitor<Derived, bool> {
7255 private:
7256   Derived &getDerived() { return static_cast<Derived&>(*this); }
7257   bool DerivedSuccess(const APValue &V, const Expr *E) {
7258     return getDerived().Success(V, E);
7259   }
7260   bool DerivedZeroInitialization(const Expr *E) {
7261     return getDerived().ZeroInitialization(E);
7262   }
7263 
7264   // Check whether a conditional operator with a non-constant condition is a
7265   // potential constant expression. If neither arm is a potential constant
7266   // expression, then the conditional operator is not either.
7267   template<typename ConditionalOperator>
7268   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7269     assert(Info.checkingPotentialConstantExpression());
7270 
7271     // Speculatively evaluate both arms.
7272     SmallVector<PartialDiagnosticAt, 8> Diag;
7273     {
7274       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7275       StmtVisitorTy::Visit(E->getFalseExpr());
7276       if (Diag.empty())
7277         return;
7278     }
7279 
7280     {
7281       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7282       Diag.clear();
7283       StmtVisitorTy::Visit(E->getTrueExpr());
7284       if (Diag.empty())
7285         return;
7286     }
7287 
7288     Error(E, diag::note_constexpr_conditional_never_const);
7289   }
7290 
7291 
7292   template<typename ConditionalOperator>
7293   bool HandleConditionalOperator(const ConditionalOperator *E) {
7294     bool BoolResult;
7295     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7296       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7297         CheckPotentialConstantConditional(E);
7298         return false;
7299       }
7300       if (Info.noteFailure()) {
7301         StmtVisitorTy::Visit(E->getTrueExpr());
7302         StmtVisitorTy::Visit(E->getFalseExpr());
7303       }
7304       return false;
7305     }
7306 
7307     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7308     return StmtVisitorTy::Visit(EvalExpr);
7309   }
7310 
7311 protected:
7312   EvalInfo &Info;
7313   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7314   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7315 
7316   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7317     return Info.CCEDiag(E, D);
7318   }
7319 
7320   bool ZeroInitialization(const Expr *E) { return Error(E); }
7321 
7322 public:
7323   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7324 
7325   EvalInfo &getEvalInfo() { return Info; }
7326 
7327   /// Report an evaluation error. This should only be called when an error is
7328   /// first discovered. When propagating an error, just return false.
7329   bool Error(const Expr *E, diag::kind D) {
7330     Info.FFDiag(E, D);
7331     return false;
7332   }
7333   bool Error(const Expr *E) {
7334     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7335   }
7336 
7337   bool VisitStmt(const Stmt *) {
7338     llvm_unreachable("Expression evaluator should not be called on stmts");
7339   }
7340   bool VisitExpr(const Expr *E) {
7341     return Error(E);
7342   }
7343 
7344   bool VisitConstantExpr(const ConstantExpr *E) {
7345     if (E->hasAPValueResult())
7346       return DerivedSuccess(E->getAPValueResult(), E);
7347 
7348     return StmtVisitorTy::Visit(E->getSubExpr());
7349   }
7350 
7351   bool VisitParenExpr(const ParenExpr *E)
7352     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7353   bool VisitUnaryExtension(const UnaryOperator *E)
7354     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7355   bool VisitUnaryPlus(const UnaryOperator *E)
7356     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7357   bool VisitChooseExpr(const ChooseExpr *E)
7358     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7359   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7360     { return StmtVisitorTy::Visit(E->getResultExpr()); }
7361   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7362     { return StmtVisitorTy::Visit(E->getReplacement()); }
7363   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7364     TempVersionRAII RAII(*Info.CurrentCall);
7365     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7366     return StmtVisitorTy::Visit(E->getExpr());
7367   }
7368   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7369     TempVersionRAII RAII(*Info.CurrentCall);
7370     // The initializer may not have been parsed yet, or might be erroneous.
7371     if (!E->getExpr())
7372       return Error(E);
7373     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7374     return StmtVisitorTy::Visit(E->getExpr());
7375   }
7376 
7377   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7378     FullExpressionRAII Scope(Info);
7379     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7380   }
7381 
7382   // Temporaries are registered when created, so we don't care about
7383   // CXXBindTemporaryExpr.
7384   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7385     return StmtVisitorTy::Visit(E->getSubExpr());
7386   }
7387 
7388   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7389     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7390     return static_cast<Derived*>(this)->VisitCastExpr(E);
7391   }
7392   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7393     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7394       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7395     return static_cast<Derived*>(this)->VisitCastExpr(E);
7396   }
7397   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7398     return static_cast<Derived*>(this)->VisitCastExpr(E);
7399   }
7400 
7401   bool VisitBinaryOperator(const BinaryOperator *E) {
7402     switch (E->getOpcode()) {
7403     default:
7404       return Error(E);
7405 
7406     case BO_Comma:
7407       VisitIgnoredValue(E->getLHS());
7408       return StmtVisitorTy::Visit(E->getRHS());
7409 
7410     case BO_PtrMemD:
7411     case BO_PtrMemI: {
7412       LValue Obj;
7413       if (!HandleMemberPointerAccess(Info, E, Obj))
7414         return false;
7415       APValue Result;
7416       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7417         return false;
7418       return DerivedSuccess(Result, E);
7419     }
7420     }
7421   }
7422 
7423   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7424     return StmtVisitorTy::Visit(E->getSemanticForm());
7425   }
7426 
7427   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7428     // Evaluate and cache the common expression. We treat it as a temporary,
7429     // even though it's not quite the same thing.
7430     LValue CommonLV;
7431     if (!Evaluate(Info.CurrentCall->createTemporary(
7432                       E->getOpaqueValue(),
7433                       getStorageType(Info.Ctx, E->getOpaqueValue()),
7434                       ScopeKind::FullExpression, CommonLV),
7435                   Info, E->getCommon()))
7436       return false;
7437 
7438     return HandleConditionalOperator(E);
7439   }
7440 
7441   bool VisitConditionalOperator(const ConditionalOperator *E) {
7442     bool IsBcpCall = false;
7443     // If the condition (ignoring parens) is a __builtin_constant_p call,
7444     // the result is a constant expression if it can be folded without
7445     // side-effects. This is an important GNU extension. See GCC PR38377
7446     // for discussion.
7447     if (const CallExpr *CallCE =
7448           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7449       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7450         IsBcpCall = true;
7451 
7452     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7453     // constant expression; we can't check whether it's potentially foldable.
7454     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7455     // it would return 'false' in this mode.
7456     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7457       return false;
7458 
7459     FoldConstant Fold(Info, IsBcpCall);
7460     if (!HandleConditionalOperator(E)) {
7461       Fold.keepDiagnostics();
7462       return false;
7463     }
7464 
7465     return true;
7466   }
7467 
7468   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7469     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7470       return DerivedSuccess(*Value, E);
7471 
7472     const Expr *Source = E->getSourceExpr();
7473     if (!Source)
7474       return Error(E);
7475     if (Source == E) { // sanity checking.
7476       assert(0 && "OpaqueValueExpr recursively refers to itself");
7477       return Error(E);
7478     }
7479     return StmtVisitorTy::Visit(Source);
7480   }
7481 
7482   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7483     for (const Expr *SemE : E->semantics()) {
7484       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7485         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7486         // result expression: there could be two different LValues that would
7487         // refer to the same object in that case, and we can't model that.
7488         if (SemE == E->getResultExpr())
7489           return Error(E);
7490 
7491         // Unique OVEs get evaluated if and when we encounter them when
7492         // emitting the rest of the semantic form, rather than eagerly.
7493         if (OVE->isUnique())
7494           continue;
7495 
7496         LValue LV;
7497         if (!Evaluate(Info.CurrentCall->createTemporary(
7498                           OVE, getStorageType(Info.Ctx, OVE),
7499                           ScopeKind::FullExpression, LV),
7500                       Info, OVE->getSourceExpr()))
7501           return false;
7502       } else if (SemE == E->getResultExpr()) {
7503         if (!StmtVisitorTy::Visit(SemE))
7504           return false;
7505       } else {
7506         if (!EvaluateIgnoredValue(Info, SemE))
7507           return false;
7508       }
7509     }
7510     return true;
7511   }
7512 
7513   bool VisitCallExpr(const CallExpr *E) {
7514     APValue Result;
7515     if (!handleCallExpr(E, Result, nullptr))
7516       return false;
7517     return DerivedSuccess(Result, E);
7518   }
7519 
7520   bool handleCallExpr(const CallExpr *E, APValue &Result,
7521                      const LValue *ResultSlot) {
7522     CallScopeRAII CallScope(Info);
7523 
7524     const Expr *Callee = E->getCallee()->IgnoreParens();
7525     QualType CalleeType = Callee->getType();
7526 
7527     const FunctionDecl *FD = nullptr;
7528     LValue *This = nullptr, ThisVal;
7529     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7530     bool HasQualifier = false;
7531 
7532     CallRef Call;
7533 
7534     // Extract function decl and 'this' pointer from the callee.
7535     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7536       const CXXMethodDecl *Member = nullptr;
7537       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7538         // Explicit bound member calls, such as x.f() or p->g();
7539         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7540           return false;
7541         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7542         if (!Member)
7543           return Error(Callee);
7544         This = &ThisVal;
7545         HasQualifier = ME->hasQualifier();
7546       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7547         // Indirect bound member calls ('.*' or '->*').
7548         const ValueDecl *D =
7549             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7550         if (!D)
7551           return false;
7552         Member = dyn_cast<CXXMethodDecl>(D);
7553         if (!Member)
7554           return Error(Callee);
7555         This = &ThisVal;
7556       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7557         if (!Info.getLangOpts().CPlusPlus20)
7558           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7559         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7560                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7561       } else
7562         return Error(Callee);
7563       FD = Member;
7564     } else if (CalleeType->isFunctionPointerType()) {
7565       LValue CalleeLV;
7566       if (!EvaluatePointer(Callee, CalleeLV, Info))
7567         return false;
7568 
7569       if (!CalleeLV.getLValueOffset().isZero())
7570         return Error(Callee);
7571       FD = dyn_cast_or_null<FunctionDecl>(
7572           CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7573       if (!FD)
7574         return Error(Callee);
7575       // Don't call function pointers which have been cast to some other type.
7576       // Per DR (no number yet), the caller and callee can differ in noexcept.
7577       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7578         CalleeType->getPointeeType(), FD->getType())) {
7579         return Error(E);
7580       }
7581 
7582       // For an (overloaded) assignment expression, evaluate the RHS before the
7583       // LHS.
7584       auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7585       if (OCE && OCE->isAssignmentOp()) {
7586         assert(Args.size() == 2 && "wrong number of arguments in assignment");
7587         Call = Info.CurrentCall->createCall(FD);
7588         if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7589                           Info, FD, /*RightToLeft=*/true))
7590           return false;
7591       }
7592 
7593       // Overloaded operator calls to member functions are represented as normal
7594       // calls with '*this' as the first argument.
7595       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7596       if (MD && !MD->isStatic()) {
7597         // FIXME: When selecting an implicit conversion for an overloaded
7598         // operator delete, we sometimes try to evaluate calls to conversion
7599         // operators without a 'this' parameter!
7600         if (Args.empty())
7601           return Error(E);
7602 
7603         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7604           return false;
7605         This = &ThisVal;
7606         Args = Args.slice(1);
7607       } else if (MD && MD->isLambdaStaticInvoker()) {
7608         // Map the static invoker for the lambda back to the call operator.
7609         // Conveniently, we don't have to slice out the 'this' argument (as is
7610         // being done for the non-static case), since a static member function
7611         // doesn't have an implicit argument passed in.
7612         const CXXRecordDecl *ClosureClass = MD->getParent();
7613         assert(
7614             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7615             "Number of captures must be zero for conversion to function-ptr");
7616 
7617         const CXXMethodDecl *LambdaCallOp =
7618             ClosureClass->getLambdaCallOperator();
7619 
7620         // Set 'FD', the function that will be called below, to the call
7621         // operator.  If the closure object represents a generic lambda, find
7622         // the corresponding specialization of the call operator.
7623 
7624         if (ClosureClass->isGenericLambda()) {
7625           assert(MD->isFunctionTemplateSpecialization() &&
7626                  "A generic lambda's static-invoker function must be a "
7627                  "template specialization");
7628           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7629           FunctionTemplateDecl *CallOpTemplate =
7630               LambdaCallOp->getDescribedFunctionTemplate();
7631           void *InsertPos = nullptr;
7632           FunctionDecl *CorrespondingCallOpSpecialization =
7633               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7634           assert(CorrespondingCallOpSpecialization &&
7635                  "We must always have a function call operator specialization "
7636                  "that corresponds to our static invoker specialization");
7637           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7638         } else
7639           FD = LambdaCallOp;
7640       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7641         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7642             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7643           LValue Ptr;
7644           if (!HandleOperatorNewCall(Info, E, Ptr))
7645             return false;
7646           Ptr.moveInto(Result);
7647           return CallScope.destroy();
7648         } else {
7649           return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7650         }
7651       }
7652     } else
7653       return Error(E);
7654 
7655     // Evaluate the arguments now if we've not already done so.
7656     if (!Call) {
7657       Call = Info.CurrentCall->createCall(FD);
7658       if (!EvaluateArgs(Args, Call, Info, FD))
7659         return false;
7660     }
7661 
7662     SmallVector<QualType, 4> CovariantAdjustmentPath;
7663     if (This) {
7664       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7665       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7666         // Perform virtual dispatch, if necessary.
7667         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7668                                    CovariantAdjustmentPath);
7669         if (!FD)
7670           return false;
7671       } else {
7672         // Check that the 'this' pointer points to an object of the right type.
7673         // FIXME: If this is an assignment operator call, we may need to change
7674         // the active union member before we check this.
7675         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7676           return false;
7677       }
7678     }
7679 
7680     // Destructor calls are different enough that they have their own codepath.
7681     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7682       assert(This && "no 'this' pointer for destructor call");
7683       return HandleDestruction(Info, E, *This,
7684                                Info.Ctx.getRecordType(DD->getParent())) &&
7685              CallScope.destroy();
7686     }
7687 
7688     const FunctionDecl *Definition = nullptr;
7689     Stmt *Body = FD->getBody(Definition);
7690 
7691     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7692         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
7693                             Body, Info, Result, ResultSlot))
7694       return false;
7695 
7696     if (!CovariantAdjustmentPath.empty() &&
7697         !HandleCovariantReturnAdjustment(Info, E, Result,
7698                                          CovariantAdjustmentPath))
7699       return false;
7700 
7701     return CallScope.destroy();
7702   }
7703 
7704   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7705     return StmtVisitorTy::Visit(E->getInitializer());
7706   }
7707   bool VisitInitListExpr(const InitListExpr *E) {
7708     if (E->getNumInits() == 0)
7709       return DerivedZeroInitialization(E);
7710     if (E->getNumInits() == 1)
7711       return StmtVisitorTy::Visit(E->getInit(0));
7712     return Error(E);
7713   }
7714   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7715     return DerivedZeroInitialization(E);
7716   }
7717   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7718     return DerivedZeroInitialization(E);
7719   }
7720   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7721     return DerivedZeroInitialization(E);
7722   }
7723 
7724   /// A member expression where the object is a prvalue is itself a prvalue.
7725   bool VisitMemberExpr(const MemberExpr *E) {
7726     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7727            "missing temporary materialization conversion");
7728     assert(!E->isArrow() && "missing call to bound member function?");
7729 
7730     APValue Val;
7731     if (!Evaluate(Val, Info, E->getBase()))
7732       return false;
7733 
7734     QualType BaseTy = E->getBase()->getType();
7735 
7736     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7737     if (!FD) return Error(E);
7738     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7739     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7740            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7741 
7742     // Note: there is no lvalue base here. But this case should only ever
7743     // happen in C or in C++98, where we cannot be evaluating a constexpr
7744     // constructor, which is the only case the base matters.
7745     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7746     SubobjectDesignator Designator(BaseTy);
7747     Designator.addDeclUnchecked(FD);
7748 
7749     APValue Result;
7750     return extractSubobject(Info, E, Obj, Designator, Result) &&
7751            DerivedSuccess(Result, E);
7752   }
7753 
7754   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7755     APValue Val;
7756     if (!Evaluate(Val, Info, E->getBase()))
7757       return false;
7758 
7759     if (Val.isVector()) {
7760       SmallVector<uint32_t, 4> Indices;
7761       E->getEncodedElementAccess(Indices);
7762       if (Indices.size() == 1) {
7763         // Return scalar.
7764         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7765       } else {
7766         // Construct new APValue vector.
7767         SmallVector<APValue, 4> Elts;
7768         for (unsigned I = 0; I < Indices.size(); ++I) {
7769           Elts.push_back(Val.getVectorElt(Indices[I]));
7770         }
7771         APValue VecResult(Elts.data(), Indices.size());
7772         return DerivedSuccess(VecResult, E);
7773       }
7774     }
7775 
7776     return false;
7777   }
7778 
7779   bool VisitCastExpr(const CastExpr *E) {
7780     switch (E->getCastKind()) {
7781     default:
7782       break;
7783 
7784     case CK_AtomicToNonAtomic: {
7785       APValue AtomicVal;
7786       // This does not need to be done in place even for class/array types:
7787       // atomic-to-non-atomic conversion implies copying the object
7788       // representation.
7789       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7790         return false;
7791       return DerivedSuccess(AtomicVal, E);
7792     }
7793 
7794     case CK_NoOp:
7795     case CK_UserDefinedConversion:
7796       return StmtVisitorTy::Visit(E->getSubExpr());
7797 
7798     case CK_LValueToRValue: {
7799       LValue LVal;
7800       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7801         return false;
7802       APValue RVal;
7803       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7804       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7805                                           LVal, RVal))
7806         return false;
7807       return DerivedSuccess(RVal, E);
7808     }
7809     case CK_LValueToRValueBitCast: {
7810       APValue DestValue, SourceValue;
7811       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7812         return false;
7813       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7814         return false;
7815       return DerivedSuccess(DestValue, E);
7816     }
7817 
7818     case CK_AddressSpaceConversion: {
7819       APValue Value;
7820       if (!Evaluate(Value, Info, E->getSubExpr()))
7821         return false;
7822       return DerivedSuccess(Value, E);
7823     }
7824     }
7825 
7826     return Error(E);
7827   }
7828 
7829   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7830     return VisitUnaryPostIncDec(UO);
7831   }
7832   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7833     return VisitUnaryPostIncDec(UO);
7834   }
7835   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7836     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7837       return Error(UO);
7838 
7839     LValue LVal;
7840     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7841       return false;
7842     APValue RVal;
7843     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7844                       UO->isIncrementOp(), &RVal))
7845       return false;
7846     return DerivedSuccess(RVal, UO);
7847   }
7848 
7849   bool VisitStmtExpr(const StmtExpr *E) {
7850     // We will have checked the full-expressions inside the statement expression
7851     // when they were completed, and don't need to check them again now.
7852     if (Info.checkingForUndefinedBehavior())
7853       return Error(E);
7854 
7855     const CompoundStmt *CS = E->getSubStmt();
7856     if (CS->body_empty())
7857       return true;
7858 
7859     BlockScopeRAII Scope(Info);
7860     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7861                                            BE = CS->body_end();
7862          /**/; ++BI) {
7863       if (BI + 1 == BE) {
7864         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7865         if (!FinalExpr) {
7866           Info.FFDiag((*BI)->getBeginLoc(),
7867                       diag::note_constexpr_stmt_expr_unsupported);
7868           return false;
7869         }
7870         return this->Visit(FinalExpr) && Scope.destroy();
7871       }
7872 
7873       APValue ReturnValue;
7874       StmtResult Result = { ReturnValue, nullptr };
7875       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7876       if (ESR != ESR_Succeeded) {
7877         // FIXME: If the statement-expression terminated due to 'return',
7878         // 'break', or 'continue', it would be nice to propagate that to
7879         // the outer statement evaluation rather than bailing out.
7880         if (ESR != ESR_Failed)
7881           Info.FFDiag((*BI)->getBeginLoc(),
7882                       diag::note_constexpr_stmt_expr_unsupported);
7883         return false;
7884       }
7885     }
7886 
7887     llvm_unreachable("Return from function from the loop above.");
7888   }
7889 
7890   /// Visit a value which is evaluated, but whose value is ignored.
7891   void VisitIgnoredValue(const Expr *E) {
7892     EvaluateIgnoredValue(Info, E);
7893   }
7894 
7895   /// Potentially visit a MemberExpr's base expression.
7896   void VisitIgnoredBaseExpression(const Expr *E) {
7897     // While MSVC doesn't evaluate the base expression, it does diagnose the
7898     // presence of side-effecting behavior.
7899     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7900       return;
7901     VisitIgnoredValue(E);
7902   }
7903 };
7904 
7905 } // namespace
7906 
7907 //===----------------------------------------------------------------------===//
7908 // Common base class for lvalue and temporary evaluation.
7909 //===----------------------------------------------------------------------===//
7910 namespace {
7911 template<class Derived>
7912 class LValueExprEvaluatorBase
7913   : public ExprEvaluatorBase<Derived> {
7914 protected:
7915   LValue &Result;
7916   bool InvalidBaseOK;
7917   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7918   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7919 
7920   bool Success(APValue::LValueBase B) {
7921     Result.set(B);
7922     return true;
7923   }
7924 
7925   bool evaluatePointer(const Expr *E, LValue &Result) {
7926     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7927   }
7928 
7929 public:
7930   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7931       : ExprEvaluatorBaseTy(Info), Result(Result),
7932         InvalidBaseOK(InvalidBaseOK) {}
7933 
7934   bool Success(const APValue &V, const Expr *E) {
7935     Result.setFrom(this->Info.Ctx, V);
7936     return true;
7937   }
7938 
7939   bool VisitMemberExpr(const MemberExpr *E) {
7940     // Handle non-static data members.
7941     QualType BaseTy;
7942     bool EvalOK;
7943     if (E->isArrow()) {
7944       EvalOK = evaluatePointer(E->getBase(), Result);
7945       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
7946     } else if (E->getBase()->isRValue()) {
7947       assert(E->getBase()->getType()->isRecordType());
7948       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
7949       BaseTy = E->getBase()->getType();
7950     } else {
7951       EvalOK = this->Visit(E->getBase());
7952       BaseTy = E->getBase()->getType();
7953     }
7954     if (!EvalOK) {
7955       if (!InvalidBaseOK)
7956         return false;
7957       Result.setInvalid(E);
7958       return true;
7959     }
7960 
7961     const ValueDecl *MD = E->getMemberDecl();
7962     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
7963       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7964              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7965       (void)BaseTy;
7966       if (!HandleLValueMember(this->Info, E, Result, FD))
7967         return false;
7968     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
7969       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
7970         return false;
7971     } else
7972       return this->Error(E);
7973 
7974     if (MD->getType()->isReferenceType()) {
7975       APValue RefValue;
7976       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
7977                                           RefValue))
7978         return false;
7979       return Success(RefValue, E);
7980     }
7981     return true;
7982   }
7983 
7984   bool VisitBinaryOperator(const BinaryOperator *E) {
7985     switch (E->getOpcode()) {
7986     default:
7987       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7988 
7989     case BO_PtrMemD:
7990     case BO_PtrMemI:
7991       return HandleMemberPointerAccess(this->Info, E, Result);
7992     }
7993   }
7994 
7995   bool VisitCastExpr(const CastExpr *E) {
7996     switch (E->getCastKind()) {
7997     default:
7998       return ExprEvaluatorBaseTy::VisitCastExpr(E);
7999 
8000     case CK_DerivedToBase:
8001     case CK_UncheckedDerivedToBase:
8002       if (!this->Visit(E->getSubExpr()))
8003         return false;
8004 
8005       // Now figure out the necessary offset to add to the base LV to get from
8006       // the derived class to the base class.
8007       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8008                                   Result);
8009     }
8010   }
8011 };
8012 }
8013 
8014 //===----------------------------------------------------------------------===//
8015 // LValue Evaluation
8016 //
8017 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8018 // function designators (in C), decl references to void objects (in C), and
8019 // temporaries (if building with -Wno-address-of-temporary).
8020 //
8021 // LValue evaluation produces values comprising a base expression of one of the
8022 // following types:
8023 // - Declarations
8024 //  * VarDecl
8025 //  * FunctionDecl
8026 // - Literals
8027 //  * CompoundLiteralExpr in C (and in global scope in C++)
8028 //  * StringLiteral
8029 //  * PredefinedExpr
8030 //  * ObjCStringLiteralExpr
8031 //  * ObjCEncodeExpr
8032 //  * AddrLabelExpr
8033 //  * BlockExpr
8034 //  * CallExpr for a MakeStringConstant builtin
8035 // - typeid(T) expressions, as TypeInfoLValues
8036 // - Locals and temporaries
8037 //  * MaterializeTemporaryExpr
8038 //  * Any Expr, with a CallIndex indicating the function in which the temporary
8039 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
8040 //    from the AST (FIXME).
8041 //  * A MaterializeTemporaryExpr that has static storage duration, with no
8042 //    CallIndex, for a lifetime-extended temporary.
8043 //  * The ConstantExpr that is currently being evaluated during evaluation of an
8044 //    immediate invocation.
8045 // plus an offset in bytes.
8046 //===----------------------------------------------------------------------===//
8047 namespace {
8048 class LValueExprEvaluator
8049   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8050 public:
8051   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8052     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8053 
8054   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8055   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8056 
8057   bool VisitDeclRefExpr(const DeclRefExpr *E);
8058   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8059   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8060   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8061   bool VisitMemberExpr(const MemberExpr *E);
8062   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
8063   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8064   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8065   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8066   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8067   bool VisitUnaryDeref(const UnaryOperator *E);
8068   bool VisitUnaryReal(const UnaryOperator *E);
8069   bool VisitUnaryImag(const UnaryOperator *E);
8070   bool VisitUnaryPreInc(const UnaryOperator *UO) {
8071     return VisitUnaryPreIncDec(UO);
8072   }
8073   bool VisitUnaryPreDec(const UnaryOperator *UO) {
8074     return VisitUnaryPreIncDec(UO);
8075   }
8076   bool VisitBinAssign(const BinaryOperator *BO);
8077   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8078 
8079   bool VisitCastExpr(const CastExpr *E) {
8080     switch (E->getCastKind()) {
8081     default:
8082       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8083 
8084     case CK_LValueBitCast:
8085       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8086       if (!Visit(E->getSubExpr()))
8087         return false;
8088       Result.Designator.setInvalid();
8089       return true;
8090 
8091     case CK_BaseToDerived:
8092       if (!Visit(E->getSubExpr()))
8093         return false;
8094       return HandleBaseToDerivedCast(Info, E, Result);
8095 
8096     case CK_Dynamic:
8097       if (!Visit(E->getSubExpr()))
8098         return false;
8099       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8100     }
8101   }
8102 };
8103 } // end anonymous namespace
8104 
8105 /// Evaluate an expression as an lvalue. This can be legitimately called on
8106 /// expressions which are not glvalues, in three cases:
8107 ///  * function designators in C, and
8108 ///  * "extern void" objects
8109 ///  * @selector() expressions in Objective-C
8110 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8111                            bool InvalidBaseOK) {
8112   assert(!E->isValueDependent());
8113   assert(E->isGLValue() || E->getType()->isFunctionType() ||
8114          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
8115   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8116 }
8117 
8118 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8119   const NamedDecl *D = E->getDecl();
8120   if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D))
8121     return Success(cast<ValueDecl>(D));
8122   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8123     return VisitVarDecl(E, VD);
8124   if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8125     return Visit(BD->getBinding());
8126   return Error(E);
8127 }
8128 
8129 
8130 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8131 
8132   // If we are within a lambda's call operator, check whether the 'VD' referred
8133   // to within 'E' actually represents a lambda-capture that maps to a
8134   // data-member/field within the closure object, and if so, evaluate to the
8135   // field or what the field refers to.
8136   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8137       isa<DeclRefExpr>(E) &&
8138       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8139     // We don't always have a complete capture-map when checking or inferring if
8140     // the function call operator meets the requirements of a constexpr function
8141     // - but we don't need to evaluate the captures to determine constexprness
8142     // (dcl.constexpr C++17).
8143     if (Info.checkingPotentialConstantExpression())
8144       return false;
8145 
8146     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8147       // Start with 'Result' referring to the complete closure object...
8148       Result = *Info.CurrentCall->This;
8149       // ... then update it to refer to the field of the closure object
8150       // that represents the capture.
8151       if (!HandleLValueMember(Info, E, Result, FD))
8152         return false;
8153       // And if the field is of reference type, update 'Result' to refer to what
8154       // the field refers to.
8155       if (FD->getType()->isReferenceType()) {
8156         APValue RVal;
8157         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8158                                             RVal))
8159           return false;
8160         Result.setFrom(Info.Ctx, RVal);
8161       }
8162       return true;
8163     }
8164   }
8165 
8166   CallStackFrame *Frame = nullptr;
8167   unsigned Version = 0;
8168   if (VD->hasLocalStorage()) {
8169     // Only if a local variable was declared in the function currently being
8170     // evaluated, do we expect to be able to find its value in the current
8171     // frame. (Otherwise it was likely declared in an enclosing context and
8172     // could either have a valid evaluatable value (for e.g. a constexpr
8173     // variable) or be ill-formed (and trigger an appropriate evaluation
8174     // diagnostic)).
8175     CallStackFrame *CurrFrame = Info.CurrentCall;
8176     if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8177       // Function parameters are stored in some caller's frame. (Usually the
8178       // immediate caller, but for an inherited constructor they may be more
8179       // distant.)
8180       if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8181         if (CurrFrame->Arguments) {
8182           VD = CurrFrame->Arguments.getOrigParam(PVD);
8183           Frame =
8184               Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8185           Version = CurrFrame->Arguments.Version;
8186         }
8187       } else {
8188         Frame = CurrFrame;
8189         Version = CurrFrame->getCurrentTemporaryVersion(VD);
8190       }
8191     }
8192   }
8193 
8194   if (!VD->getType()->isReferenceType()) {
8195     if (Frame) {
8196       Result.set({VD, Frame->Index, Version});
8197       return true;
8198     }
8199     return Success(VD);
8200   }
8201 
8202   if (!Info.getLangOpts().CPlusPlus11) {
8203     Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8204         << VD << VD->getType();
8205     Info.Note(VD->getLocation(), diag::note_declared_at);
8206   }
8207 
8208   APValue *V;
8209   if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8210     return false;
8211   if (!V->hasValue()) {
8212     // FIXME: Is it possible for V to be indeterminate here? If so, we should
8213     // adjust the diagnostic to say that.
8214     if (!Info.checkingPotentialConstantExpression())
8215       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8216     return false;
8217   }
8218   return Success(*V, E);
8219 }
8220 
8221 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8222     const MaterializeTemporaryExpr *E) {
8223   // Walk through the expression to find the materialized temporary itself.
8224   SmallVector<const Expr *, 2> CommaLHSs;
8225   SmallVector<SubobjectAdjustment, 2> Adjustments;
8226   const Expr *Inner =
8227       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8228 
8229   // If we passed any comma operators, evaluate their LHSs.
8230   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
8231     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
8232       return false;
8233 
8234   // A materialized temporary with static storage duration can appear within the
8235   // result of a constant expression evaluation, so we need to preserve its
8236   // value for use outside this evaluation.
8237   APValue *Value;
8238   if (E->getStorageDuration() == SD_Static) {
8239     // FIXME: What about SD_Thread?
8240     Value = E->getOrCreateValue(true);
8241     *Value = APValue();
8242     Result.set(E);
8243   } else {
8244     Value = &Info.CurrentCall->createTemporary(
8245         E, E->getType(),
8246         E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8247                                                      : ScopeKind::Block,
8248         Result);
8249   }
8250 
8251   QualType Type = Inner->getType();
8252 
8253   // Materialize the temporary itself.
8254   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8255     *Value = APValue();
8256     return false;
8257   }
8258 
8259   // Adjust our lvalue to refer to the desired subobject.
8260   for (unsigned I = Adjustments.size(); I != 0; /**/) {
8261     --I;
8262     switch (Adjustments[I].Kind) {
8263     case SubobjectAdjustment::DerivedToBaseAdjustment:
8264       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8265                                 Type, Result))
8266         return false;
8267       Type = Adjustments[I].DerivedToBase.BasePath->getType();
8268       break;
8269 
8270     case SubobjectAdjustment::FieldAdjustment:
8271       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8272         return false;
8273       Type = Adjustments[I].Field->getType();
8274       break;
8275 
8276     case SubobjectAdjustment::MemberPointerAdjustment:
8277       if (!HandleMemberPointerAccess(this->Info, Type, Result,
8278                                      Adjustments[I].Ptr.RHS))
8279         return false;
8280       Type = Adjustments[I].Ptr.MPT->getPointeeType();
8281       break;
8282     }
8283   }
8284 
8285   return true;
8286 }
8287 
8288 bool
8289 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8290   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8291          "lvalue compound literal in c++?");
8292   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8293   // only see this when folding in C, so there's no standard to follow here.
8294   return Success(E);
8295 }
8296 
8297 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8298   TypeInfoLValue TypeInfo;
8299 
8300   if (!E->isPotentiallyEvaluated()) {
8301     if (E->isTypeOperand())
8302       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8303     else
8304       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8305   } else {
8306     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8307       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8308         << E->getExprOperand()->getType()
8309         << E->getExprOperand()->getSourceRange();
8310     }
8311 
8312     if (!Visit(E->getExprOperand()))
8313       return false;
8314 
8315     Optional<DynamicType> DynType =
8316         ComputeDynamicType(Info, E, Result, AK_TypeId);
8317     if (!DynType)
8318       return false;
8319 
8320     TypeInfo =
8321         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8322   }
8323 
8324   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8325 }
8326 
8327 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8328   return Success(E->getGuidDecl());
8329 }
8330 
8331 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8332   // Handle static data members.
8333   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8334     VisitIgnoredBaseExpression(E->getBase());
8335     return VisitVarDecl(E, VD);
8336   }
8337 
8338   // Handle static member functions.
8339   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8340     if (MD->isStatic()) {
8341       VisitIgnoredBaseExpression(E->getBase());
8342       return Success(MD);
8343     }
8344   }
8345 
8346   // Handle non-static data members.
8347   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8348 }
8349 
8350 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8351   // FIXME: Deal with vectors as array subscript bases.
8352   if (E->getBase()->getType()->isVectorType())
8353     return Error(E);
8354 
8355   APSInt Index;
8356   bool Success = true;
8357 
8358   // C++17's rules require us to evaluate the LHS first, regardless of which
8359   // side is the base.
8360   for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8361     if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8362                                 : !EvaluateInteger(SubExpr, Index, Info)) {
8363       if (!Info.noteFailure())
8364         return false;
8365       Success = false;
8366     }
8367   }
8368 
8369   return Success &&
8370          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8371 }
8372 
8373 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8374   return evaluatePointer(E->getSubExpr(), Result);
8375 }
8376 
8377 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8378   if (!Visit(E->getSubExpr()))
8379     return false;
8380   // __real is a no-op on scalar lvalues.
8381   if (E->getSubExpr()->getType()->isAnyComplexType())
8382     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8383   return true;
8384 }
8385 
8386 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8387   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8388          "lvalue __imag__ on scalar?");
8389   if (!Visit(E->getSubExpr()))
8390     return false;
8391   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8392   return true;
8393 }
8394 
8395 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8396   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8397     return Error(UO);
8398 
8399   if (!this->Visit(UO->getSubExpr()))
8400     return false;
8401 
8402   return handleIncDec(
8403       this->Info, UO, Result, UO->getSubExpr()->getType(),
8404       UO->isIncrementOp(), nullptr);
8405 }
8406 
8407 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8408     const CompoundAssignOperator *CAO) {
8409   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8410     return Error(CAO);
8411 
8412   bool Success = true;
8413 
8414   // C++17 onwards require that we evaluate the RHS first.
8415   APValue RHS;
8416   if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8417     if (!Info.noteFailure())
8418       return false;
8419     Success = false;
8420   }
8421 
8422   // The overall lvalue result is the result of evaluating the LHS.
8423   if (!this->Visit(CAO->getLHS()) || !Success)
8424     return false;
8425 
8426   return handleCompoundAssignment(
8427       this->Info, CAO,
8428       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8429       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8430 }
8431 
8432 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8433   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8434     return Error(E);
8435 
8436   bool Success = true;
8437 
8438   // C++17 onwards require that we evaluate the RHS first.
8439   APValue NewVal;
8440   if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8441     if (!Info.noteFailure())
8442       return false;
8443     Success = false;
8444   }
8445 
8446   if (!this->Visit(E->getLHS()) || !Success)
8447     return false;
8448 
8449   if (Info.getLangOpts().CPlusPlus20 &&
8450       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8451     return false;
8452 
8453   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8454                           NewVal);
8455 }
8456 
8457 //===----------------------------------------------------------------------===//
8458 // Pointer Evaluation
8459 //===----------------------------------------------------------------------===//
8460 
8461 /// Attempts to compute the number of bytes available at the pointer
8462 /// returned by a function with the alloc_size attribute. Returns true if we
8463 /// were successful. Places an unsigned number into `Result`.
8464 ///
8465 /// This expects the given CallExpr to be a call to a function with an
8466 /// alloc_size attribute.
8467 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8468                                             const CallExpr *Call,
8469                                             llvm::APInt &Result) {
8470   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8471 
8472   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8473   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8474   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8475   if (Call->getNumArgs() <= SizeArgNo)
8476     return false;
8477 
8478   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8479     Expr::EvalResult ExprResult;
8480     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8481       return false;
8482     Into = ExprResult.Val.getInt();
8483     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8484       return false;
8485     Into = Into.zextOrSelf(BitsInSizeT);
8486     return true;
8487   };
8488 
8489   APSInt SizeOfElem;
8490   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8491     return false;
8492 
8493   if (!AllocSize->getNumElemsParam().isValid()) {
8494     Result = std::move(SizeOfElem);
8495     return true;
8496   }
8497 
8498   APSInt NumberOfElems;
8499   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8500   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8501     return false;
8502 
8503   bool Overflow;
8504   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8505   if (Overflow)
8506     return false;
8507 
8508   Result = std::move(BytesAvailable);
8509   return true;
8510 }
8511 
8512 /// Convenience function. LVal's base must be a call to an alloc_size
8513 /// function.
8514 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8515                                             const LValue &LVal,
8516                                             llvm::APInt &Result) {
8517   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8518          "Can't get the size of a non alloc_size function");
8519   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8520   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8521   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8522 }
8523 
8524 /// Attempts to evaluate the given LValueBase as the result of a call to
8525 /// a function with the alloc_size attribute. If it was possible to do so, this
8526 /// function will return true, make Result's Base point to said function call,
8527 /// and mark Result's Base as invalid.
8528 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8529                                       LValue &Result) {
8530   if (Base.isNull())
8531     return false;
8532 
8533   // Because we do no form of static analysis, we only support const variables.
8534   //
8535   // Additionally, we can't support parameters, nor can we support static
8536   // variables (in the latter case, use-before-assign isn't UB; in the former,
8537   // we have no clue what they'll be assigned to).
8538   const auto *VD =
8539       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8540   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8541     return false;
8542 
8543   const Expr *Init = VD->getAnyInitializer();
8544   if (!Init)
8545     return false;
8546 
8547   const Expr *E = Init->IgnoreParens();
8548   if (!tryUnwrapAllocSizeCall(E))
8549     return false;
8550 
8551   // Store E instead of E unwrapped so that the type of the LValue's base is
8552   // what the user wanted.
8553   Result.setInvalid(E);
8554 
8555   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8556   Result.addUnsizedArray(Info, E, Pointee);
8557   return true;
8558 }
8559 
8560 namespace {
8561 class PointerExprEvaluator
8562   : public ExprEvaluatorBase<PointerExprEvaluator> {
8563   LValue &Result;
8564   bool InvalidBaseOK;
8565 
8566   bool Success(const Expr *E) {
8567     Result.set(E);
8568     return true;
8569   }
8570 
8571   bool evaluateLValue(const Expr *E, LValue &Result) {
8572     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8573   }
8574 
8575   bool evaluatePointer(const Expr *E, LValue &Result) {
8576     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8577   }
8578 
8579   bool visitNonBuiltinCallExpr(const CallExpr *E);
8580 public:
8581 
8582   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8583       : ExprEvaluatorBaseTy(info), Result(Result),
8584         InvalidBaseOK(InvalidBaseOK) {}
8585 
8586   bool Success(const APValue &V, const Expr *E) {
8587     Result.setFrom(Info.Ctx, V);
8588     return true;
8589   }
8590   bool ZeroInitialization(const Expr *E) {
8591     Result.setNull(Info.Ctx, E->getType());
8592     return true;
8593   }
8594 
8595   bool VisitBinaryOperator(const BinaryOperator *E);
8596   bool VisitCastExpr(const CastExpr* E);
8597   bool VisitUnaryAddrOf(const UnaryOperator *E);
8598   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8599       { return Success(E); }
8600   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8601     if (E->isExpressibleAsConstantInitializer())
8602       return Success(E);
8603     if (Info.noteFailure())
8604       EvaluateIgnoredValue(Info, E->getSubExpr());
8605     return Error(E);
8606   }
8607   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8608       { return Success(E); }
8609   bool VisitCallExpr(const CallExpr *E);
8610   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8611   bool VisitBlockExpr(const BlockExpr *E) {
8612     if (!E->getBlockDecl()->hasCaptures())
8613       return Success(E);
8614     return Error(E);
8615   }
8616   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8617     // Can't look at 'this' when checking a potential constant expression.
8618     if (Info.checkingPotentialConstantExpression())
8619       return false;
8620     if (!Info.CurrentCall->This) {
8621       if (Info.getLangOpts().CPlusPlus11)
8622         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8623       else
8624         Info.FFDiag(E);
8625       return false;
8626     }
8627     Result = *Info.CurrentCall->This;
8628     // If we are inside a lambda's call operator, the 'this' expression refers
8629     // to the enclosing '*this' object (either by value or reference) which is
8630     // either copied into the closure object's field that represents the '*this'
8631     // or refers to '*this'.
8632     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8633       // Ensure we actually have captured 'this'. (an error will have
8634       // been previously reported if not).
8635       if (!Info.CurrentCall->LambdaThisCaptureField)
8636         return false;
8637 
8638       // Update 'Result' to refer to the data member/field of the closure object
8639       // that represents the '*this' capture.
8640       if (!HandleLValueMember(Info, E, Result,
8641                              Info.CurrentCall->LambdaThisCaptureField))
8642         return false;
8643       // If we captured '*this' by reference, replace the field with its referent.
8644       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8645               ->isPointerType()) {
8646         APValue RVal;
8647         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8648                                             RVal))
8649           return false;
8650 
8651         Result.setFrom(Info.Ctx, RVal);
8652       }
8653     }
8654     return true;
8655   }
8656 
8657   bool VisitCXXNewExpr(const CXXNewExpr *E);
8658 
8659   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8660     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
8661     APValue LValResult = E->EvaluateInContext(
8662         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8663     Result.setFrom(Info.Ctx, LValResult);
8664     return true;
8665   }
8666 
8667   // FIXME: Missing: @protocol, @selector
8668 };
8669 } // end anonymous namespace
8670 
8671 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8672                             bool InvalidBaseOK) {
8673   assert(!E->isValueDependent());
8674   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
8675   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8676 }
8677 
8678 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8679   if (E->getOpcode() != BO_Add &&
8680       E->getOpcode() != BO_Sub)
8681     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8682 
8683   const Expr *PExp = E->getLHS();
8684   const Expr *IExp = E->getRHS();
8685   if (IExp->getType()->isPointerType())
8686     std::swap(PExp, IExp);
8687 
8688   bool EvalPtrOK = evaluatePointer(PExp, Result);
8689   if (!EvalPtrOK && !Info.noteFailure())
8690     return false;
8691 
8692   llvm::APSInt Offset;
8693   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8694     return false;
8695 
8696   if (E->getOpcode() == BO_Sub)
8697     negateAsSigned(Offset);
8698 
8699   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8700   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8701 }
8702 
8703 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8704   return evaluateLValue(E->getSubExpr(), Result);
8705 }
8706 
8707 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8708   const Expr *SubExpr = E->getSubExpr();
8709 
8710   switch (E->getCastKind()) {
8711   default:
8712     break;
8713   case CK_BitCast:
8714   case CK_CPointerToObjCPointerCast:
8715   case CK_BlockPointerToObjCPointerCast:
8716   case CK_AnyPointerToBlockPointerCast:
8717   case CK_AddressSpaceConversion:
8718     if (!Visit(SubExpr))
8719       return false;
8720     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8721     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8722     // also static_casts, but we disallow them as a resolution to DR1312.
8723     if (!E->getType()->isVoidPointerType()) {
8724       if (!Result.InvalidBase && !Result.Designator.Invalid &&
8725           !Result.IsNullPtr &&
8726           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8727                                           E->getType()->getPointeeType()) &&
8728           Info.getStdAllocatorCaller("allocate")) {
8729         // Inside a call to std::allocator::allocate and friends, we permit
8730         // casting from void* back to cv1 T* for a pointer that points to a
8731         // cv2 T.
8732       } else {
8733         Result.Designator.setInvalid();
8734         if (SubExpr->getType()->isVoidPointerType())
8735           CCEDiag(E, diag::note_constexpr_invalid_cast)
8736             << 3 << SubExpr->getType();
8737         else
8738           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8739       }
8740     }
8741     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8742       ZeroInitialization(E);
8743     return true;
8744 
8745   case CK_DerivedToBase:
8746   case CK_UncheckedDerivedToBase:
8747     if (!evaluatePointer(E->getSubExpr(), Result))
8748       return false;
8749     if (!Result.Base && Result.Offset.isZero())
8750       return true;
8751 
8752     // Now figure out the necessary offset to add to the base LV to get from
8753     // the derived class to the base class.
8754     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8755                                   castAs<PointerType>()->getPointeeType(),
8756                                 Result);
8757 
8758   case CK_BaseToDerived:
8759     if (!Visit(E->getSubExpr()))
8760       return false;
8761     if (!Result.Base && Result.Offset.isZero())
8762       return true;
8763     return HandleBaseToDerivedCast(Info, E, Result);
8764 
8765   case CK_Dynamic:
8766     if (!Visit(E->getSubExpr()))
8767       return false;
8768     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8769 
8770   case CK_NullToPointer:
8771     VisitIgnoredValue(E->getSubExpr());
8772     return ZeroInitialization(E);
8773 
8774   case CK_IntegralToPointer: {
8775     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8776 
8777     APValue Value;
8778     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8779       break;
8780 
8781     if (Value.isInt()) {
8782       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8783       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8784       Result.Base = (Expr*)nullptr;
8785       Result.InvalidBase = false;
8786       Result.Offset = CharUnits::fromQuantity(N);
8787       Result.Designator.setInvalid();
8788       Result.IsNullPtr = false;
8789       return true;
8790     } else {
8791       // Cast is of an lvalue, no need to change value.
8792       Result.setFrom(Info.Ctx, Value);
8793       return true;
8794     }
8795   }
8796 
8797   case CK_ArrayToPointerDecay: {
8798     if (SubExpr->isGLValue()) {
8799       if (!evaluateLValue(SubExpr, Result))
8800         return false;
8801     } else {
8802       APValue &Value = Info.CurrentCall->createTemporary(
8803           SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
8804       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8805         return false;
8806     }
8807     // The result is a pointer to the first element of the array.
8808     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8809     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8810       Result.addArray(Info, E, CAT);
8811     else
8812       Result.addUnsizedArray(Info, E, AT->getElementType());
8813     return true;
8814   }
8815 
8816   case CK_FunctionToPointerDecay:
8817     return evaluateLValue(SubExpr, Result);
8818 
8819   case CK_LValueToRValue: {
8820     LValue LVal;
8821     if (!evaluateLValue(E->getSubExpr(), LVal))
8822       return false;
8823 
8824     APValue RVal;
8825     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8826     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8827                                         LVal, RVal))
8828       return InvalidBaseOK &&
8829              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8830     return Success(RVal, E);
8831   }
8832   }
8833 
8834   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8835 }
8836 
8837 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8838                                 UnaryExprOrTypeTrait ExprKind) {
8839   // C++ [expr.alignof]p3:
8840   //     When alignof is applied to a reference type, the result is the
8841   //     alignment of the referenced type.
8842   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8843     T = Ref->getPointeeType();
8844 
8845   if (T.getQualifiers().hasUnaligned())
8846     return CharUnits::One();
8847 
8848   const bool AlignOfReturnsPreferred =
8849       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8850 
8851   // __alignof is defined to return the preferred alignment.
8852   // Before 8, clang returned the preferred alignment for alignof and _Alignof
8853   // as well.
8854   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8855     return Info.Ctx.toCharUnitsFromBits(
8856       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8857   // alignof and _Alignof are defined to return the ABI alignment.
8858   else if (ExprKind == UETT_AlignOf)
8859     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8860   else
8861     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8862 }
8863 
8864 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8865                                 UnaryExprOrTypeTrait ExprKind) {
8866   E = E->IgnoreParens();
8867 
8868   // The kinds of expressions that we have special-case logic here for
8869   // should be kept up to date with the special checks for those
8870   // expressions in Sema.
8871 
8872   // alignof decl is always accepted, even if it doesn't make sense: we default
8873   // to 1 in those cases.
8874   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8875     return Info.Ctx.getDeclAlign(DRE->getDecl(),
8876                                  /*RefAsPointee*/true);
8877 
8878   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8879     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8880                                  /*RefAsPointee*/true);
8881 
8882   return GetAlignOfType(Info, E->getType(), ExprKind);
8883 }
8884 
8885 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
8886   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
8887     return Info.Ctx.getDeclAlign(VD);
8888   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
8889     return GetAlignOfExpr(Info, E, UETT_AlignOf);
8890   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
8891 }
8892 
8893 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
8894 /// __builtin_is_aligned and __builtin_assume_aligned.
8895 static bool getAlignmentArgument(const Expr *E, QualType ForType,
8896                                  EvalInfo &Info, APSInt &Alignment) {
8897   if (!EvaluateInteger(E, Alignment, Info))
8898     return false;
8899   if (Alignment < 0 || !Alignment.isPowerOf2()) {
8900     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
8901     return false;
8902   }
8903   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
8904   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
8905   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
8906     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
8907         << MaxValue << ForType << Alignment;
8908     return false;
8909   }
8910   // Ensure both alignment and source value have the same bit width so that we
8911   // don't assert when computing the resulting value.
8912   APSInt ExtAlignment =
8913       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
8914   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
8915          "Alignment should not be changed by ext/trunc");
8916   Alignment = ExtAlignment;
8917   assert(Alignment.getBitWidth() == SrcWidth);
8918   return true;
8919 }
8920 
8921 // To be clear: this happily visits unsupported builtins. Better name welcomed.
8922 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8923   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8924     return true;
8925 
8926   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
8927     return false;
8928 
8929   Result.setInvalid(E);
8930   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
8931   Result.addUnsizedArray(Info, E, PointeeTy);
8932   return true;
8933 }
8934 
8935 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
8936   if (IsStringLiteralCall(E))
8937     return Success(E);
8938 
8939   if (unsigned BuiltinOp = E->getBuiltinCallee())
8940     return VisitBuiltinCallExpr(E, BuiltinOp);
8941 
8942   return visitNonBuiltinCallExpr(E);
8943 }
8944 
8945 // Determine if T is a character type for which we guarantee that
8946 // sizeof(T) == 1.
8947 static bool isOneByteCharacterType(QualType T) {
8948   return T->isCharType() || T->isChar8Type();
8949 }
8950 
8951 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8952                                                 unsigned BuiltinOp) {
8953   switch (BuiltinOp) {
8954   case Builtin::BI__builtin_addressof:
8955     return evaluateLValue(E->getArg(0), Result);
8956   case Builtin::BI__builtin_assume_aligned: {
8957     // We need to be very careful here because: if the pointer does not have the
8958     // asserted alignment, then the behavior is undefined, and undefined
8959     // behavior is non-constant.
8960     if (!evaluatePointer(E->getArg(0), Result))
8961       return false;
8962 
8963     LValue OffsetResult(Result);
8964     APSInt Alignment;
8965     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8966                               Alignment))
8967       return false;
8968     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
8969 
8970     if (E->getNumArgs() > 2) {
8971       APSInt Offset;
8972       if (!EvaluateInteger(E->getArg(2), Offset, Info))
8973         return false;
8974 
8975       int64_t AdditionalOffset = -Offset.getZExtValue();
8976       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
8977     }
8978 
8979     // If there is a base object, then it must have the correct alignment.
8980     if (OffsetResult.Base) {
8981       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
8982 
8983       if (BaseAlignment < Align) {
8984         Result.Designator.setInvalid();
8985         // FIXME: Add support to Diagnostic for long / long long.
8986         CCEDiag(E->getArg(0),
8987                 diag::note_constexpr_baa_insufficient_alignment) << 0
8988           << (unsigned)BaseAlignment.getQuantity()
8989           << (unsigned)Align.getQuantity();
8990         return false;
8991       }
8992     }
8993 
8994     // The offset must also have the correct alignment.
8995     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
8996       Result.Designator.setInvalid();
8997 
8998       (OffsetResult.Base
8999            ? CCEDiag(E->getArg(0),
9000                      diag::note_constexpr_baa_insufficient_alignment) << 1
9001            : CCEDiag(E->getArg(0),
9002                      diag::note_constexpr_baa_value_insufficient_alignment))
9003         << (int)OffsetResult.Offset.getQuantity()
9004         << (unsigned)Align.getQuantity();
9005       return false;
9006     }
9007 
9008     return true;
9009   }
9010   case Builtin::BI__builtin_align_up:
9011   case Builtin::BI__builtin_align_down: {
9012     if (!evaluatePointer(E->getArg(0), Result))
9013       return false;
9014     APSInt Alignment;
9015     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9016                               Alignment))
9017       return false;
9018     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9019     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9020     // For align_up/align_down, we can return the same value if the alignment
9021     // is known to be greater or equal to the requested value.
9022     if (PtrAlign.getQuantity() >= Alignment)
9023       return true;
9024 
9025     // The alignment could be greater than the minimum at run-time, so we cannot
9026     // infer much about the resulting pointer value. One case is possible:
9027     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9028     // can infer the correct index if the requested alignment is smaller than
9029     // the base alignment so we can perform the computation on the offset.
9030     if (BaseAlignment.getQuantity() >= Alignment) {
9031       assert(Alignment.getBitWidth() <= 64 &&
9032              "Cannot handle > 64-bit address-space");
9033       uint64_t Alignment64 = Alignment.getZExtValue();
9034       CharUnits NewOffset = CharUnits::fromQuantity(
9035           BuiltinOp == Builtin::BI__builtin_align_down
9036               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9037               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9038       Result.adjustOffset(NewOffset - Result.Offset);
9039       // TODO: diagnose out-of-bounds values/only allow for arrays?
9040       return true;
9041     }
9042     // Otherwise, we cannot constant-evaluate the result.
9043     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9044         << Alignment;
9045     return false;
9046   }
9047   case Builtin::BI__builtin_operator_new:
9048     return HandleOperatorNewCall(Info, E, Result);
9049   case Builtin::BI__builtin_launder:
9050     return evaluatePointer(E->getArg(0), Result);
9051   case Builtin::BIstrchr:
9052   case Builtin::BIwcschr:
9053   case Builtin::BImemchr:
9054   case Builtin::BIwmemchr:
9055     if (Info.getLangOpts().CPlusPlus11)
9056       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9057         << /*isConstexpr*/0 << /*isConstructor*/0
9058         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9059     else
9060       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9061     LLVM_FALLTHROUGH;
9062   case Builtin::BI__builtin_strchr:
9063   case Builtin::BI__builtin_wcschr:
9064   case Builtin::BI__builtin_memchr:
9065   case Builtin::BI__builtin_char_memchr:
9066   case Builtin::BI__builtin_wmemchr: {
9067     if (!Visit(E->getArg(0)))
9068       return false;
9069     APSInt Desired;
9070     if (!EvaluateInteger(E->getArg(1), Desired, Info))
9071       return false;
9072     uint64_t MaxLength = uint64_t(-1);
9073     if (BuiltinOp != Builtin::BIstrchr &&
9074         BuiltinOp != Builtin::BIwcschr &&
9075         BuiltinOp != Builtin::BI__builtin_strchr &&
9076         BuiltinOp != Builtin::BI__builtin_wcschr) {
9077       APSInt N;
9078       if (!EvaluateInteger(E->getArg(2), N, Info))
9079         return false;
9080       MaxLength = N.getExtValue();
9081     }
9082     // We cannot find the value if there are no candidates to match against.
9083     if (MaxLength == 0u)
9084       return ZeroInitialization(E);
9085     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9086         Result.Designator.Invalid)
9087       return false;
9088     QualType CharTy = Result.Designator.getType(Info.Ctx);
9089     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9090                      BuiltinOp == Builtin::BI__builtin_memchr;
9091     assert(IsRawByte ||
9092            Info.Ctx.hasSameUnqualifiedType(
9093                CharTy, E->getArg(0)->getType()->getPointeeType()));
9094     // Pointers to const void may point to objects of incomplete type.
9095     if (IsRawByte && CharTy->isIncompleteType()) {
9096       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9097       return false;
9098     }
9099     // Give up on byte-oriented matching against multibyte elements.
9100     // FIXME: We can compare the bytes in the correct order.
9101     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9102       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9103           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
9104           << CharTy;
9105       return false;
9106     }
9107     // Figure out what value we're actually looking for (after converting to
9108     // the corresponding unsigned type if necessary).
9109     uint64_t DesiredVal;
9110     bool StopAtNull = false;
9111     switch (BuiltinOp) {
9112     case Builtin::BIstrchr:
9113     case Builtin::BI__builtin_strchr:
9114       // strchr compares directly to the passed integer, and therefore
9115       // always fails if given an int that is not a char.
9116       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9117                                                   E->getArg(1)->getType(),
9118                                                   Desired),
9119                                Desired))
9120         return ZeroInitialization(E);
9121       StopAtNull = true;
9122       LLVM_FALLTHROUGH;
9123     case Builtin::BImemchr:
9124     case Builtin::BI__builtin_memchr:
9125     case Builtin::BI__builtin_char_memchr:
9126       // memchr compares by converting both sides to unsigned char. That's also
9127       // correct for strchr if we get this far (to cope with plain char being
9128       // unsigned in the strchr case).
9129       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9130       break;
9131 
9132     case Builtin::BIwcschr:
9133     case Builtin::BI__builtin_wcschr:
9134       StopAtNull = true;
9135       LLVM_FALLTHROUGH;
9136     case Builtin::BIwmemchr:
9137     case Builtin::BI__builtin_wmemchr:
9138       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9139       DesiredVal = Desired.getZExtValue();
9140       break;
9141     }
9142 
9143     for (; MaxLength; --MaxLength) {
9144       APValue Char;
9145       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9146           !Char.isInt())
9147         return false;
9148       if (Char.getInt().getZExtValue() == DesiredVal)
9149         return true;
9150       if (StopAtNull && !Char.getInt())
9151         break;
9152       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9153         return false;
9154     }
9155     // Not found: return nullptr.
9156     return ZeroInitialization(E);
9157   }
9158 
9159   case Builtin::BImemcpy:
9160   case Builtin::BImemmove:
9161   case Builtin::BIwmemcpy:
9162   case Builtin::BIwmemmove:
9163     if (Info.getLangOpts().CPlusPlus11)
9164       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9165         << /*isConstexpr*/0 << /*isConstructor*/0
9166         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9167     else
9168       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9169     LLVM_FALLTHROUGH;
9170   case Builtin::BI__builtin_memcpy:
9171   case Builtin::BI__builtin_memmove:
9172   case Builtin::BI__builtin_wmemcpy:
9173   case Builtin::BI__builtin_wmemmove: {
9174     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9175                  BuiltinOp == Builtin::BIwmemmove ||
9176                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9177                  BuiltinOp == Builtin::BI__builtin_wmemmove;
9178     bool Move = BuiltinOp == Builtin::BImemmove ||
9179                 BuiltinOp == Builtin::BIwmemmove ||
9180                 BuiltinOp == Builtin::BI__builtin_memmove ||
9181                 BuiltinOp == Builtin::BI__builtin_wmemmove;
9182 
9183     // The result of mem* is the first argument.
9184     if (!Visit(E->getArg(0)))
9185       return false;
9186     LValue Dest = Result;
9187 
9188     LValue Src;
9189     if (!EvaluatePointer(E->getArg(1), Src, Info))
9190       return false;
9191 
9192     APSInt N;
9193     if (!EvaluateInteger(E->getArg(2), N, Info))
9194       return false;
9195     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9196 
9197     // If the size is zero, we treat this as always being a valid no-op.
9198     // (Even if one of the src and dest pointers is null.)
9199     if (!N)
9200       return true;
9201 
9202     // Otherwise, if either of the operands is null, we can't proceed. Don't
9203     // try to determine the type of the copied objects, because there aren't
9204     // any.
9205     if (!Src.Base || !Dest.Base) {
9206       APValue Val;
9207       (!Src.Base ? Src : Dest).moveInto(Val);
9208       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9209           << Move << WChar << !!Src.Base
9210           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9211       return false;
9212     }
9213     if (Src.Designator.Invalid || Dest.Designator.Invalid)
9214       return false;
9215 
9216     // We require that Src and Dest are both pointers to arrays of
9217     // trivially-copyable type. (For the wide version, the designator will be
9218     // invalid if the designated object is not a wchar_t.)
9219     QualType T = Dest.Designator.getType(Info.Ctx);
9220     QualType SrcT = Src.Designator.getType(Info.Ctx);
9221     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9222       // FIXME: Consider using our bit_cast implementation to support this.
9223       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9224       return false;
9225     }
9226     if (T->isIncompleteType()) {
9227       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9228       return false;
9229     }
9230     if (!T.isTriviallyCopyableType(Info.Ctx)) {
9231       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9232       return false;
9233     }
9234 
9235     // Figure out how many T's we're copying.
9236     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9237     if (!WChar) {
9238       uint64_t Remainder;
9239       llvm::APInt OrigN = N;
9240       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9241       if (Remainder) {
9242         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9243             << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
9244             << (unsigned)TSize;
9245         return false;
9246       }
9247     }
9248 
9249     // Check that the copying will remain within the arrays, just so that we
9250     // can give a more meaningful diagnostic. This implicitly also checks that
9251     // N fits into 64 bits.
9252     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9253     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9254     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9255       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9256           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9257           << N.toString(10, /*Signed*/false);
9258       return false;
9259     }
9260     uint64_t NElems = N.getZExtValue();
9261     uint64_t NBytes = NElems * TSize;
9262 
9263     // Check for overlap.
9264     int Direction = 1;
9265     if (HasSameBase(Src, Dest)) {
9266       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9267       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9268       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9269         // Dest is inside the source region.
9270         if (!Move) {
9271           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9272           return false;
9273         }
9274         // For memmove and friends, copy backwards.
9275         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9276             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9277           return false;
9278         Direction = -1;
9279       } else if (!Move && SrcOffset >= DestOffset &&
9280                  SrcOffset - DestOffset < NBytes) {
9281         // Src is inside the destination region for memcpy: invalid.
9282         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9283         return false;
9284       }
9285     }
9286 
9287     while (true) {
9288       APValue Val;
9289       // FIXME: Set WantObjectRepresentation to true if we're copying a
9290       // char-like type?
9291       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9292           !handleAssignment(Info, E, Dest, T, Val))
9293         return false;
9294       // Do not iterate past the last element; if we're copying backwards, that
9295       // might take us off the start of the array.
9296       if (--NElems == 0)
9297         return true;
9298       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9299           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9300         return false;
9301     }
9302   }
9303 
9304   default:
9305     break;
9306   }
9307 
9308   return visitNonBuiltinCallExpr(E);
9309 }
9310 
9311 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9312                                      APValue &Result, const InitListExpr *ILE,
9313                                      QualType AllocType);
9314 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9315                                           APValue &Result,
9316                                           const CXXConstructExpr *CCE,
9317                                           QualType AllocType);
9318 
9319 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9320   if (!Info.getLangOpts().CPlusPlus20)
9321     Info.CCEDiag(E, diag::note_constexpr_new);
9322 
9323   // We cannot speculatively evaluate a delete expression.
9324   if (Info.SpeculativeEvaluationDepth)
9325     return false;
9326 
9327   FunctionDecl *OperatorNew = E->getOperatorNew();
9328 
9329   bool IsNothrow = false;
9330   bool IsPlacement = false;
9331   if (OperatorNew->isReservedGlobalPlacementOperator() &&
9332       Info.CurrentCall->isStdFunction() && !E->isArray()) {
9333     // FIXME Support array placement new.
9334     assert(E->getNumPlacementArgs() == 1);
9335     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9336       return false;
9337     if (Result.Designator.Invalid)
9338       return false;
9339     IsPlacement = true;
9340   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9341     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9342         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9343     return false;
9344   } else if (E->getNumPlacementArgs()) {
9345     // The only new-placement list we support is of the form (std::nothrow).
9346     //
9347     // FIXME: There is no restriction on this, but it's not clear that any
9348     // other form makes any sense. We get here for cases such as:
9349     //
9350     //   new (std::align_val_t{N}) X(int)
9351     //
9352     // (which should presumably be valid only if N is a multiple of
9353     // alignof(int), and in any case can't be deallocated unless N is
9354     // alignof(X) and X has new-extended alignment).
9355     if (E->getNumPlacementArgs() != 1 ||
9356         !E->getPlacementArg(0)->getType()->isNothrowT())
9357       return Error(E, diag::note_constexpr_new_placement);
9358 
9359     LValue Nothrow;
9360     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9361       return false;
9362     IsNothrow = true;
9363   }
9364 
9365   const Expr *Init = E->getInitializer();
9366   const InitListExpr *ResizedArrayILE = nullptr;
9367   const CXXConstructExpr *ResizedArrayCCE = nullptr;
9368   bool ValueInit = false;
9369 
9370   QualType AllocType = E->getAllocatedType();
9371   if (Optional<const Expr*> ArraySize = E->getArraySize()) {
9372     const Expr *Stripped = *ArraySize;
9373     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9374          Stripped = ICE->getSubExpr())
9375       if (ICE->getCastKind() != CK_NoOp &&
9376           ICE->getCastKind() != CK_IntegralCast)
9377         break;
9378 
9379     llvm::APSInt ArrayBound;
9380     if (!EvaluateInteger(Stripped, ArrayBound, Info))
9381       return false;
9382 
9383     // C++ [expr.new]p9:
9384     //   The expression is erroneous if:
9385     //   -- [...] its value before converting to size_t [or] applying the
9386     //      second standard conversion sequence is less than zero
9387     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9388       if (IsNothrow)
9389         return ZeroInitialization(E);
9390 
9391       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9392           << ArrayBound << (*ArraySize)->getSourceRange();
9393       return false;
9394     }
9395 
9396     //   -- its value is such that the size of the allocated object would
9397     //      exceed the implementation-defined limit
9398     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9399                                                 ArrayBound) >
9400         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9401       if (IsNothrow)
9402         return ZeroInitialization(E);
9403 
9404       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9405         << ArrayBound << (*ArraySize)->getSourceRange();
9406       return false;
9407     }
9408 
9409     //   -- the new-initializer is a braced-init-list and the number of
9410     //      array elements for which initializers are provided [...]
9411     //      exceeds the number of elements to initialize
9412     if (!Init) {
9413       // No initialization is performed.
9414     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9415                isa<ImplicitValueInitExpr>(Init)) {
9416       ValueInit = true;
9417     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9418       ResizedArrayCCE = CCE;
9419     } else {
9420       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9421       assert(CAT && "unexpected type for array initializer");
9422 
9423       unsigned Bits =
9424           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9425       llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
9426       llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
9427       if (InitBound.ugt(AllocBound)) {
9428         if (IsNothrow)
9429           return ZeroInitialization(E);
9430 
9431         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9432             << AllocBound.toString(10, /*Signed=*/false)
9433             << InitBound.toString(10, /*Signed=*/false)
9434             << (*ArraySize)->getSourceRange();
9435         return false;
9436       }
9437 
9438       // If the sizes differ, we must have an initializer list, and we need
9439       // special handling for this case when we initialize.
9440       if (InitBound != AllocBound)
9441         ResizedArrayILE = cast<InitListExpr>(Init);
9442     }
9443 
9444     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9445                                               ArrayType::Normal, 0);
9446   } else {
9447     assert(!AllocType->isArrayType() &&
9448            "array allocation with non-array new");
9449   }
9450 
9451   APValue *Val;
9452   if (IsPlacement) {
9453     AccessKinds AK = AK_Construct;
9454     struct FindObjectHandler {
9455       EvalInfo &Info;
9456       const Expr *E;
9457       QualType AllocType;
9458       const AccessKinds AccessKind;
9459       APValue *Value;
9460 
9461       typedef bool result_type;
9462       bool failed() { return false; }
9463       bool found(APValue &Subobj, QualType SubobjType) {
9464         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9465         // old name of the object to be used to name the new object.
9466         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9467           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9468             SubobjType << AllocType;
9469           return false;
9470         }
9471         Value = &Subobj;
9472         return true;
9473       }
9474       bool found(APSInt &Value, QualType SubobjType) {
9475         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9476         return false;
9477       }
9478       bool found(APFloat &Value, QualType SubobjType) {
9479         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9480         return false;
9481       }
9482     } Handler = {Info, E, AllocType, AK, nullptr};
9483 
9484     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9485     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9486       return false;
9487 
9488     Val = Handler.Value;
9489 
9490     // [basic.life]p1:
9491     //   The lifetime of an object o of type T ends when [...] the storage
9492     //   which the object occupies is [...] reused by an object that is not
9493     //   nested within o (6.6.2).
9494     *Val = APValue();
9495   } else {
9496     // Perform the allocation and obtain a pointer to the resulting object.
9497     Val = Info.createHeapAlloc(E, AllocType, Result);
9498     if (!Val)
9499       return false;
9500   }
9501 
9502   if (ValueInit) {
9503     ImplicitValueInitExpr VIE(AllocType);
9504     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9505       return false;
9506   } else if (ResizedArrayILE) {
9507     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9508                                   AllocType))
9509       return false;
9510   } else if (ResizedArrayCCE) {
9511     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9512                                        AllocType))
9513       return false;
9514   } else if (Init) {
9515     if (!EvaluateInPlace(*Val, Info, Result, Init))
9516       return false;
9517   } else if (!getDefaultInitValue(AllocType, *Val)) {
9518     return false;
9519   }
9520 
9521   // Array new returns a pointer to the first element, not a pointer to the
9522   // array.
9523   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9524     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9525 
9526   return true;
9527 }
9528 //===----------------------------------------------------------------------===//
9529 // Member Pointer Evaluation
9530 //===----------------------------------------------------------------------===//
9531 
9532 namespace {
9533 class MemberPointerExprEvaluator
9534   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9535   MemberPtr &Result;
9536 
9537   bool Success(const ValueDecl *D) {
9538     Result = MemberPtr(D);
9539     return true;
9540   }
9541 public:
9542 
9543   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9544     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9545 
9546   bool Success(const APValue &V, const Expr *E) {
9547     Result.setFrom(V);
9548     return true;
9549   }
9550   bool ZeroInitialization(const Expr *E) {
9551     return Success((const ValueDecl*)nullptr);
9552   }
9553 
9554   bool VisitCastExpr(const CastExpr *E);
9555   bool VisitUnaryAddrOf(const UnaryOperator *E);
9556 };
9557 } // end anonymous namespace
9558 
9559 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9560                                   EvalInfo &Info) {
9561   assert(!E->isValueDependent());
9562   assert(E->isRValue() && E->getType()->isMemberPointerType());
9563   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9564 }
9565 
9566 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9567   switch (E->getCastKind()) {
9568   default:
9569     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9570 
9571   case CK_NullToMemberPointer:
9572     VisitIgnoredValue(E->getSubExpr());
9573     return ZeroInitialization(E);
9574 
9575   case CK_BaseToDerivedMemberPointer: {
9576     if (!Visit(E->getSubExpr()))
9577       return false;
9578     if (E->path_empty())
9579       return true;
9580     // Base-to-derived member pointer casts store the path in derived-to-base
9581     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9582     // the wrong end of the derived->base arc, so stagger the path by one class.
9583     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9584     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9585          PathI != PathE; ++PathI) {
9586       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9587       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9588       if (!Result.castToDerived(Derived))
9589         return Error(E);
9590     }
9591     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9592     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9593       return Error(E);
9594     return true;
9595   }
9596 
9597   case CK_DerivedToBaseMemberPointer:
9598     if (!Visit(E->getSubExpr()))
9599       return false;
9600     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9601          PathE = E->path_end(); PathI != PathE; ++PathI) {
9602       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9603       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9604       if (!Result.castToBase(Base))
9605         return Error(E);
9606     }
9607     return true;
9608   }
9609 }
9610 
9611 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9612   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9613   // member can be formed.
9614   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9615 }
9616 
9617 //===----------------------------------------------------------------------===//
9618 // Record Evaluation
9619 //===----------------------------------------------------------------------===//
9620 
9621 namespace {
9622   class RecordExprEvaluator
9623   : public ExprEvaluatorBase<RecordExprEvaluator> {
9624     const LValue &This;
9625     APValue &Result;
9626   public:
9627 
9628     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9629       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9630 
9631     bool Success(const APValue &V, const Expr *E) {
9632       Result = V;
9633       return true;
9634     }
9635     bool ZeroInitialization(const Expr *E) {
9636       return ZeroInitialization(E, E->getType());
9637     }
9638     bool ZeroInitialization(const Expr *E, QualType T);
9639 
9640     bool VisitCallExpr(const CallExpr *E) {
9641       return handleCallExpr(E, Result, &This);
9642     }
9643     bool VisitCastExpr(const CastExpr *E);
9644     bool VisitInitListExpr(const InitListExpr *E);
9645     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9646       return VisitCXXConstructExpr(E, E->getType());
9647     }
9648     bool VisitLambdaExpr(const LambdaExpr *E);
9649     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9650     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9651     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9652     bool VisitBinCmp(const BinaryOperator *E);
9653   };
9654 }
9655 
9656 /// Perform zero-initialization on an object of non-union class type.
9657 /// C++11 [dcl.init]p5:
9658 ///  To zero-initialize an object or reference of type T means:
9659 ///    [...]
9660 ///    -- if T is a (possibly cv-qualified) non-union class type,
9661 ///       each non-static data member and each base-class subobject is
9662 ///       zero-initialized
9663 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9664                                           const RecordDecl *RD,
9665                                           const LValue &This, APValue &Result) {
9666   assert(!RD->isUnion() && "Expected non-union class type");
9667   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9668   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9669                    std::distance(RD->field_begin(), RD->field_end()));
9670 
9671   if (RD->isInvalidDecl()) return false;
9672   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9673 
9674   if (CD) {
9675     unsigned Index = 0;
9676     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9677            End = CD->bases_end(); I != End; ++I, ++Index) {
9678       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9679       LValue Subobject = This;
9680       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9681         return false;
9682       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9683                                          Result.getStructBase(Index)))
9684         return false;
9685     }
9686   }
9687 
9688   for (const auto *I : RD->fields()) {
9689     // -- if T is a reference type, no initialization is performed.
9690     if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
9691       continue;
9692 
9693     LValue Subobject = This;
9694     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9695       return false;
9696 
9697     ImplicitValueInitExpr VIE(I->getType());
9698     if (!EvaluateInPlace(
9699           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9700       return false;
9701   }
9702 
9703   return true;
9704 }
9705 
9706 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9707   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9708   if (RD->isInvalidDecl()) return false;
9709   if (RD->isUnion()) {
9710     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9711     // object's first non-static named data member is zero-initialized
9712     RecordDecl::field_iterator I = RD->field_begin();
9713     while (I != RD->field_end() && (*I)->isUnnamedBitfield())
9714       ++I;
9715     if (I == RD->field_end()) {
9716       Result = APValue((const FieldDecl*)nullptr);
9717       return true;
9718     }
9719 
9720     LValue Subobject = This;
9721     if (!HandleLValueMember(Info, E, Subobject, *I))
9722       return false;
9723     Result = APValue(*I);
9724     ImplicitValueInitExpr VIE(I->getType());
9725     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9726   }
9727 
9728   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9729     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9730     return false;
9731   }
9732 
9733   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9734 }
9735 
9736 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9737   switch (E->getCastKind()) {
9738   default:
9739     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9740 
9741   case CK_ConstructorConversion:
9742     return Visit(E->getSubExpr());
9743 
9744   case CK_DerivedToBase:
9745   case CK_UncheckedDerivedToBase: {
9746     APValue DerivedObject;
9747     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9748       return false;
9749     if (!DerivedObject.isStruct())
9750       return Error(E->getSubExpr());
9751 
9752     // Derived-to-base rvalue conversion: just slice off the derived part.
9753     APValue *Value = &DerivedObject;
9754     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9755     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9756          PathE = E->path_end(); PathI != PathE; ++PathI) {
9757       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9758       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9759       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9760       RD = Base;
9761     }
9762     Result = *Value;
9763     return true;
9764   }
9765   }
9766 }
9767 
9768 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9769   if (E->isTransparent())
9770     return Visit(E->getInit(0));
9771 
9772   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9773   if (RD->isInvalidDecl()) return false;
9774   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9775   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9776 
9777   EvalInfo::EvaluatingConstructorRAII EvalObj(
9778       Info,
9779       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9780       CXXRD && CXXRD->getNumBases());
9781 
9782   if (RD->isUnion()) {
9783     const FieldDecl *Field = E->getInitializedFieldInUnion();
9784     Result = APValue(Field);
9785     if (!Field)
9786       return true;
9787 
9788     // If the initializer list for a union does not contain any elements, the
9789     // first element of the union is value-initialized.
9790     // FIXME: The element should be initialized from an initializer list.
9791     //        Is this difference ever observable for initializer lists which
9792     //        we don't build?
9793     ImplicitValueInitExpr VIE(Field->getType());
9794     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9795 
9796     LValue Subobject = This;
9797     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9798       return false;
9799 
9800     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9801     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9802                                   isa<CXXDefaultInitExpr>(InitExpr));
9803 
9804     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
9805   }
9806 
9807   if (!Result.hasValue())
9808     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9809                      std::distance(RD->field_begin(), RD->field_end()));
9810   unsigned ElementNo = 0;
9811   bool Success = true;
9812 
9813   // Initialize base classes.
9814   if (CXXRD && CXXRD->getNumBases()) {
9815     for (const auto &Base : CXXRD->bases()) {
9816       assert(ElementNo < E->getNumInits() && "missing init for base class");
9817       const Expr *Init = E->getInit(ElementNo);
9818 
9819       LValue Subobject = This;
9820       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9821         return false;
9822 
9823       APValue &FieldVal = Result.getStructBase(ElementNo);
9824       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9825         if (!Info.noteFailure())
9826           return false;
9827         Success = false;
9828       }
9829       ++ElementNo;
9830     }
9831 
9832     EvalObj.finishedConstructingBases();
9833   }
9834 
9835   // Initialize members.
9836   for (const auto *Field : RD->fields()) {
9837     // Anonymous bit-fields are not considered members of the class for
9838     // purposes of aggregate initialization.
9839     if (Field->isUnnamedBitfield())
9840       continue;
9841 
9842     LValue Subobject = This;
9843 
9844     bool HaveInit = ElementNo < E->getNumInits();
9845 
9846     // FIXME: Diagnostics here should point to the end of the initializer
9847     // list, not the start.
9848     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9849                             Subobject, Field, &Layout))
9850       return false;
9851 
9852     // Perform an implicit value-initialization for members beyond the end of
9853     // the initializer list.
9854     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9855     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9856 
9857     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9858     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9859                                   isa<CXXDefaultInitExpr>(Init));
9860 
9861     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9862     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9863         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9864                                                        FieldVal, Field))) {
9865       if (!Info.noteFailure())
9866         return false;
9867       Success = false;
9868     }
9869   }
9870 
9871   EvalObj.finishedConstructingFields();
9872 
9873   return Success;
9874 }
9875 
9876 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9877                                                 QualType T) {
9878   // Note that E's type is not necessarily the type of our class here; we might
9879   // be initializing an array element instead.
9880   const CXXConstructorDecl *FD = E->getConstructor();
9881   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9882 
9883   bool ZeroInit = E->requiresZeroInitialization();
9884   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
9885     // If we've already performed zero-initialization, we're already done.
9886     if (Result.hasValue())
9887       return true;
9888 
9889     if (ZeroInit)
9890       return ZeroInitialization(E, T);
9891 
9892     return getDefaultInitValue(T, Result);
9893   }
9894 
9895   const FunctionDecl *Definition = nullptr;
9896   auto Body = FD->getBody(Definition);
9897 
9898   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9899     return false;
9900 
9901   // Avoid materializing a temporary for an elidable copy/move constructor.
9902   if (E->isElidable() && !ZeroInit)
9903     if (const MaterializeTemporaryExpr *ME
9904           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
9905       return Visit(ME->getSubExpr());
9906 
9907   if (ZeroInit && !ZeroInitialization(E, T))
9908     return false;
9909 
9910   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
9911   return HandleConstructorCall(E, This, Args,
9912                                cast<CXXConstructorDecl>(Definition), Info,
9913                                Result);
9914 }
9915 
9916 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9917     const CXXInheritedCtorInitExpr *E) {
9918   if (!Info.CurrentCall) {
9919     assert(Info.checkingPotentialConstantExpression());
9920     return false;
9921   }
9922 
9923   const CXXConstructorDecl *FD = E->getConstructor();
9924   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9925     return false;
9926 
9927   const FunctionDecl *Definition = nullptr;
9928   auto Body = FD->getBody(Definition);
9929 
9930   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9931     return false;
9932 
9933   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
9934                                cast<CXXConstructorDecl>(Definition), Info,
9935                                Result);
9936 }
9937 
9938 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
9939     const CXXStdInitializerListExpr *E) {
9940   const ConstantArrayType *ArrayType =
9941       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
9942 
9943   LValue Array;
9944   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
9945     return false;
9946 
9947   // Get a pointer to the first element of the array.
9948   Array.addArray(Info, E, ArrayType);
9949 
9950   auto InvalidType = [&] {
9951     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
9952       << E->getType();
9953     return false;
9954   };
9955 
9956   // FIXME: Perform the checks on the field types in SemaInit.
9957   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
9958   RecordDecl::field_iterator Field = Record->field_begin();
9959   if (Field == Record->field_end())
9960     return InvalidType();
9961 
9962   // Start pointer.
9963   if (!Field->getType()->isPointerType() ||
9964       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9965                             ArrayType->getElementType()))
9966     return InvalidType();
9967 
9968   // FIXME: What if the initializer_list type has base classes, etc?
9969   Result = APValue(APValue::UninitStruct(), 0, 2);
9970   Array.moveInto(Result.getStructField(0));
9971 
9972   if (++Field == Record->field_end())
9973     return InvalidType();
9974 
9975   if (Field->getType()->isPointerType() &&
9976       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
9977                            ArrayType->getElementType())) {
9978     // End pointer.
9979     if (!HandleLValueArrayAdjustment(Info, E, Array,
9980                                      ArrayType->getElementType(),
9981                                      ArrayType->getSize().getZExtValue()))
9982       return false;
9983     Array.moveInto(Result.getStructField(1));
9984   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
9985     // Length.
9986     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
9987   else
9988     return InvalidType();
9989 
9990   if (++Field != Record->field_end())
9991     return InvalidType();
9992 
9993   return true;
9994 }
9995 
9996 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
9997   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
9998   if (ClosureClass->isInvalidDecl())
9999     return false;
10000 
10001   const size_t NumFields =
10002       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10003 
10004   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10005                                             E->capture_init_end()) &&
10006          "The number of lambda capture initializers should equal the number of "
10007          "fields within the closure type");
10008 
10009   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10010   // Iterate through all the lambda's closure object's fields and initialize
10011   // them.
10012   auto *CaptureInitIt = E->capture_init_begin();
10013   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
10014   bool Success = true;
10015   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10016   for (const auto *Field : ClosureClass->fields()) {
10017     assert(CaptureInitIt != E->capture_init_end());
10018     // Get the initializer for this field
10019     Expr *const CurFieldInit = *CaptureInitIt++;
10020 
10021     // If there is no initializer, either this is a VLA or an error has
10022     // occurred.
10023     if (!CurFieldInit)
10024       return Error(E);
10025 
10026     LValue Subobject = This;
10027 
10028     if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10029       return false;
10030 
10031     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10032     if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10033       if (!Info.keepEvaluatingAfterFailure())
10034         return false;
10035       Success = false;
10036     }
10037     ++CaptureIt;
10038   }
10039   return Success;
10040 }
10041 
10042 static bool EvaluateRecord(const Expr *E, const LValue &This,
10043                            APValue &Result, EvalInfo &Info) {
10044   assert(!E->isValueDependent());
10045   assert(E->isRValue() && E->getType()->isRecordType() &&
10046          "can't evaluate expression as a record rvalue");
10047   return RecordExprEvaluator(Info, This, Result).Visit(E);
10048 }
10049 
10050 //===----------------------------------------------------------------------===//
10051 // Temporary Evaluation
10052 //
10053 // Temporaries are represented in the AST as rvalues, but generally behave like
10054 // lvalues. The full-object of which the temporary is a subobject is implicitly
10055 // materialized so that a reference can bind to it.
10056 //===----------------------------------------------------------------------===//
10057 namespace {
10058 class TemporaryExprEvaluator
10059   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10060 public:
10061   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10062     LValueExprEvaluatorBaseTy(Info, Result, false) {}
10063 
10064   /// Visit an expression which constructs the value of this temporary.
10065   bool VisitConstructExpr(const Expr *E) {
10066     APValue &Value = Info.CurrentCall->createTemporary(
10067         E, E->getType(), ScopeKind::FullExpression, Result);
10068     return EvaluateInPlace(Value, Info, Result, E);
10069   }
10070 
10071   bool VisitCastExpr(const CastExpr *E) {
10072     switch (E->getCastKind()) {
10073     default:
10074       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10075 
10076     case CK_ConstructorConversion:
10077       return VisitConstructExpr(E->getSubExpr());
10078     }
10079   }
10080   bool VisitInitListExpr(const InitListExpr *E) {
10081     return VisitConstructExpr(E);
10082   }
10083   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10084     return VisitConstructExpr(E);
10085   }
10086   bool VisitCallExpr(const CallExpr *E) {
10087     return VisitConstructExpr(E);
10088   }
10089   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10090     return VisitConstructExpr(E);
10091   }
10092   bool VisitLambdaExpr(const LambdaExpr *E) {
10093     return VisitConstructExpr(E);
10094   }
10095 };
10096 } // end anonymous namespace
10097 
10098 /// Evaluate an expression of record type as a temporary.
10099 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10100   assert(!E->isValueDependent());
10101   assert(E->isRValue() && E->getType()->isRecordType());
10102   return TemporaryExprEvaluator(Info, Result).Visit(E);
10103 }
10104 
10105 //===----------------------------------------------------------------------===//
10106 // Vector Evaluation
10107 //===----------------------------------------------------------------------===//
10108 
10109 namespace {
10110   class VectorExprEvaluator
10111   : public ExprEvaluatorBase<VectorExprEvaluator> {
10112     APValue &Result;
10113   public:
10114 
10115     VectorExprEvaluator(EvalInfo &info, APValue &Result)
10116       : ExprEvaluatorBaseTy(info), Result(Result) {}
10117 
10118     bool Success(ArrayRef<APValue> V, const Expr *E) {
10119       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10120       // FIXME: remove this APValue copy.
10121       Result = APValue(V.data(), V.size());
10122       return true;
10123     }
10124     bool Success(const APValue &V, const Expr *E) {
10125       assert(V.isVector());
10126       Result = V;
10127       return true;
10128     }
10129     bool ZeroInitialization(const Expr *E);
10130 
10131     bool VisitUnaryReal(const UnaryOperator *E)
10132       { return Visit(E->getSubExpr()); }
10133     bool VisitCastExpr(const CastExpr* E);
10134     bool VisitInitListExpr(const InitListExpr *E);
10135     bool VisitUnaryImag(const UnaryOperator *E);
10136     bool VisitBinaryOperator(const BinaryOperator *E);
10137     // FIXME: Missing: unary -, unary ~, conditional operator (for GNU
10138     //                 conditional select), shufflevector, ExtVectorElementExpr
10139   };
10140 } // end anonymous namespace
10141 
10142 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10143   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
10144   return VectorExprEvaluator(Info, Result).Visit(E);
10145 }
10146 
10147 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10148   const VectorType *VTy = E->getType()->castAs<VectorType>();
10149   unsigned NElts = VTy->getNumElements();
10150 
10151   const Expr *SE = E->getSubExpr();
10152   QualType SETy = SE->getType();
10153 
10154   switch (E->getCastKind()) {
10155   case CK_VectorSplat: {
10156     APValue Val = APValue();
10157     if (SETy->isIntegerType()) {
10158       APSInt IntResult;
10159       if (!EvaluateInteger(SE, IntResult, Info))
10160         return false;
10161       Val = APValue(std::move(IntResult));
10162     } else if (SETy->isRealFloatingType()) {
10163       APFloat FloatResult(0.0);
10164       if (!EvaluateFloat(SE, FloatResult, Info))
10165         return false;
10166       Val = APValue(std::move(FloatResult));
10167     } else {
10168       return Error(E);
10169     }
10170 
10171     // Splat and create vector APValue.
10172     SmallVector<APValue, 4> Elts(NElts, Val);
10173     return Success(Elts, E);
10174   }
10175   case CK_BitCast: {
10176     // Evaluate the operand into an APInt we can extract from.
10177     llvm::APInt SValInt;
10178     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10179       return false;
10180     // Extract the elements
10181     QualType EltTy = VTy->getElementType();
10182     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10183     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10184     SmallVector<APValue, 4> Elts;
10185     if (EltTy->isRealFloatingType()) {
10186       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10187       unsigned FloatEltSize = EltSize;
10188       if (&Sem == &APFloat::x87DoubleExtended())
10189         FloatEltSize = 80;
10190       for (unsigned i = 0; i < NElts; i++) {
10191         llvm::APInt Elt;
10192         if (BigEndian)
10193           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
10194         else
10195           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
10196         Elts.push_back(APValue(APFloat(Sem, Elt)));
10197       }
10198     } else if (EltTy->isIntegerType()) {
10199       for (unsigned i = 0; i < NElts; i++) {
10200         llvm::APInt Elt;
10201         if (BigEndian)
10202           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10203         else
10204           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10205         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
10206       }
10207     } else {
10208       return Error(E);
10209     }
10210     return Success(Elts, E);
10211   }
10212   default:
10213     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10214   }
10215 }
10216 
10217 bool
10218 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10219   const VectorType *VT = E->getType()->castAs<VectorType>();
10220   unsigned NumInits = E->getNumInits();
10221   unsigned NumElements = VT->getNumElements();
10222 
10223   QualType EltTy = VT->getElementType();
10224   SmallVector<APValue, 4> Elements;
10225 
10226   // The number of initializers can be less than the number of
10227   // vector elements. For OpenCL, this can be due to nested vector
10228   // initialization. For GCC compatibility, missing trailing elements
10229   // should be initialized with zeroes.
10230   unsigned CountInits = 0, CountElts = 0;
10231   while (CountElts < NumElements) {
10232     // Handle nested vector initialization.
10233     if (CountInits < NumInits
10234         && E->getInit(CountInits)->getType()->isVectorType()) {
10235       APValue v;
10236       if (!EvaluateVector(E->getInit(CountInits), v, Info))
10237         return Error(E);
10238       unsigned vlen = v.getVectorLength();
10239       for (unsigned j = 0; j < vlen; j++)
10240         Elements.push_back(v.getVectorElt(j));
10241       CountElts += vlen;
10242     } else if (EltTy->isIntegerType()) {
10243       llvm::APSInt sInt(32);
10244       if (CountInits < NumInits) {
10245         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10246           return false;
10247       } else // trailing integer zero.
10248         sInt = Info.Ctx.MakeIntValue(0, EltTy);
10249       Elements.push_back(APValue(sInt));
10250       CountElts++;
10251     } else {
10252       llvm::APFloat f(0.0);
10253       if (CountInits < NumInits) {
10254         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10255           return false;
10256       } else // trailing float zero.
10257         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10258       Elements.push_back(APValue(f));
10259       CountElts++;
10260     }
10261     CountInits++;
10262   }
10263   return Success(Elements, E);
10264 }
10265 
10266 bool
10267 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10268   const auto *VT = E->getType()->castAs<VectorType>();
10269   QualType EltTy = VT->getElementType();
10270   APValue ZeroElement;
10271   if (EltTy->isIntegerType())
10272     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10273   else
10274     ZeroElement =
10275         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10276 
10277   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10278   return Success(Elements, E);
10279 }
10280 
10281 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10282   VisitIgnoredValue(E->getSubExpr());
10283   return ZeroInitialization(E);
10284 }
10285 
10286 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10287   BinaryOperatorKind Op = E->getOpcode();
10288   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10289          "Operation not supported on vector types");
10290 
10291   if (Op == BO_Comma)
10292     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10293 
10294   Expr *LHS = E->getLHS();
10295   Expr *RHS = E->getRHS();
10296 
10297   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10298          "Must both be vector types");
10299   // Checking JUST the types are the same would be fine, except shifts don't
10300   // need to have their types be the same (since you always shift by an int).
10301   assert(LHS->getType()->getAs<VectorType>()->getNumElements() ==
10302              E->getType()->getAs<VectorType>()->getNumElements() &&
10303          RHS->getType()->getAs<VectorType>()->getNumElements() ==
10304              E->getType()->getAs<VectorType>()->getNumElements() &&
10305          "All operands must be the same size.");
10306 
10307   APValue LHSValue;
10308   APValue RHSValue;
10309   bool LHSOK = Evaluate(LHSValue, Info, LHS);
10310   if (!LHSOK && !Info.noteFailure())
10311     return false;
10312   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10313     return false;
10314 
10315   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10316     return false;
10317 
10318   return Success(LHSValue, E);
10319 }
10320 
10321 //===----------------------------------------------------------------------===//
10322 // Array Evaluation
10323 //===----------------------------------------------------------------------===//
10324 
10325 namespace {
10326   class ArrayExprEvaluator
10327   : public ExprEvaluatorBase<ArrayExprEvaluator> {
10328     const LValue &This;
10329     APValue &Result;
10330   public:
10331 
10332     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10333       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10334 
10335     bool Success(const APValue &V, const Expr *E) {
10336       assert(V.isArray() && "expected array");
10337       Result = V;
10338       return true;
10339     }
10340 
10341     bool ZeroInitialization(const Expr *E) {
10342       const ConstantArrayType *CAT =
10343           Info.Ctx.getAsConstantArrayType(E->getType());
10344       if (!CAT) {
10345         if (E->getType()->isIncompleteArrayType()) {
10346           // We can be asked to zero-initialize a flexible array member; this
10347           // is represented as an ImplicitValueInitExpr of incomplete array
10348           // type. In this case, the array has zero elements.
10349           Result = APValue(APValue::UninitArray(), 0, 0);
10350           return true;
10351         }
10352         // FIXME: We could handle VLAs here.
10353         return Error(E);
10354       }
10355 
10356       Result = APValue(APValue::UninitArray(), 0,
10357                        CAT->getSize().getZExtValue());
10358       if (!Result.hasArrayFiller()) return true;
10359 
10360       // Zero-initialize all elements.
10361       LValue Subobject = This;
10362       Subobject.addArray(Info, E, CAT);
10363       ImplicitValueInitExpr VIE(CAT->getElementType());
10364       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10365     }
10366 
10367     bool VisitCallExpr(const CallExpr *E) {
10368       return handleCallExpr(E, Result, &This);
10369     }
10370     bool VisitInitListExpr(const InitListExpr *E,
10371                            QualType AllocType = QualType());
10372     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10373     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10374     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10375                                const LValue &Subobject,
10376                                APValue *Value, QualType Type);
10377     bool VisitStringLiteral(const StringLiteral *E,
10378                             QualType AllocType = QualType()) {
10379       expandStringLiteral(Info, E, Result, AllocType);
10380       return true;
10381     }
10382   };
10383 } // end anonymous namespace
10384 
10385 static bool EvaluateArray(const Expr *E, const LValue &This,
10386                           APValue &Result, EvalInfo &Info) {
10387   assert(!E->isValueDependent());
10388   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
10389   return ArrayExprEvaluator(Info, This, Result).Visit(E);
10390 }
10391 
10392 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10393                                      APValue &Result, const InitListExpr *ILE,
10394                                      QualType AllocType) {
10395   assert(!ILE->isValueDependent());
10396   assert(ILE->isRValue() && ILE->getType()->isArrayType() &&
10397          "not an array rvalue");
10398   return ArrayExprEvaluator(Info, This, Result)
10399       .VisitInitListExpr(ILE, AllocType);
10400 }
10401 
10402 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10403                                           APValue &Result,
10404                                           const CXXConstructExpr *CCE,
10405                                           QualType AllocType) {
10406   assert(!CCE->isValueDependent());
10407   assert(CCE->isRValue() && CCE->getType()->isArrayType() &&
10408          "not an array rvalue");
10409   return ArrayExprEvaluator(Info, This, Result)
10410       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10411 }
10412 
10413 // Return true iff the given array filler may depend on the element index.
10414 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10415   // For now, just allow non-class value-initialization and initialization
10416   // lists comprised of them.
10417   if (isa<ImplicitValueInitExpr>(FillerExpr))
10418     return false;
10419   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10420     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10421       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10422         return true;
10423     }
10424     return false;
10425   }
10426   return true;
10427 }
10428 
10429 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10430                                            QualType AllocType) {
10431   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10432       AllocType.isNull() ? E->getType() : AllocType);
10433   if (!CAT)
10434     return Error(E);
10435 
10436   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10437   // an appropriately-typed string literal enclosed in braces.
10438   if (E->isStringLiteralInit()) {
10439     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParens());
10440     // FIXME: Support ObjCEncodeExpr here once we support it in
10441     // ArrayExprEvaluator generally.
10442     if (!SL)
10443       return Error(E);
10444     return VisitStringLiteral(SL, AllocType);
10445   }
10446 
10447   bool Success = true;
10448 
10449   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10450          "zero-initialized array shouldn't have any initialized elts");
10451   APValue Filler;
10452   if (Result.isArray() && Result.hasArrayFiller())
10453     Filler = Result.getArrayFiller();
10454 
10455   unsigned NumEltsToInit = E->getNumInits();
10456   unsigned NumElts = CAT->getSize().getZExtValue();
10457   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
10458 
10459   // If the initializer might depend on the array index, run it for each
10460   // array element.
10461   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
10462     NumEltsToInit = NumElts;
10463 
10464   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10465                           << NumEltsToInit << ".\n");
10466 
10467   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10468 
10469   // If the array was previously zero-initialized, preserve the
10470   // zero-initialized values.
10471   if (Filler.hasValue()) {
10472     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10473       Result.getArrayInitializedElt(I) = Filler;
10474     if (Result.hasArrayFiller())
10475       Result.getArrayFiller() = Filler;
10476   }
10477 
10478   LValue Subobject = This;
10479   Subobject.addArray(Info, E, CAT);
10480   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10481     const Expr *Init =
10482         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
10483     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10484                          Info, Subobject, Init) ||
10485         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10486                                      CAT->getElementType(), 1)) {
10487       if (!Info.noteFailure())
10488         return false;
10489       Success = false;
10490     }
10491   }
10492 
10493   if (!Result.hasArrayFiller())
10494     return Success;
10495 
10496   // If we get here, we have a trivial filler, which we can just evaluate
10497   // once and splat over the rest of the array elements.
10498   assert(FillerExpr && "no array filler for incomplete init list");
10499   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10500                          FillerExpr) && Success;
10501 }
10502 
10503 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10504   LValue CommonLV;
10505   if (E->getCommonExpr() &&
10506       !Evaluate(Info.CurrentCall->createTemporary(
10507                     E->getCommonExpr(),
10508                     getStorageType(Info.Ctx, E->getCommonExpr()),
10509                     ScopeKind::FullExpression, CommonLV),
10510                 Info, E->getCommonExpr()->getSourceExpr()))
10511     return false;
10512 
10513   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10514 
10515   uint64_t Elements = CAT->getSize().getZExtValue();
10516   Result = APValue(APValue::UninitArray(), Elements, Elements);
10517 
10518   LValue Subobject = This;
10519   Subobject.addArray(Info, E, CAT);
10520 
10521   bool Success = true;
10522   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10523     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10524                          Info, Subobject, E->getSubExpr()) ||
10525         !HandleLValueArrayAdjustment(Info, E, Subobject,
10526                                      CAT->getElementType(), 1)) {
10527       if (!Info.noteFailure())
10528         return false;
10529       Success = false;
10530     }
10531   }
10532 
10533   return Success;
10534 }
10535 
10536 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10537   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10538 }
10539 
10540 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10541                                                const LValue &Subobject,
10542                                                APValue *Value,
10543                                                QualType Type) {
10544   bool HadZeroInit = Value->hasValue();
10545 
10546   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10547     unsigned N = CAT->getSize().getZExtValue();
10548 
10549     // Preserve the array filler if we had prior zero-initialization.
10550     APValue Filler =
10551       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10552                                              : APValue();
10553 
10554     *Value = APValue(APValue::UninitArray(), N, N);
10555 
10556     if (HadZeroInit)
10557       for (unsigned I = 0; I != N; ++I)
10558         Value->getArrayInitializedElt(I) = Filler;
10559 
10560     // Initialize the elements.
10561     LValue ArrayElt = Subobject;
10562     ArrayElt.addArray(Info, E, CAT);
10563     for (unsigned I = 0; I != N; ++I)
10564       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
10565                                  CAT->getElementType()) ||
10566           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10567                                        CAT->getElementType(), 1))
10568         return false;
10569 
10570     return true;
10571   }
10572 
10573   if (!Type->isRecordType())
10574     return Error(E);
10575 
10576   return RecordExprEvaluator(Info, Subobject, *Value)
10577              .VisitCXXConstructExpr(E, Type);
10578 }
10579 
10580 //===----------------------------------------------------------------------===//
10581 // Integer Evaluation
10582 //
10583 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10584 // types and back in constant folding. Integer values are thus represented
10585 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10586 //===----------------------------------------------------------------------===//
10587 
10588 namespace {
10589 class IntExprEvaluator
10590         : public ExprEvaluatorBase<IntExprEvaluator> {
10591   APValue &Result;
10592 public:
10593   IntExprEvaluator(EvalInfo &info, APValue &result)
10594       : ExprEvaluatorBaseTy(info), Result(result) {}
10595 
10596   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10597     assert(E->getType()->isIntegralOrEnumerationType() &&
10598            "Invalid evaluation result.");
10599     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10600            "Invalid evaluation result.");
10601     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10602            "Invalid evaluation result.");
10603     Result = APValue(SI);
10604     return true;
10605   }
10606   bool Success(const llvm::APSInt &SI, const Expr *E) {
10607     return Success(SI, E, Result);
10608   }
10609 
10610   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10611     assert(E->getType()->isIntegralOrEnumerationType() &&
10612            "Invalid evaluation result.");
10613     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10614            "Invalid evaluation result.");
10615     Result = APValue(APSInt(I));
10616     Result.getInt().setIsUnsigned(
10617                             E->getType()->isUnsignedIntegerOrEnumerationType());
10618     return true;
10619   }
10620   bool Success(const llvm::APInt &I, const Expr *E) {
10621     return Success(I, E, Result);
10622   }
10623 
10624   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10625     assert(E->getType()->isIntegralOrEnumerationType() &&
10626            "Invalid evaluation result.");
10627     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10628     return true;
10629   }
10630   bool Success(uint64_t Value, const Expr *E) {
10631     return Success(Value, E, Result);
10632   }
10633 
10634   bool Success(CharUnits Size, const Expr *E) {
10635     return Success(Size.getQuantity(), E);
10636   }
10637 
10638   bool Success(const APValue &V, const Expr *E) {
10639     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10640       Result = V;
10641       return true;
10642     }
10643     return Success(V.getInt(), E);
10644   }
10645 
10646   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10647 
10648   //===--------------------------------------------------------------------===//
10649   //                            Visitor Methods
10650   //===--------------------------------------------------------------------===//
10651 
10652   bool VisitIntegerLiteral(const IntegerLiteral *E) {
10653     return Success(E->getValue(), E);
10654   }
10655   bool VisitCharacterLiteral(const CharacterLiteral *E) {
10656     return Success(E->getValue(), E);
10657   }
10658 
10659   bool CheckReferencedDecl(const Expr *E, const Decl *D);
10660   bool VisitDeclRefExpr(const DeclRefExpr *E) {
10661     if (CheckReferencedDecl(E, E->getDecl()))
10662       return true;
10663 
10664     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
10665   }
10666   bool VisitMemberExpr(const MemberExpr *E) {
10667     if (CheckReferencedDecl(E, E->getMemberDecl())) {
10668       VisitIgnoredBaseExpression(E->getBase());
10669       return true;
10670     }
10671 
10672     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
10673   }
10674 
10675   bool VisitCallExpr(const CallExpr *E);
10676   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10677   bool VisitBinaryOperator(const BinaryOperator *E);
10678   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
10679   bool VisitUnaryOperator(const UnaryOperator *E);
10680 
10681   bool VisitCastExpr(const CastExpr* E);
10682   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
10683 
10684   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
10685     return Success(E->getValue(), E);
10686   }
10687 
10688   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
10689     return Success(E->getValue(), E);
10690   }
10691 
10692   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
10693     if (Info.ArrayInitIndex == uint64_t(-1)) {
10694       // We were asked to evaluate this subexpression independent of the
10695       // enclosing ArrayInitLoopExpr. We can't do that.
10696       Info.FFDiag(E);
10697       return false;
10698     }
10699     return Success(Info.ArrayInitIndex, E);
10700   }
10701 
10702   // Note, GNU defines __null as an integer, not a pointer.
10703   bool VisitGNUNullExpr(const GNUNullExpr *E) {
10704     return ZeroInitialization(E);
10705   }
10706 
10707   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
10708     return Success(E->getValue(), E);
10709   }
10710 
10711   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
10712     return Success(E->getValue(), E);
10713   }
10714 
10715   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
10716     return Success(E->getValue(), E);
10717   }
10718 
10719   bool VisitUnaryReal(const UnaryOperator *E);
10720   bool VisitUnaryImag(const UnaryOperator *E);
10721 
10722   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
10723   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
10724   bool VisitSourceLocExpr(const SourceLocExpr *E);
10725   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
10726   bool VisitRequiresExpr(const RequiresExpr *E);
10727   // FIXME: Missing: array subscript of vector, member of vector
10728 };
10729 
10730 class FixedPointExprEvaluator
10731     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
10732   APValue &Result;
10733 
10734  public:
10735   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
10736       : ExprEvaluatorBaseTy(info), Result(result) {}
10737 
10738   bool Success(const llvm::APInt &I, const Expr *E) {
10739     return Success(
10740         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10741   }
10742 
10743   bool Success(uint64_t Value, const Expr *E) {
10744     return Success(
10745         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10746   }
10747 
10748   bool Success(const APValue &V, const Expr *E) {
10749     return Success(V.getFixedPoint(), E);
10750   }
10751 
10752   bool Success(const APFixedPoint &V, const Expr *E) {
10753     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
10754     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10755            "Invalid evaluation result.");
10756     Result = APValue(V);
10757     return true;
10758   }
10759 
10760   //===--------------------------------------------------------------------===//
10761   //                            Visitor Methods
10762   //===--------------------------------------------------------------------===//
10763 
10764   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
10765     return Success(E->getValue(), E);
10766   }
10767 
10768   bool VisitCastExpr(const CastExpr *E);
10769   bool VisitUnaryOperator(const UnaryOperator *E);
10770   bool VisitBinaryOperator(const BinaryOperator *E);
10771 };
10772 } // end anonymous namespace
10773 
10774 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
10775 /// produce either the integer value or a pointer.
10776 ///
10777 /// GCC has a heinous extension which folds casts between pointer types and
10778 /// pointer-sized integral types. We support this by allowing the evaluation of
10779 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
10780 /// Some simple arithmetic on such values is supported (they are treated much
10781 /// like char*).
10782 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
10783                                     EvalInfo &Info) {
10784   assert(!E->isValueDependent());
10785   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
10786   return IntExprEvaluator(Info, Result).Visit(E);
10787 }
10788 
10789 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
10790   assert(!E->isValueDependent());
10791   APValue Val;
10792   if (!EvaluateIntegerOrLValue(E, Val, Info))
10793     return false;
10794   if (!Val.isInt()) {
10795     // FIXME: It would be better to produce the diagnostic for casting
10796     //        a pointer to an integer.
10797     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10798     return false;
10799   }
10800   Result = Val.getInt();
10801   return true;
10802 }
10803 
10804 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
10805   APValue Evaluated = E->EvaluateInContext(
10806       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10807   return Success(Evaluated, E);
10808 }
10809 
10810 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
10811                                EvalInfo &Info) {
10812   assert(!E->isValueDependent());
10813   if (E->getType()->isFixedPointType()) {
10814     APValue Val;
10815     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
10816       return false;
10817     if (!Val.isFixedPoint())
10818       return false;
10819 
10820     Result = Val.getFixedPoint();
10821     return true;
10822   }
10823   return false;
10824 }
10825 
10826 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
10827                                         EvalInfo &Info) {
10828   assert(!E->isValueDependent());
10829   if (E->getType()->isIntegerType()) {
10830     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
10831     APSInt Val;
10832     if (!EvaluateInteger(E, Val, Info))
10833       return false;
10834     Result = APFixedPoint(Val, FXSema);
10835     return true;
10836   } else if (E->getType()->isFixedPointType()) {
10837     return EvaluateFixedPoint(E, Result, Info);
10838   }
10839   return false;
10840 }
10841 
10842 /// Check whether the given declaration can be directly converted to an integral
10843 /// rvalue. If not, no diagnostic is produced; there are other things we can
10844 /// try.
10845 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
10846   // Enums are integer constant exprs.
10847   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
10848     // Check for signedness/width mismatches between E type and ECD value.
10849     bool SameSign = (ECD->getInitVal().isSigned()
10850                      == E->getType()->isSignedIntegerOrEnumerationType());
10851     bool SameWidth = (ECD->getInitVal().getBitWidth()
10852                       == Info.Ctx.getIntWidth(E->getType()));
10853     if (SameSign && SameWidth)
10854       return Success(ECD->getInitVal(), E);
10855     else {
10856       // Get rid of mismatch (otherwise Success assertions will fail)
10857       // by computing a new value matching the type of E.
10858       llvm::APSInt Val = ECD->getInitVal();
10859       if (!SameSign)
10860         Val.setIsSigned(!ECD->getInitVal().isSigned());
10861       if (!SameWidth)
10862         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
10863       return Success(Val, E);
10864     }
10865   }
10866   return false;
10867 }
10868 
10869 /// Values returned by __builtin_classify_type, chosen to match the values
10870 /// produced by GCC's builtin.
10871 enum class GCCTypeClass {
10872   None = -1,
10873   Void = 0,
10874   Integer = 1,
10875   // GCC reserves 2 for character types, but instead classifies them as
10876   // integers.
10877   Enum = 3,
10878   Bool = 4,
10879   Pointer = 5,
10880   // GCC reserves 6 for references, but appears to never use it (because
10881   // expressions never have reference type, presumably).
10882   PointerToDataMember = 7,
10883   RealFloat = 8,
10884   Complex = 9,
10885   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
10886   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
10887   // GCC claims to reserve 11 for pointers to member functions, but *actually*
10888   // uses 12 for that purpose, same as for a class or struct. Maybe it
10889   // internally implements a pointer to member as a struct?  Who knows.
10890   PointerToMemberFunction = 12, // Not a bug, see above.
10891   ClassOrStruct = 12,
10892   Union = 13,
10893   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
10894   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
10895   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
10896   // literals.
10897 };
10898 
10899 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10900 /// as GCC.
10901 static GCCTypeClass
10902 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
10903   assert(!T->isDependentType() && "unexpected dependent type");
10904 
10905   QualType CanTy = T.getCanonicalType();
10906   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
10907 
10908   switch (CanTy->getTypeClass()) {
10909 #define TYPE(ID, BASE)
10910 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
10911 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
10912 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
10913 #include "clang/AST/TypeNodes.inc"
10914   case Type::Auto:
10915   case Type::DeducedTemplateSpecialization:
10916       llvm_unreachable("unexpected non-canonical or dependent type");
10917 
10918   case Type::Builtin:
10919     switch (BT->getKind()) {
10920 #define BUILTIN_TYPE(ID, SINGLETON_ID)
10921 #define SIGNED_TYPE(ID, SINGLETON_ID) \
10922     case BuiltinType::ID: return GCCTypeClass::Integer;
10923 #define FLOATING_TYPE(ID, SINGLETON_ID) \
10924     case BuiltinType::ID: return GCCTypeClass::RealFloat;
10925 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
10926     case BuiltinType::ID: break;
10927 #include "clang/AST/BuiltinTypes.def"
10928     case BuiltinType::Void:
10929       return GCCTypeClass::Void;
10930 
10931     case BuiltinType::Bool:
10932       return GCCTypeClass::Bool;
10933 
10934     case BuiltinType::Char_U:
10935     case BuiltinType::UChar:
10936     case BuiltinType::WChar_U:
10937     case BuiltinType::Char8:
10938     case BuiltinType::Char16:
10939     case BuiltinType::Char32:
10940     case BuiltinType::UShort:
10941     case BuiltinType::UInt:
10942     case BuiltinType::ULong:
10943     case BuiltinType::ULongLong:
10944     case BuiltinType::UInt128:
10945       return GCCTypeClass::Integer;
10946 
10947     case BuiltinType::UShortAccum:
10948     case BuiltinType::UAccum:
10949     case BuiltinType::ULongAccum:
10950     case BuiltinType::UShortFract:
10951     case BuiltinType::UFract:
10952     case BuiltinType::ULongFract:
10953     case BuiltinType::SatUShortAccum:
10954     case BuiltinType::SatUAccum:
10955     case BuiltinType::SatULongAccum:
10956     case BuiltinType::SatUShortFract:
10957     case BuiltinType::SatUFract:
10958     case BuiltinType::SatULongFract:
10959       return GCCTypeClass::None;
10960 
10961     case BuiltinType::NullPtr:
10962 
10963     case BuiltinType::ObjCId:
10964     case BuiltinType::ObjCClass:
10965     case BuiltinType::ObjCSel:
10966 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
10967     case BuiltinType::Id:
10968 #include "clang/Basic/OpenCLImageTypes.def"
10969 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
10970     case BuiltinType::Id:
10971 #include "clang/Basic/OpenCLExtensionTypes.def"
10972     case BuiltinType::OCLSampler:
10973     case BuiltinType::OCLEvent:
10974     case BuiltinType::OCLClkEvent:
10975     case BuiltinType::OCLQueue:
10976     case BuiltinType::OCLReserveID:
10977 #define SVE_TYPE(Name, Id, SingletonId) \
10978     case BuiltinType::Id:
10979 #include "clang/Basic/AArch64SVEACLETypes.def"
10980 #define PPC_VECTOR_TYPE(Name, Id, Size) \
10981     case BuiltinType::Id:
10982 #include "clang/Basic/PPCTypes.def"
10983       return GCCTypeClass::None;
10984 
10985     case BuiltinType::Dependent:
10986       llvm_unreachable("unexpected dependent type");
10987     };
10988     llvm_unreachable("unexpected placeholder type");
10989 
10990   case Type::Enum:
10991     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
10992 
10993   case Type::Pointer:
10994   case Type::ConstantArray:
10995   case Type::VariableArray:
10996   case Type::IncompleteArray:
10997   case Type::FunctionNoProto:
10998   case Type::FunctionProto:
10999     return GCCTypeClass::Pointer;
11000 
11001   case Type::MemberPointer:
11002     return CanTy->isMemberDataPointerType()
11003                ? GCCTypeClass::PointerToDataMember
11004                : GCCTypeClass::PointerToMemberFunction;
11005 
11006   case Type::Complex:
11007     return GCCTypeClass::Complex;
11008 
11009   case Type::Record:
11010     return CanTy->isUnionType() ? GCCTypeClass::Union
11011                                 : GCCTypeClass::ClassOrStruct;
11012 
11013   case Type::Atomic:
11014     // GCC classifies _Atomic T the same as T.
11015     return EvaluateBuiltinClassifyType(
11016         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11017 
11018   case Type::BlockPointer:
11019   case Type::Vector:
11020   case Type::ExtVector:
11021   case Type::ConstantMatrix:
11022   case Type::ObjCObject:
11023   case Type::ObjCInterface:
11024   case Type::ObjCObjectPointer:
11025   case Type::Pipe:
11026   case Type::ExtInt:
11027     // GCC classifies vectors as None. We follow its lead and classify all
11028     // other types that don't fit into the regular classification the same way.
11029     return GCCTypeClass::None;
11030 
11031   case Type::LValueReference:
11032   case Type::RValueReference:
11033     llvm_unreachable("invalid type for expression");
11034   }
11035 
11036   llvm_unreachable("unexpected type class");
11037 }
11038 
11039 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11040 /// as GCC.
11041 static GCCTypeClass
11042 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11043   // If no argument was supplied, default to None. This isn't
11044   // ideal, however it is what gcc does.
11045   if (E->getNumArgs() == 0)
11046     return GCCTypeClass::None;
11047 
11048   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11049   // being an ICE, but still folds it to a constant using the type of the first
11050   // argument.
11051   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11052 }
11053 
11054 /// EvaluateBuiltinConstantPForLValue - Determine the result of
11055 /// __builtin_constant_p when applied to the given pointer.
11056 ///
11057 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
11058 /// or it points to the first character of a string literal.
11059 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11060   APValue::LValueBase Base = LV.getLValueBase();
11061   if (Base.isNull()) {
11062     // A null base is acceptable.
11063     return true;
11064   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11065     if (!isa<StringLiteral>(E))
11066       return false;
11067     return LV.getLValueOffset().isZero();
11068   } else if (Base.is<TypeInfoLValue>()) {
11069     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11070     // evaluate to true.
11071     return true;
11072   } else {
11073     // Any other base is not constant enough for GCC.
11074     return false;
11075   }
11076 }
11077 
11078 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11079 /// GCC as we can manage.
11080 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11081   // This evaluation is not permitted to have side-effects, so evaluate it in
11082   // a speculative evaluation context.
11083   SpeculativeEvaluationRAII SpeculativeEval(Info);
11084 
11085   // Constant-folding is always enabled for the operand of __builtin_constant_p
11086   // (even when the enclosing evaluation context otherwise requires a strict
11087   // language-specific constant expression).
11088   FoldConstant Fold(Info, true);
11089 
11090   QualType ArgType = Arg->getType();
11091 
11092   // __builtin_constant_p always has one operand. The rules which gcc follows
11093   // are not precisely documented, but are as follows:
11094   //
11095   //  - If the operand is of integral, floating, complex or enumeration type,
11096   //    and can be folded to a known value of that type, it returns 1.
11097   //  - If the operand can be folded to a pointer to the first character
11098   //    of a string literal (or such a pointer cast to an integral type)
11099   //    or to a null pointer or an integer cast to a pointer, it returns 1.
11100   //
11101   // Otherwise, it returns 0.
11102   //
11103   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11104   // its support for this did not work prior to GCC 9 and is not yet well
11105   // understood.
11106   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11107       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11108       ArgType->isNullPtrType()) {
11109     APValue V;
11110     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11111       Fold.keepDiagnostics();
11112       return false;
11113     }
11114 
11115     // For a pointer (possibly cast to integer), there are special rules.
11116     if (V.getKind() == APValue::LValue)
11117       return EvaluateBuiltinConstantPForLValue(V);
11118 
11119     // Otherwise, any constant value is good enough.
11120     return V.hasValue();
11121   }
11122 
11123   // Anything else isn't considered to be sufficiently constant.
11124   return false;
11125 }
11126 
11127 /// Retrieves the "underlying object type" of the given expression,
11128 /// as used by __builtin_object_size.
11129 static QualType getObjectType(APValue::LValueBase B) {
11130   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11131     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11132       return VD->getType();
11133   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11134     if (isa<CompoundLiteralExpr>(E))
11135       return E->getType();
11136   } else if (B.is<TypeInfoLValue>()) {
11137     return B.getTypeInfoType();
11138   } else if (B.is<DynamicAllocLValue>()) {
11139     return B.getDynamicAllocType();
11140   }
11141 
11142   return QualType();
11143 }
11144 
11145 /// A more selective version of E->IgnoreParenCasts for
11146 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11147 /// to change the type of E.
11148 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11149 ///
11150 /// Always returns an RValue with a pointer representation.
11151 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11152   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
11153 
11154   auto *NoParens = E->IgnoreParens();
11155   auto *Cast = dyn_cast<CastExpr>(NoParens);
11156   if (Cast == nullptr)
11157     return NoParens;
11158 
11159   // We only conservatively allow a few kinds of casts, because this code is
11160   // inherently a simple solution that seeks to support the common case.
11161   auto CastKind = Cast->getCastKind();
11162   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11163       CastKind != CK_AddressSpaceConversion)
11164     return NoParens;
11165 
11166   auto *SubExpr = Cast->getSubExpr();
11167   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
11168     return NoParens;
11169   return ignorePointerCastsAndParens(SubExpr);
11170 }
11171 
11172 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11173 /// record layout. e.g.
11174 ///   struct { struct { int a, b; } fst, snd; } obj;
11175 ///   obj.fst   // no
11176 ///   obj.snd   // yes
11177 ///   obj.fst.a // no
11178 ///   obj.fst.b // no
11179 ///   obj.snd.a // no
11180 ///   obj.snd.b // yes
11181 ///
11182 /// Please note: this function is specialized for how __builtin_object_size
11183 /// views "objects".
11184 ///
11185 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11186 /// correct result, it will always return true.
11187 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11188   assert(!LVal.Designator.Invalid);
11189 
11190   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11191     const RecordDecl *Parent = FD->getParent();
11192     Invalid = Parent->isInvalidDecl();
11193     if (Invalid || Parent->isUnion())
11194       return true;
11195     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11196     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11197   };
11198 
11199   auto &Base = LVal.getLValueBase();
11200   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11201     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11202       bool Invalid;
11203       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11204         return Invalid;
11205     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11206       for (auto *FD : IFD->chain()) {
11207         bool Invalid;
11208         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11209           return Invalid;
11210       }
11211     }
11212   }
11213 
11214   unsigned I = 0;
11215   QualType BaseType = getType(Base);
11216   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11217     // If we don't know the array bound, conservatively assume we're looking at
11218     // the final array element.
11219     ++I;
11220     if (BaseType->isIncompleteArrayType())
11221       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11222     else
11223       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11224   }
11225 
11226   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11227     const auto &Entry = LVal.Designator.Entries[I];
11228     if (BaseType->isArrayType()) {
11229       // Because __builtin_object_size treats arrays as objects, we can ignore
11230       // the index iff this is the last array in the Designator.
11231       if (I + 1 == E)
11232         return true;
11233       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11234       uint64_t Index = Entry.getAsArrayIndex();
11235       if (Index + 1 != CAT->getSize())
11236         return false;
11237       BaseType = CAT->getElementType();
11238     } else if (BaseType->isAnyComplexType()) {
11239       const auto *CT = BaseType->castAs<ComplexType>();
11240       uint64_t Index = Entry.getAsArrayIndex();
11241       if (Index != 1)
11242         return false;
11243       BaseType = CT->getElementType();
11244     } else if (auto *FD = getAsField(Entry)) {
11245       bool Invalid;
11246       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11247         return Invalid;
11248       BaseType = FD->getType();
11249     } else {
11250       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11251       return false;
11252     }
11253   }
11254   return true;
11255 }
11256 
11257 /// Tests to see if the LValue has a user-specified designator (that isn't
11258 /// necessarily valid). Note that this always returns 'true' if the LValue has
11259 /// an unsized array as its first designator entry, because there's currently no
11260 /// way to tell if the user typed *foo or foo[0].
11261 static bool refersToCompleteObject(const LValue &LVal) {
11262   if (LVal.Designator.Invalid)
11263     return false;
11264 
11265   if (!LVal.Designator.Entries.empty())
11266     return LVal.Designator.isMostDerivedAnUnsizedArray();
11267 
11268   if (!LVal.InvalidBase)
11269     return true;
11270 
11271   // If `E` is a MemberExpr, then the first part of the designator is hiding in
11272   // the LValueBase.
11273   const auto *E = LVal.Base.dyn_cast<const Expr *>();
11274   return !E || !isa<MemberExpr>(E);
11275 }
11276 
11277 /// Attempts to detect a user writing into a piece of memory that's impossible
11278 /// to figure out the size of by just using types.
11279 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11280   const SubobjectDesignator &Designator = LVal.Designator;
11281   // Notes:
11282   // - Users can only write off of the end when we have an invalid base. Invalid
11283   //   bases imply we don't know where the memory came from.
11284   // - We used to be a bit more aggressive here; we'd only be conservative if
11285   //   the array at the end was flexible, or if it had 0 or 1 elements. This
11286   //   broke some common standard library extensions (PR30346), but was
11287   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
11288   //   with some sort of list. OTOH, it seems that GCC is always
11289   //   conservative with the last element in structs (if it's an array), so our
11290   //   current behavior is more compatible than an explicit list approach would
11291   //   be.
11292   return LVal.InvalidBase &&
11293          Designator.Entries.size() == Designator.MostDerivedPathLength &&
11294          Designator.MostDerivedIsArrayElement &&
11295          isDesignatorAtObjectEnd(Ctx, LVal);
11296 }
11297 
11298 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11299 /// Fails if the conversion would cause loss of precision.
11300 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11301                                             CharUnits &Result) {
11302   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11303   if (Int.ugt(CharUnitsMax))
11304     return false;
11305   Result = CharUnits::fromQuantity(Int.getZExtValue());
11306   return true;
11307 }
11308 
11309 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11310 /// determine how many bytes exist from the beginning of the object to either
11311 /// the end of the current subobject, or the end of the object itself, depending
11312 /// on what the LValue looks like + the value of Type.
11313 ///
11314 /// If this returns false, the value of Result is undefined.
11315 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11316                                unsigned Type, const LValue &LVal,
11317                                CharUnits &EndOffset) {
11318   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11319 
11320   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11321     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11322       return false;
11323     return HandleSizeof(Info, ExprLoc, Ty, Result);
11324   };
11325 
11326   // We want to evaluate the size of the entire object. This is a valid fallback
11327   // for when Type=1 and the designator is invalid, because we're asked for an
11328   // upper-bound.
11329   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11330     // Type=3 wants a lower bound, so we can't fall back to this.
11331     if (Type == 3 && !DetermineForCompleteObject)
11332       return false;
11333 
11334     llvm::APInt APEndOffset;
11335     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11336         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11337       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11338 
11339     if (LVal.InvalidBase)
11340       return false;
11341 
11342     QualType BaseTy = getObjectType(LVal.getLValueBase());
11343     return CheckedHandleSizeof(BaseTy, EndOffset);
11344   }
11345 
11346   // We want to evaluate the size of a subobject.
11347   const SubobjectDesignator &Designator = LVal.Designator;
11348 
11349   // The following is a moderately common idiom in C:
11350   //
11351   // struct Foo { int a; char c[1]; };
11352   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11353   // strcpy(&F->c[0], Bar);
11354   //
11355   // In order to not break too much legacy code, we need to support it.
11356   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11357     // If we can resolve this to an alloc_size call, we can hand that back,
11358     // because we know for certain how many bytes there are to write to.
11359     llvm::APInt APEndOffset;
11360     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11361         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11362       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11363 
11364     // If we cannot determine the size of the initial allocation, then we can't
11365     // given an accurate upper-bound. However, we are still able to give
11366     // conservative lower-bounds for Type=3.
11367     if (Type == 1)
11368       return false;
11369   }
11370 
11371   CharUnits BytesPerElem;
11372   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11373     return false;
11374 
11375   // According to the GCC documentation, we want the size of the subobject
11376   // denoted by the pointer. But that's not quite right -- what we actually
11377   // want is the size of the immediately-enclosing array, if there is one.
11378   int64_t ElemsRemaining;
11379   if (Designator.MostDerivedIsArrayElement &&
11380       Designator.Entries.size() == Designator.MostDerivedPathLength) {
11381     uint64_t ArraySize = Designator.getMostDerivedArraySize();
11382     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11383     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11384   } else {
11385     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11386   }
11387 
11388   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11389   return true;
11390 }
11391 
11392 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11393 /// returns true and stores the result in @p Size.
11394 ///
11395 /// If @p WasError is non-null, this will report whether the failure to evaluate
11396 /// is to be treated as an Error in IntExprEvaluator.
11397 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11398                                          EvalInfo &Info, uint64_t &Size) {
11399   // Determine the denoted object.
11400   LValue LVal;
11401   {
11402     // The operand of __builtin_object_size is never evaluated for side-effects.
11403     // If there are any, but we can determine the pointed-to object anyway, then
11404     // ignore the side-effects.
11405     SpeculativeEvaluationRAII SpeculativeEval(Info);
11406     IgnoreSideEffectsRAII Fold(Info);
11407 
11408     if (E->isGLValue()) {
11409       // It's possible for us to be given GLValues if we're called via
11410       // Expr::tryEvaluateObjectSize.
11411       APValue RVal;
11412       if (!EvaluateAsRValue(Info, E, RVal))
11413         return false;
11414       LVal.setFrom(Info.Ctx, RVal);
11415     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11416                                 /*InvalidBaseOK=*/true))
11417       return false;
11418   }
11419 
11420   // If we point to before the start of the object, there are no accessible
11421   // bytes.
11422   if (LVal.getLValueOffset().isNegative()) {
11423     Size = 0;
11424     return true;
11425   }
11426 
11427   CharUnits EndOffset;
11428   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11429     return false;
11430 
11431   // If we've fallen outside of the end offset, just pretend there's nothing to
11432   // write to/read from.
11433   if (EndOffset <= LVal.getLValueOffset())
11434     Size = 0;
11435   else
11436     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11437   return true;
11438 }
11439 
11440 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11441   if (unsigned BuiltinOp = E->getBuiltinCallee())
11442     return VisitBuiltinCallExpr(E, BuiltinOp);
11443 
11444   return ExprEvaluatorBaseTy::VisitCallExpr(E);
11445 }
11446 
11447 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11448                                      APValue &Val, APSInt &Alignment) {
11449   QualType SrcTy = E->getArg(0)->getType();
11450   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11451     return false;
11452   // Even though we are evaluating integer expressions we could get a pointer
11453   // argument for the __builtin_is_aligned() case.
11454   if (SrcTy->isPointerType()) {
11455     LValue Ptr;
11456     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11457       return false;
11458     Ptr.moveInto(Val);
11459   } else if (!SrcTy->isIntegralOrEnumerationType()) {
11460     Info.FFDiag(E->getArg(0));
11461     return false;
11462   } else {
11463     APSInt SrcInt;
11464     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11465       return false;
11466     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11467            "Bit widths must be the same");
11468     Val = APValue(SrcInt);
11469   }
11470   assert(Val.hasValue());
11471   return true;
11472 }
11473 
11474 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11475                                             unsigned BuiltinOp) {
11476   switch (BuiltinOp) {
11477   default:
11478     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11479 
11480   case Builtin::BI__builtin_dynamic_object_size:
11481   case Builtin::BI__builtin_object_size: {
11482     // The type was checked when we built the expression.
11483     unsigned Type =
11484         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11485     assert(Type <= 3 && "unexpected type");
11486 
11487     uint64_t Size;
11488     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11489       return Success(Size, E);
11490 
11491     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11492       return Success((Type & 2) ? 0 : -1, E);
11493 
11494     // Expression had no side effects, but we couldn't statically determine the
11495     // size of the referenced object.
11496     switch (Info.EvalMode) {
11497     case EvalInfo::EM_ConstantExpression:
11498     case EvalInfo::EM_ConstantFold:
11499     case EvalInfo::EM_IgnoreSideEffects:
11500       // Leave it to IR generation.
11501       return Error(E);
11502     case EvalInfo::EM_ConstantExpressionUnevaluated:
11503       // Reduce it to a constant now.
11504       return Success((Type & 2) ? 0 : -1, E);
11505     }
11506 
11507     llvm_unreachable("unexpected EvalMode");
11508   }
11509 
11510   case Builtin::BI__builtin_os_log_format_buffer_size: {
11511     analyze_os_log::OSLogBufferLayout Layout;
11512     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11513     return Success(Layout.size().getQuantity(), E);
11514   }
11515 
11516   case Builtin::BI__builtin_is_aligned: {
11517     APValue Src;
11518     APSInt Alignment;
11519     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11520       return false;
11521     if (Src.isLValue()) {
11522       // If we evaluated a pointer, check the minimum known alignment.
11523       LValue Ptr;
11524       Ptr.setFrom(Info.Ctx, Src);
11525       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11526       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11527       // We can return true if the known alignment at the computed offset is
11528       // greater than the requested alignment.
11529       assert(PtrAlign.isPowerOfTwo());
11530       assert(Alignment.isPowerOf2());
11531       if (PtrAlign.getQuantity() >= Alignment)
11532         return Success(1, E);
11533       // If the alignment is not known to be sufficient, some cases could still
11534       // be aligned at run time. However, if the requested alignment is less or
11535       // equal to the base alignment and the offset is not aligned, we know that
11536       // the run-time value can never be aligned.
11537       if (BaseAlignment.getQuantity() >= Alignment &&
11538           PtrAlign.getQuantity() < Alignment)
11539         return Success(0, E);
11540       // Otherwise we can't infer whether the value is sufficiently aligned.
11541       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11542       //  in cases where we can't fully evaluate the pointer.
11543       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11544           << Alignment;
11545       return false;
11546     }
11547     assert(Src.isInt());
11548     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11549   }
11550   case Builtin::BI__builtin_align_up: {
11551     APValue Src;
11552     APSInt Alignment;
11553     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11554       return false;
11555     if (!Src.isInt())
11556       return Error(E);
11557     APSInt AlignedVal =
11558         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11559                Src.getInt().isUnsigned());
11560     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11561     return Success(AlignedVal, E);
11562   }
11563   case Builtin::BI__builtin_align_down: {
11564     APValue Src;
11565     APSInt Alignment;
11566     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11567       return false;
11568     if (!Src.isInt())
11569       return Error(E);
11570     APSInt AlignedVal =
11571         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11572     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11573     return Success(AlignedVal, E);
11574   }
11575 
11576   case Builtin::BI__builtin_bitreverse8:
11577   case Builtin::BI__builtin_bitreverse16:
11578   case Builtin::BI__builtin_bitreverse32:
11579   case Builtin::BI__builtin_bitreverse64: {
11580     APSInt Val;
11581     if (!EvaluateInteger(E->getArg(0), Val, Info))
11582       return false;
11583 
11584     return Success(Val.reverseBits(), E);
11585   }
11586 
11587   case Builtin::BI__builtin_bswap16:
11588   case Builtin::BI__builtin_bswap32:
11589   case Builtin::BI__builtin_bswap64: {
11590     APSInt Val;
11591     if (!EvaluateInteger(E->getArg(0), Val, Info))
11592       return false;
11593 
11594     return Success(Val.byteSwap(), E);
11595   }
11596 
11597   case Builtin::BI__builtin_classify_type:
11598     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11599 
11600   case Builtin::BI__builtin_clrsb:
11601   case Builtin::BI__builtin_clrsbl:
11602   case Builtin::BI__builtin_clrsbll: {
11603     APSInt Val;
11604     if (!EvaluateInteger(E->getArg(0), Val, Info))
11605       return false;
11606 
11607     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11608   }
11609 
11610   case Builtin::BI__builtin_clz:
11611   case Builtin::BI__builtin_clzl:
11612   case Builtin::BI__builtin_clzll:
11613   case Builtin::BI__builtin_clzs: {
11614     APSInt Val;
11615     if (!EvaluateInteger(E->getArg(0), Val, Info))
11616       return false;
11617     if (!Val)
11618       return Error(E);
11619 
11620     return Success(Val.countLeadingZeros(), E);
11621   }
11622 
11623   case Builtin::BI__builtin_constant_p: {
11624     const Expr *Arg = E->getArg(0);
11625     if (EvaluateBuiltinConstantP(Info, Arg))
11626       return Success(true, E);
11627     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11628       // Outside a constant context, eagerly evaluate to false in the presence
11629       // of side-effects in order to avoid -Wunsequenced false-positives in
11630       // a branch on __builtin_constant_p(expr).
11631       return Success(false, E);
11632     }
11633     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11634     return false;
11635   }
11636 
11637   case Builtin::BI__builtin_is_constant_evaluated: {
11638     const auto *Callee = Info.CurrentCall->getCallee();
11639     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
11640         (Info.CallStackDepth == 1 ||
11641          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
11642           Callee->getIdentifier() &&
11643           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
11644       // FIXME: Find a better way to avoid duplicated diagnostics.
11645       if (Info.EvalStatus.Diag)
11646         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
11647                                                : Info.CurrentCall->CallLoc,
11648                     diag::warn_is_constant_evaluated_always_true_constexpr)
11649             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
11650                                          : "std::is_constant_evaluated");
11651     }
11652 
11653     return Success(Info.InConstantContext, E);
11654   }
11655 
11656   case Builtin::BI__builtin_ctz:
11657   case Builtin::BI__builtin_ctzl:
11658   case Builtin::BI__builtin_ctzll:
11659   case Builtin::BI__builtin_ctzs: {
11660     APSInt Val;
11661     if (!EvaluateInteger(E->getArg(0), Val, Info))
11662       return false;
11663     if (!Val)
11664       return Error(E);
11665 
11666     return Success(Val.countTrailingZeros(), E);
11667   }
11668 
11669   case Builtin::BI__builtin_eh_return_data_regno: {
11670     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11671     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
11672     return Success(Operand, E);
11673   }
11674 
11675   case Builtin::BI__builtin_expect:
11676   case Builtin::BI__builtin_expect_with_probability:
11677     return Visit(E->getArg(0));
11678 
11679   case Builtin::BI__builtin_ffs:
11680   case Builtin::BI__builtin_ffsl:
11681   case Builtin::BI__builtin_ffsll: {
11682     APSInt Val;
11683     if (!EvaluateInteger(E->getArg(0), Val, Info))
11684       return false;
11685 
11686     unsigned N = Val.countTrailingZeros();
11687     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
11688   }
11689 
11690   case Builtin::BI__builtin_fpclassify: {
11691     APFloat Val(0.0);
11692     if (!EvaluateFloat(E->getArg(5), Val, Info))
11693       return false;
11694     unsigned Arg;
11695     switch (Val.getCategory()) {
11696     case APFloat::fcNaN: Arg = 0; break;
11697     case APFloat::fcInfinity: Arg = 1; break;
11698     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
11699     case APFloat::fcZero: Arg = 4; break;
11700     }
11701     return Visit(E->getArg(Arg));
11702   }
11703 
11704   case Builtin::BI__builtin_isinf_sign: {
11705     APFloat Val(0.0);
11706     return EvaluateFloat(E->getArg(0), Val, Info) &&
11707            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
11708   }
11709 
11710   case Builtin::BI__builtin_isinf: {
11711     APFloat Val(0.0);
11712     return EvaluateFloat(E->getArg(0), Val, Info) &&
11713            Success(Val.isInfinity() ? 1 : 0, E);
11714   }
11715 
11716   case Builtin::BI__builtin_isfinite: {
11717     APFloat Val(0.0);
11718     return EvaluateFloat(E->getArg(0), Val, Info) &&
11719            Success(Val.isFinite() ? 1 : 0, E);
11720   }
11721 
11722   case Builtin::BI__builtin_isnan: {
11723     APFloat Val(0.0);
11724     return EvaluateFloat(E->getArg(0), Val, Info) &&
11725            Success(Val.isNaN() ? 1 : 0, E);
11726   }
11727 
11728   case Builtin::BI__builtin_isnormal: {
11729     APFloat Val(0.0);
11730     return EvaluateFloat(E->getArg(0), Val, Info) &&
11731            Success(Val.isNormal() ? 1 : 0, E);
11732   }
11733 
11734   case Builtin::BI__builtin_parity:
11735   case Builtin::BI__builtin_parityl:
11736   case Builtin::BI__builtin_parityll: {
11737     APSInt Val;
11738     if (!EvaluateInteger(E->getArg(0), Val, Info))
11739       return false;
11740 
11741     return Success(Val.countPopulation() % 2, E);
11742   }
11743 
11744   case Builtin::BI__builtin_popcount:
11745   case Builtin::BI__builtin_popcountl:
11746   case Builtin::BI__builtin_popcountll: {
11747     APSInt Val;
11748     if (!EvaluateInteger(E->getArg(0), Val, Info))
11749       return false;
11750 
11751     return Success(Val.countPopulation(), E);
11752   }
11753 
11754   case Builtin::BI__builtin_rotateleft8:
11755   case Builtin::BI__builtin_rotateleft16:
11756   case Builtin::BI__builtin_rotateleft32:
11757   case Builtin::BI__builtin_rotateleft64:
11758   case Builtin::BI_rotl8: // Microsoft variants of rotate right
11759   case Builtin::BI_rotl16:
11760   case Builtin::BI_rotl:
11761   case Builtin::BI_lrotl:
11762   case Builtin::BI_rotl64: {
11763     APSInt Val, Amt;
11764     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11765         !EvaluateInteger(E->getArg(1), Amt, Info))
11766       return false;
11767 
11768     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
11769   }
11770 
11771   case Builtin::BI__builtin_rotateright8:
11772   case Builtin::BI__builtin_rotateright16:
11773   case Builtin::BI__builtin_rotateright32:
11774   case Builtin::BI__builtin_rotateright64:
11775   case Builtin::BI_rotr8: // Microsoft variants of rotate right
11776   case Builtin::BI_rotr16:
11777   case Builtin::BI_rotr:
11778   case Builtin::BI_lrotr:
11779   case Builtin::BI_rotr64: {
11780     APSInt Val, Amt;
11781     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11782         !EvaluateInteger(E->getArg(1), Amt, Info))
11783       return false;
11784 
11785     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
11786   }
11787 
11788   case Builtin::BIstrlen:
11789   case Builtin::BIwcslen:
11790     // A call to strlen is not a constant expression.
11791     if (Info.getLangOpts().CPlusPlus11)
11792       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11793         << /*isConstexpr*/0 << /*isConstructor*/0
11794         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11795     else
11796       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11797     LLVM_FALLTHROUGH;
11798   case Builtin::BI__builtin_strlen:
11799   case Builtin::BI__builtin_wcslen: {
11800     // As an extension, we support __builtin_strlen() as a constant expression,
11801     // and support folding strlen() to a constant.
11802     LValue String;
11803     if (!EvaluatePointer(E->getArg(0), String, Info))
11804       return false;
11805 
11806     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
11807 
11808     // Fast path: if it's a string literal, search the string value.
11809     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
11810             String.getLValueBase().dyn_cast<const Expr *>())) {
11811       // The string literal may have embedded null characters. Find the first
11812       // one and truncate there.
11813       StringRef Str = S->getBytes();
11814       int64_t Off = String.Offset.getQuantity();
11815       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
11816           S->getCharByteWidth() == 1 &&
11817           // FIXME: Add fast-path for wchar_t too.
11818           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
11819         Str = Str.substr(Off);
11820 
11821         StringRef::size_type Pos = Str.find(0);
11822         if (Pos != StringRef::npos)
11823           Str = Str.substr(0, Pos);
11824 
11825         return Success(Str.size(), E);
11826       }
11827 
11828       // Fall through to slow path to issue appropriate diagnostic.
11829     }
11830 
11831     // Slow path: scan the bytes of the string looking for the terminating 0.
11832     for (uint64_t Strlen = 0; /**/; ++Strlen) {
11833       APValue Char;
11834       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
11835           !Char.isInt())
11836         return false;
11837       if (!Char.getInt())
11838         return Success(Strlen, E);
11839       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
11840         return false;
11841     }
11842   }
11843 
11844   case Builtin::BIstrcmp:
11845   case Builtin::BIwcscmp:
11846   case Builtin::BIstrncmp:
11847   case Builtin::BIwcsncmp:
11848   case Builtin::BImemcmp:
11849   case Builtin::BIbcmp:
11850   case Builtin::BIwmemcmp:
11851     // A call to strlen is not a constant expression.
11852     if (Info.getLangOpts().CPlusPlus11)
11853       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11854         << /*isConstexpr*/0 << /*isConstructor*/0
11855         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11856     else
11857       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11858     LLVM_FALLTHROUGH;
11859   case Builtin::BI__builtin_strcmp:
11860   case Builtin::BI__builtin_wcscmp:
11861   case Builtin::BI__builtin_strncmp:
11862   case Builtin::BI__builtin_wcsncmp:
11863   case Builtin::BI__builtin_memcmp:
11864   case Builtin::BI__builtin_bcmp:
11865   case Builtin::BI__builtin_wmemcmp: {
11866     LValue String1, String2;
11867     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
11868         !EvaluatePointer(E->getArg(1), String2, Info))
11869       return false;
11870 
11871     uint64_t MaxLength = uint64_t(-1);
11872     if (BuiltinOp != Builtin::BIstrcmp &&
11873         BuiltinOp != Builtin::BIwcscmp &&
11874         BuiltinOp != Builtin::BI__builtin_strcmp &&
11875         BuiltinOp != Builtin::BI__builtin_wcscmp) {
11876       APSInt N;
11877       if (!EvaluateInteger(E->getArg(2), N, Info))
11878         return false;
11879       MaxLength = N.getExtValue();
11880     }
11881 
11882     // Empty substrings compare equal by definition.
11883     if (MaxLength == 0u)
11884       return Success(0, E);
11885 
11886     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11887         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11888         String1.Designator.Invalid || String2.Designator.Invalid)
11889       return false;
11890 
11891     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
11892     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
11893 
11894     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
11895                      BuiltinOp == Builtin::BIbcmp ||
11896                      BuiltinOp == Builtin::BI__builtin_memcmp ||
11897                      BuiltinOp == Builtin::BI__builtin_bcmp;
11898 
11899     assert(IsRawByte ||
11900            (Info.Ctx.hasSameUnqualifiedType(
11901                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
11902             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
11903 
11904     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
11905     // 'char8_t', but no other types.
11906     if (IsRawByte &&
11907         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
11908       // FIXME: Consider using our bit_cast implementation to support this.
11909       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
11910           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
11911           << CharTy1 << CharTy2;
11912       return false;
11913     }
11914 
11915     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
11916       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
11917              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
11918              Char1.isInt() && Char2.isInt();
11919     };
11920     const auto &AdvanceElems = [&] {
11921       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
11922              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
11923     };
11924 
11925     bool StopAtNull =
11926         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
11927          BuiltinOp != Builtin::BIwmemcmp &&
11928          BuiltinOp != Builtin::BI__builtin_memcmp &&
11929          BuiltinOp != Builtin::BI__builtin_bcmp &&
11930          BuiltinOp != Builtin::BI__builtin_wmemcmp);
11931     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
11932                   BuiltinOp == Builtin::BIwcsncmp ||
11933                   BuiltinOp == Builtin::BIwmemcmp ||
11934                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
11935                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
11936                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
11937 
11938     for (; MaxLength; --MaxLength) {
11939       APValue Char1, Char2;
11940       if (!ReadCurElems(Char1, Char2))
11941         return false;
11942       if (Char1.getInt().ne(Char2.getInt())) {
11943         if (IsWide) // wmemcmp compares with wchar_t signedness.
11944           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
11945         // memcmp always compares unsigned chars.
11946         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
11947       }
11948       if (StopAtNull && !Char1.getInt())
11949         return Success(0, E);
11950       assert(!(StopAtNull && !Char2.getInt()));
11951       if (!AdvanceElems())
11952         return false;
11953     }
11954     // We hit the strncmp / memcmp limit.
11955     return Success(0, E);
11956   }
11957 
11958   case Builtin::BI__atomic_always_lock_free:
11959   case Builtin::BI__atomic_is_lock_free:
11960   case Builtin::BI__c11_atomic_is_lock_free: {
11961     APSInt SizeVal;
11962     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
11963       return false;
11964 
11965     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
11966     // of two less than or equal to the maximum inline atomic width, we know it
11967     // is lock-free.  If the size isn't a power of two, or greater than the
11968     // maximum alignment where we promote atomics, we know it is not lock-free
11969     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
11970     // the answer can only be determined at runtime; for example, 16-byte
11971     // atomics have lock-free implementations on some, but not all,
11972     // x86-64 processors.
11973 
11974     // Check power-of-two.
11975     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
11976     if (Size.isPowerOfTwo()) {
11977       // Check against inlining width.
11978       unsigned InlineWidthBits =
11979           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
11980       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
11981         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
11982             Size == CharUnits::One() ||
11983             E->getArg(1)->isNullPointerConstant(Info.Ctx,
11984                                                 Expr::NPC_NeverValueDependent))
11985           // OK, we will inline appropriately-aligned operations of this size,
11986           // and _Atomic(T) is appropriately-aligned.
11987           return Success(1, E);
11988 
11989         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
11990           castAs<PointerType>()->getPointeeType();
11991         if (!PointeeType->isIncompleteType() &&
11992             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
11993           // OK, we will inline operations on this object.
11994           return Success(1, E);
11995         }
11996       }
11997     }
11998 
11999     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12000         Success(0, E) : Error(E);
12001   }
12002   case Builtin::BIomp_is_initial_device:
12003     // We can decide statically which value the runtime would return if called.
12004     return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
12005   case Builtin::BI__builtin_add_overflow:
12006   case Builtin::BI__builtin_sub_overflow:
12007   case Builtin::BI__builtin_mul_overflow:
12008   case Builtin::BI__builtin_sadd_overflow:
12009   case Builtin::BI__builtin_uadd_overflow:
12010   case Builtin::BI__builtin_uaddl_overflow:
12011   case Builtin::BI__builtin_uaddll_overflow:
12012   case Builtin::BI__builtin_usub_overflow:
12013   case Builtin::BI__builtin_usubl_overflow:
12014   case Builtin::BI__builtin_usubll_overflow:
12015   case Builtin::BI__builtin_umul_overflow:
12016   case Builtin::BI__builtin_umull_overflow:
12017   case Builtin::BI__builtin_umulll_overflow:
12018   case Builtin::BI__builtin_saddl_overflow:
12019   case Builtin::BI__builtin_saddll_overflow:
12020   case Builtin::BI__builtin_ssub_overflow:
12021   case Builtin::BI__builtin_ssubl_overflow:
12022   case Builtin::BI__builtin_ssubll_overflow:
12023   case Builtin::BI__builtin_smul_overflow:
12024   case Builtin::BI__builtin_smull_overflow:
12025   case Builtin::BI__builtin_smulll_overflow: {
12026     LValue ResultLValue;
12027     APSInt LHS, RHS;
12028 
12029     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12030     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12031         !EvaluateInteger(E->getArg(1), RHS, Info) ||
12032         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12033       return false;
12034 
12035     APSInt Result;
12036     bool DidOverflow = false;
12037 
12038     // If the types don't have to match, enlarge all 3 to the largest of them.
12039     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12040         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12041         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12042       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12043                       ResultType->isSignedIntegerOrEnumerationType();
12044       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12045                       ResultType->isSignedIntegerOrEnumerationType();
12046       uint64_t LHSSize = LHS.getBitWidth();
12047       uint64_t RHSSize = RHS.getBitWidth();
12048       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12049       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12050 
12051       // Add an additional bit if the signedness isn't uniformly agreed to. We
12052       // could do this ONLY if there is a signed and an unsigned that both have
12053       // MaxBits, but the code to check that is pretty nasty.  The issue will be
12054       // caught in the shrink-to-result later anyway.
12055       if (IsSigned && !AllSigned)
12056         ++MaxBits;
12057 
12058       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12059       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12060       Result = APSInt(MaxBits, !IsSigned);
12061     }
12062 
12063     // Find largest int.
12064     switch (BuiltinOp) {
12065     default:
12066       llvm_unreachable("Invalid value for BuiltinOp");
12067     case Builtin::BI__builtin_add_overflow:
12068     case Builtin::BI__builtin_sadd_overflow:
12069     case Builtin::BI__builtin_saddl_overflow:
12070     case Builtin::BI__builtin_saddll_overflow:
12071     case Builtin::BI__builtin_uadd_overflow:
12072     case Builtin::BI__builtin_uaddl_overflow:
12073     case Builtin::BI__builtin_uaddll_overflow:
12074       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12075                               : LHS.uadd_ov(RHS, DidOverflow);
12076       break;
12077     case Builtin::BI__builtin_sub_overflow:
12078     case Builtin::BI__builtin_ssub_overflow:
12079     case Builtin::BI__builtin_ssubl_overflow:
12080     case Builtin::BI__builtin_ssubll_overflow:
12081     case Builtin::BI__builtin_usub_overflow:
12082     case Builtin::BI__builtin_usubl_overflow:
12083     case Builtin::BI__builtin_usubll_overflow:
12084       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12085                               : LHS.usub_ov(RHS, DidOverflow);
12086       break;
12087     case Builtin::BI__builtin_mul_overflow:
12088     case Builtin::BI__builtin_smul_overflow:
12089     case Builtin::BI__builtin_smull_overflow:
12090     case Builtin::BI__builtin_smulll_overflow:
12091     case Builtin::BI__builtin_umul_overflow:
12092     case Builtin::BI__builtin_umull_overflow:
12093     case Builtin::BI__builtin_umulll_overflow:
12094       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12095                               : LHS.umul_ov(RHS, DidOverflow);
12096       break;
12097     }
12098 
12099     // In the case where multiple sizes are allowed, truncate and see if
12100     // the values are the same.
12101     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12102         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12103         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12104       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12105       // since it will give us the behavior of a TruncOrSelf in the case where
12106       // its parameter <= its size.  We previously set Result to be at least the
12107       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12108       // will work exactly like TruncOrSelf.
12109       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12110       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12111 
12112       if (!APSInt::isSameValue(Temp, Result))
12113         DidOverflow = true;
12114       Result = Temp;
12115     }
12116 
12117     APValue APV{Result};
12118     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12119       return false;
12120     return Success(DidOverflow, E);
12121   }
12122   }
12123 }
12124 
12125 /// Determine whether this is a pointer past the end of the complete
12126 /// object referred to by the lvalue.
12127 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12128                                             const LValue &LV) {
12129   // A null pointer can be viewed as being "past the end" but we don't
12130   // choose to look at it that way here.
12131   if (!LV.getLValueBase())
12132     return false;
12133 
12134   // If the designator is valid and refers to a subobject, we're not pointing
12135   // past the end.
12136   if (!LV.getLValueDesignator().Invalid &&
12137       !LV.getLValueDesignator().isOnePastTheEnd())
12138     return false;
12139 
12140   // A pointer to an incomplete type might be past-the-end if the type's size is
12141   // zero.  We cannot tell because the type is incomplete.
12142   QualType Ty = getType(LV.getLValueBase());
12143   if (Ty->isIncompleteType())
12144     return true;
12145 
12146   // We're a past-the-end pointer if we point to the byte after the object,
12147   // no matter what our type or path is.
12148   auto Size = Ctx.getTypeSizeInChars(Ty);
12149   return LV.getLValueOffset() == Size;
12150 }
12151 
12152 namespace {
12153 
12154 /// Data recursive integer evaluator of certain binary operators.
12155 ///
12156 /// We use a data recursive algorithm for binary operators so that we are able
12157 /// to handle extreme cases of chained binary operators without causing stack
12158 /// overflow.
12159 class DataRecursiveIntBinOpEvaluator {
12160   struct EvalResult {
12161     APValue Val;
12162     bool Failed;
12163 
12164     EvalResult() : Failed(false) { }
12165 
12166     void swap(EvalResult &RHS) {
12167       Val.swap(RHS.Val);
12168       Failed = RHS.Failed;
12169       RHS.Failed = false;
12170     }
12171   };
12172 
12173   struct Job {
12174     const Expr *E;
12175     EvalResult LHSResult; // meaningful only for binary operator expression.
12176     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12177 
12178     Job() = default;
12179     Job(Job &&) = default;
12180 
12181     void startSpeculativeEval(EvalInfo &Info) {
12182       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12183     }
12184 
12185   private:
12186     SpeculativeEvaluationRAII SpecEvalRAII;
12187   };
12188 
12189   SmallVector<Job, 16> Queue;
12190 
12191   IntExprEvaluator &IntEval;
12192   EvalInfo &Info;
12193   APValue &FinalResult;
12194 
12195 public:
12196   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12197     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12198 
12199   /// True if \param E is a binary operator that we are going to handle
12200   /// data recursively.
12201   /// We handle binary operators that are comma, logical, or that have operands
12202   /// with integral or enumeration type.
12203   static bool shouldEnqueue(const BinaryOperator *E) {
12204     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12205            (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
12206             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12207             E->getRHS()->getType()->isIntegralOrEnumerationType());
12208   }
12209 
12210   bool Traverse(const BinaryOperator *E) {
12211     enqueue(E);
12212     EvalResult PrevResult;
12213     while (!Queue.empty())
12214       process(PrevResult);
12215 
12216     if (PrevResult.Failed) return false;
12217 
12218     FinalResult.swap(PrevResult.Val);
12219     return true;
12220   }
12221 
12222 private:
12223   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12224     return IntEval.Success(Value, E, Result);
12225   }
12226   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12227     return IntEval.Success(Value, E, Result);
12228   }
12229   bool Error(const Expr *E) {
12230     return IntEval.Error(E);
12231   }
12232   bool Error(const Expr *E, diag::kind D) {
12233     return IntEval.Error(E, D);
12234   }
12235 
12236   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12237     return Info.CCEDiag(E, D);
12238   }
12239 
12240   // Returns true if visiting the RHS is necessary, false otherwise.
12241   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12242                          bool &SuppressRHSDiags);
12243 
12244   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12245                   const BinaryOperator *E, APValue &Result);
12246 
12247   void EvaluateExpr(const Expr *E, EvalResult &Result) {
12248     Result.Failed = !Evaluate(Result.Val, Info, E);
12249     if (Result.Failed)
12250       Result.Val = APValue();
12251   }
12252 
12253   void process(EvalResult &Result);
12254 
12255   void enqueue(const Expr *E) {
12256     E = E->IgnoreParens();
12257     Queue.resize(Queue.size()+1);
12258     Queue.back().E = E;
12259     Queue.back().Kind = Job::AnyExprKind;
12260   }
12261 };
12262 
12263 }
12264 
12265 bool DataRecursiveIntBinOpEvaluator::
12266        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12267                          bool &SuppressRHSDiags) {
12268   if (E->getOpcode() == BO_Comma) {
12269     // Ignore LHS but note if we could not evaluate it.
12270     if (LHSResult.Failed)
12271       return Info.noteSideEffect();
12272     return true;
12273   }
12274 
12275   if (E->isLogicalOp()) {
12276     bool LHSAsBool;
12277     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12278       // We were able to evaluate the LHS, see if we can get away with not
12279       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12280       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12281         Success(LHSAsBool, E, LHSResult.Val);
12282         return false; // Ignore RHS
12283       }
12284     } else {
12285       LHSResult.Failed = true;
12286 
12287       // Since we weren't able to evaluate the left hand side, it
12288       // might have had side effects.
12289       if (!Info.noteSideEffect())
12290         return false;
12291 
12292       // We can't evaluate the LHS; however, sometimes the result
12293       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12294       // Don't ignore RHS and suppress diagnostics from this arm.
12295       SuppressRHSDiags = true;
12296     }
12297 
12298     return true;
12299   }
12300 
12301   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12302          E->getRHS()->getType()->isIntegralOrEnumerationType());
12303 
12304   if (LHSResult.Failed && !Info.noteFailure())
12305     return false; // Ignore RHS;
12306 
12307   return true;
12308 }
12309 
12310 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12311                                     bool IsSub) {
12312   // Compute the new offset in the appropriate width, wrapping at 64 bits.
12313   // FIXME: When compiling for a 32-bit target, we should use 32-bit
12314   // offsets.
12315   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12316   CharUnits &Offset = LVal.getLValueOffset();
12317   uint64_t Offset64 = Offset.getQuantity();
12318   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12319   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12320                                          : Offset64 + Index64);
12321 }
12322 
12323 bool DataRecursiveIntBinOpEvaluator::
12324        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12325                   const BinaryOperator *E, APValue &Result) {
12326   if (E->getOpcode() == BO_Comma) {
12327     if (RHSResult.Failed)
12328       return false;
12329     Result = RHSResult.Val;
12330     return true;
12331   }
12332 
12333   if (E->isLogicalOp()) {
12334     bool lhsResult, rhsResult;
12335     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12336     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12337 
12338     if (LHSIsOK) {
12339       if (RHSIsOK) {
12340         if (E->getOpcode() == BO_LOr)
12341           return Success(lhsResult || rhsResult, E, Result);
12342         else
12343           return Success(lhsResult && rhsResult, E, Result);
12344       }
12345     } else {
12346       if (RHSIsOK) {
12347         // We can't evaluate the LHS; however, sometimes the result
12348         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12349         if (rhsResult == (E->getOpcode() == BO_LOr))
12350           return Success(rhsResult, E, Result);
12351       }
12352     }
12353 
12354     return false;
12355   }
12356 
12357   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12358          E->getRHS()->getType()->isIntegralOrEnumerationType());
12359 
12360   if (LHSResult.Failed || RHSResult.Failed)
12361     return false;
12362 
12363   const APValue &LHSVal = LHSResult.Val;
12364   const APValue &RHSVal = RHSResult.Val;
12365 
12366   // Handle cases like (unsigned long)&a + 4.
12367   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12368     Result = LHSVal;
12369     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12370     return true;
12371   }
12372 
12373   // Handle cases like 4 + (unsigned long)&a
12374   if (E->getOpcode() == BO_Add &&
12375       RHSVal.isLValue() && LHSVal.isInt()) {
12376     Result = RHSVal;
12377     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12378     return true;
12379   }
12380 
12381   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12382     // Handle (intptr_t)&&A - (intptr_t)&&B.
12383     if (!LHSVal.getLValueOffset().isZero() ||
12384         !RHSVal.getLValueOffset().isZero())
12385       return false;
12386     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12387     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12388     if (!LHSExpr || !RHSExpr)
12389       return false;
12390     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12391     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12392     if (!LHSAddrExpr || !RHSAddrExpr)
12393       return false;
12394     // Make sure both labels come from the same function.
12395     if (LHSAddrExpr->getLabel()->getDeclContext() !=
12396         RHSAddrExpr->getLabel()->getDeclContext())
12397       return false;
12398     Result = APValue(LHSAddrExpr, RHSAddrExpr);
12399     return true;
12400   }
12401 
12402   // All the remaining cases expect both operands to be an integer
12403   if (!LHSVal.isInt() || !RHSVal.isInt())
12404     return Error(E);
12405 
12406   // Set up the width and signedness manually, in case it can't be deduced
12407   // from the operation we're performing.
12408   // FIXME: Don't do this in the cases where we can deduce it.
12409   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12410                E->getType()->isUnsignedIntegerOrEnumerationType());
12411   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12412                          RHSVal.getInt(), Value))
12413     return false;
12414   return Success(Value, E, Result);
12415 }
12416 
12417 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12418   Job &job = Queue.back();
12419 
12420   switch (job.Kind) {
12421     case Job::AnyExprKind: {
12422       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12423         if (shouldEnqueue(Bop)) {
12424           job.Kind = Job::BinOpKind;
12425           enqueue(Bop->getLHS());
12426           return;
12427         }
12428       }
12429 
12430       EvaluateExpr(job.E, Result);
12431       Queue.pop_back();
12432       return;
12433     }
12434 
12435     case Job::BinOpKind: {
12436       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12437       bool SuppressRHSDiags = false;
12438       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12439         Queue.pop_back();
12440         return;
12441       }
12442       if (SuppressRHSDiags)
12443         job.startSpeculativeEval(Info);
12444       job.LHSResult.swap(Result);
12445       job.Kind = Job::BinOpVisitedLHSKind;
12446       enqueue(Bop->getRHS());
12447       return;
12448     }
12449 
12450     case Job::BinOpVisitedLHSKind: {
12451       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12452       EvalResult RHS;
12453       RHS.swap(Result);
12454       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12455       Queue.pop_back();
12456       return;
12457     }
12458   }
12459 
12460   llvm_unreachable("Invalid Job::Kind!");
12461 }
12462 
12463 namespace {
12464 /// Used when we determine that we should fail, but can keep evaluating prior to
12465 /// noting that we had a failure.
12466 class DelayedNoteFailureRAII {
12467   EvalInfo &Info;
12468   bool NoteFailure;
12469 
12470 public:
12471   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
12472       : Info(Info), NoteFailure(NoteFailure) {}
12473   ~DelayedNoteFailureRAII() {
12474     if (NoteFailure) {
12475       bool ContinueAfterFailure = Info.noteFailure();
12476       (void)ContinueAfterFailure;
12477       assert(ContinueAfterFailure &&
12478              "Shouldn't have kept evaluating on failure.");
12479     }
12480   }
12481 };
12482 
12483 enum class CmpResult {
12484   Unequal,
12485   Less,
12486   Equal,
12487   Greater,
12488   Unordered,
12489 };
12490 }
12491 
12492 template <class SuccessCB, class AfterCB>
12493 static bool
12494 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12495                                  SuccessCB &&Success, AfterCB &&DoAfter) {
12496   assert(!E->isValueDependent());
12497   assert(E->isComparisonOp() && "expected comparison operator");
12498   assert((E->getOpcode() == BO_Cmp ||
12499           E->getType()->isIntegralOrEnumerationType()) &&
12500          "unsupported binary expression evaluation");
12501   auto Error = [&](const Expr *E) {
12502     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12503     return false;
12504   };
12505 
12506   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12507   bool IsEquality = E->isEqualityOp();
12508 
12509   QualType LHSTy = E->getLHS()->getType();
12510   QualType RHSTy = E->getRHS()->getType();
12511 
12512   if (LHSTy->isIntegralOrEnumerationType() &&
12513       RHSTy->isIntegralOrEnumerationType()) {
12514     APSInt LHS, RHS;
12515     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12516     if (!LHSOK && !Info.noteFailure())
12517       return false;
12518     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12519       return false;
12520     if (LHS < RHS)
12521       return Success(CmpResult::Less, E);
12522     if (LHS > RHS)
12523       return Success(CmpResult::Greater, E);
12524     return Success(CmpResult::Equal, E);
12525   }
12526 
12527   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12528     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12529     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12530 
12531     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12532     if (!LHSOK && !Info.noteFailure())
12533       return false;
12534     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12535       return false;
12536     if (LHSFX < RHSFX)
12537       return Success(CmpResult::Less, E);
12538     if (LHSFX > RHSFX)
12539       return Success(CmpResult::Greater, E);
12540     return Success(CmpResult::Equal, E);
12541   }
12542 
12543   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12544     ComplexValue LHS, RHS;
12545     bool LHSOK;
12546     if (E->isAssignmentOp()) {
12547       LValue LV;
12548       EvaluateLValue(E->getLHS(), LV, Info);
12549       LHSOK = false;
12550     } else if (LHSTy->isRealFloatingType()) {
12551       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12552       if (LHSOK) {
12553         LHS.makeComplexFloat();
12554         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12555       }
12556     } else {
12557       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12558     }
12559     if (!LHSOK && !Info.noteFailure())
12560       return false;
12561 
12562     if (E->getRHS()->getType()->isRealFloatingType()) {
12563       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12564         return false;
12565       RHS.makeComplexFloat();
12566       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12567     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12568       return false;
12569 
12570     if (LHS.isComplexFloat()) {
12571       APFloat::cmpResult CR_r =
12572         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12573       APFloat::cmpResult CR_i =
12574         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12575       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12576       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12577     } else {
12578       assert(IsEquality && "invalid complex comparison");
12579       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12580                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
12581       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12582     }
12583   }
12584 
12585   if (LHSTy->isRealFloatingType() &&
12586       RHSTy->isRealFloatingType()) {
12587     APFloat RHS(0.0), LHS(0.0);
12588 
12589     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12590     if (!LHSOK && !Info.noteFailure())
12591       return false;
12592 
12593     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12594       return false;
12595 
12596     assert(E->isComparisonOp() && "Invalid binary operator!");
12597     llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
12598     if (!Info.InConstantContext &&
12599         APFloatCmpResult == APFloat::cmpUnordered &&
12600         E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
12601       // Note: Compares may raise invalid in some cases involving NaN or sNaN.
12602       Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
12603       return false;
12604     }
12605     auto GetCmpRes = [&]() {
12606       switch (APFloatCmpResult) {
12607       case APFloat::cmpEqual:
12608         return CmpResult::Equal;
12609       case APFloat::cmpLessThan:
12610         return CmpResult::Less;
12611       case APFloat::cmpGreaterThan:
12612         return CmpResult::Greater;
12613       case APFloat::cmpUnordered:
12614         return CmpResult::Unordered;
12615       }
12616       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12617     };
12618     return Success(GetCmpRes(), E);
12619   }
12620 
12621   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12622     LValue LHSValue, RHSValue;
12623 
12624     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12625     if (!LHSOK && !Info.noteFailure())
12626       return false;
12627 
12628     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12629       return false;
12630 
12631     // Reject differing bases from the normal codepath; we special-case
12632     // comparisons to null.
12633     if (!HasSameBase(LHSValue, RHSValue)) {
12634       // Inequalities and subtractions between unrelated pointers have
12635       // unspecified or undefined behavior.
12636       if (!IsEquality) {
12637         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
12638         return false;
12639       }
12640       // A constant address may compare equal to the address of a symbol.
12641       // The one exception is that address of an object cannot compare equal
12642       // to a null pointer constant.
12643       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12644           (!RHSValue.Base && !RHSValue.Offset.isZero()))
12645         return Error(E);
12646       // It's implementation-defined whether distinct literals will have
12647       // distinct addresses. In clang, the result of such a comparison is
12648       // unspecified, so it is not a constant expression. However, we do know
12649       // that the address of a literal will be non-null.
12650       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12651           LHSValue.Base && RHSValue.Base)
12652         return Error(E);
12653       // We can't tell whether weak symbols will end up pointing to the same
12654       // object.
12655       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12656         return Error(E);
12657       // We can't compare the address of the start of one object with the
12658       // past-the-end address of another object, per C++ DR1652.
12659       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
12660            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
12661           (RHSValue.Base && RHSValue.Offset.isZero() &&
12662            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
12663         return Error(E);
12664       // We can't tell whether an object is at the same address as another
12665       // zero sized object.
12666       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12667           (LHSValue.Base && isZeroSized(RHSValue)))
12668         return Error(E);
12669       return Success(CmpResult::Unequal, E);
12670     }
12671 
12672     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12673     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12674 
12675     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12676     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12677 
12678     // C++11 [expr.rel]p3:
12679     //   Pointers to void (after pointer conversions) can be compared, with a
12680     //   result defined as follows: If both pointers represent the same
12681     //   address or are both the null pointer value, the result is true if the
12682     //   operator is <= or >= and false otherwise; otherwise the result is
12683     //   unspecified.
12684     // We interpret this as applying to pointers to *cv* void.
12685     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
12686       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
12687 
12688     // C++11 [expr.rel]p2:
12689     // - If two pointers point to non-static data members of the same object,
12690     //   or to subobjects or array elements fo such members, recursively, the
12691     //   pointer to the later declared member compares greater provided the
12692     //   two members have the same access control and provided their class is
12693     //   not a union.
12694     //   [...]
12695     // - Otherwise pointer comparisons are unspecified.
12696     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
12697       bool WasArrayIndex;
12698       unsigned Mismatch = FindDesignatorMismatch(
12699           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
12700       // At the point where the designators diverge, the comparison has a
12701       // specified value if:
12702       //  - we are comparing array indices
12703       //  - we are comparing fields of a union, or fields with the same access
12704       // Otherwise, the result is unspecified and thus the comparison is not a
12705       // constant expression.
12706       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
12707           Mismatch < RHSDesignator.Entries.size()) {
12708         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
12709         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
12710         if (!LF && !RF)
12711           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
12712         else if (!LF)
12713           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12714               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
12715               << RF->getParent() << RF;
12716         else if (!RF)
12717           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12718               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
12719               << LF->getParent() << LF;
12720         else if (!LF->getParent()->isUnion() &&
12721                  LF->getAccess() != RF->getAccess())
12722           Info.CCEDiag(E,
12723                        diag::note_constexpr_pointer_comparison_differing_access)
12724               << LF << LF->getAccess() << RF << RF->getAccess()
12725               << LF->getParent();
12726       }
12727     }
12728 
12729     // The comparison here must be unsigned, and performed with the same
12730     // width as the pointer.
12731     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
12732     uint64_t CompareLHS = LHSOffset.getQuantity();
12733     uint64_t CompareRHS = RHSOffset.getQuantity();
12734     assert(PtrSize <= 64 && "Unexpected pointer width");
12735     uint64_t Mask = ~0ULL >> (64 - PtrSize);
12736     CompareLHS &= Mask;
12737     CompareRHS &= Mask;
12738 
12739     // If there is a base and this is a relational operator, we can only
12740     // compare pointers within the object in question; otherwise, the result
12741     // depends on where the object is located in memory.
12742     if (!LHSValue.Base.isNull() && IsRelational) {
12743       QualType BaseTy = getType(LHSValue.Base);
12744       if (BaseTy->isIncompleteType())
12745         return Error(E);
12746       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
12747       uint64_t OffsetLimit = Size.getQuantity();
12748       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
12749         return Error(E);
12750     }
12751 
12752     if (CompareLHS < CompareRHS)
12753       return Success(CmpResult::Less, E);
12754     if (CompareLHS > CompareRHS)
12755       return Success(CmpResult::Greater, E);
12756     return Success(CmpResult::Equal, E);
12757   }
12758 
12759   if (LHSTy->isMemberPointerType()) {
12760     assert(IsEquality && "unexpected member pointer operation");
12761     assert(RHSTy->isMemberPointerType() && "invalid comparison");
12762 
12763     MemberPtr LHSValue, RHSValue;
12764 
12765     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
12766     if (!LHSOK && !Info.noteFailure())
12767       return false;
12768 
12769     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12770       return false;
12771 
12772     // C++11 [expr.eq]p2:
12773     //   If both operands are null, they compare equal. Otherwise if only one is
12774     //   null, they compare unequal.
12775     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
12776       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
12777       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12778     }
12779 
12780     //   Otherwise if either is a pointer to a virtual member function, the
12781     //   result is unspecified.
12782     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
12783       if (MD->isVirtual())
12784         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12785     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
12786       if (MD->isVirtual())
12787         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12788 
12789     //   Otherwise they compare equal if and only if they would refer to the
12790     //   same member of the same most derived object or the same subobject if
12791     //   they were dereferenced with a hypothetical object of the associated
12792     //   class type.
12793     bool Equal = LHSValue == RHSValue;
12794     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12795   }
12796 
12797   if (LHSTy->isNullPtrType()) {
12798     assert(E->isComparisonOp() && "unexpected nullptr operation");
12799     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12800     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12801     // are compared, the result is true of the operator is <=, >= or ==, and
12802     // false otherwise.
12803     return Success(CmpResult::Equal, E);
12804   }
12805 
12806   return DoAfter();
12807 }
12808 
12809 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
12810   if (!CheckLiteralType(Info, E))
12811     return false;
12812 
12813   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12814     ComparisonCategoryResult CCR;
12815     switch (CR) {
12816     case CmpResult::Unequal:
12817       llvm_unreachable("should never produce Unequal for three-way comparison");
12818     case CmpResult::Less:
12819       CCR = ComparisonCategoryResult::Less;
12820       break;
12821     case CmpResult::Equal:
12822       CCR = ComparisonCategoryResult::Equal;
12823       break;
12824     case CmpResult::Greater:
12825       CCR = ComparisonCategoryResult::Greater;
12826       break;
12827     case CmpResult::Unordered:
12828       CCR = ComparisonCategoryResult::Unordered;
12829       break;
12830     }
12831     // Evaluation succeeded. Lookup the information for the comparison category
12832     // type and fetch the VarDecl for the result.
12833     const ComparisonCategoryInfo &CmpInfo =
12834         Info.Ctx.CompCategories.getInfoForType(E->getType());
12835     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
12836     // Check and evaluate the result as a constant expression.
12837     LValue LV;
12838     LV.set(VD);
12839     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12840       return false;
12841     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
12842                                    ConstantExprKind::Normal);
12843   };
12844   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12845     return ExprEvaluatorBaseTy::VisitBinCmp(E);
12846   });
12847 }
12848 
12849 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12850   // We don't call noteFailure immediately because the assignment happens after
12851   // we evaluate LHS and RHS.
12852   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
12853     return Error(E);
12854 
12855   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
12856   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
12857     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
12858 
12859   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
12860           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
12861          "DataRecursiveIntBinOpEvaluator should have handled integral types");
12862 
12863   if (E->isComparisonOp()) {
12864     // Evaluate builtin binary comparisons by evaluating them as three-way
12865     // comparisons and then translating the result.
12866     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12867       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
12868              "should only produce Unequal for equality comparisons");
12869       bool IsEqual   = CR == CmpResult::Equal,
12870            IsLess    = CR == CmpResult::Less,
12871            IsGreater = CR == CmpResult::Greater;
12872       auto Op = E->getOpcode();
12873       switch (Op) {
12874       default:
12875         llvm_unreachable("unsupported binary operator");
12876       case BO_EQ:
12877       case BO_NE:
12878         return Success(IsEqual == (Op == BO_EQ), E);
12879       case BO_LT:
12880         return Success(IsLess, E);
12881       case BO_GT:
12882         return Success(IsGreater, E);
12883       case BO_LE:
12884         return Success(IsEqual || IsLess, E);
12885       case BO_GE:
12886         return Success(IsEqual || IsGreater, E);
12887       }
12888     };
12889     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12890       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12891     });
12892   }
12893 
12894   QualType LHSTy = E->getLHS()->getType();
12895   QualType RHSTy = E->getRHS()->getType();
12896 
12897   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
12898       E->getOpcode() == BO_Sub) {
12899     LValue LHSValue, RHSValue;
12900 
12901     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12902     if (!LHSOK && !Info.noteFailure())
12903       return false;
12904 
12905     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12906       return false;
12907 
12908     // Reject differing bases from the normal codepath; we special-case
12909     // comparisons to null.
12910     if (!HasSameBase(LHSValue, RHSValue)) {
12911       // Handle &&A - &&B.
12912       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
12913         return Error(E);
12914       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
12915       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
12916       if (!LHSExpr || !RHSExpr)
12917         return Error(E);
12918       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12919       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12920       if (!LHSAddrExpr || !RHSAddrExpr)
12921         return Error(E);
12922       // Make sure both labels come from the same function.
12923       if (LHSAddrExpr->getLabel()->getDeclContext() !=
12924           RHSAddrExpr->getLabel()->getDeclContext())
12925         return Error(E);
12926       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
12927     }
12928     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12929     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12930 
12931     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12932     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12933 
12934     // C++11 [expr.add]p6:
12935     //   Unless both pointers point to elements of the same array object, or
12936     //   one past the last element of the array object, the behavior is
12937     //   undefined.
12938     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
12939         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
12940                                 RHSDesignator))
12941       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
12942 
12943     QualType Type = E->getLHS()->getType();
12944     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
12945 
12946     CharUnits ElementSize;
12947     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
12948       return false;
12949 
12950     // As an extension, a type may have zero size (empty struct or union in
12951     // C, array of zero length). Pointer subtraction in such cases has
12952     // undefined behavior, so is not constant.
12953     if (ElementSize.isZero()) {
12954       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
12955           << ElementType;
12956       return false;
12957     }
12958 
12959     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
12960     // and produce incorrect results when it overflows. Such behavior
12961     // appears to be non-conforming, but is common, so perhaps we should
12962     // assume the standard intended for such cases to be undefined behavior
12963     // and check for them.
12964 
12965     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
12966     // overflow in the final conversion to ptrdiff_t.
12967     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
12968     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
12969     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
12970                     false);
12971     APSInt TrueResult = (LHS - RHS) / ElemSize;
12972     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
12973 
12974     if (Result.extend(65) != TrueResult &&
12975         !HandleOverflow(Info, E, TrueResult, E->getType()))
12976       return false;
12977     return Success(Result, E);
12978   }
12979 
12980   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12981 }
12982 
12983 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
12984 /// a result as the expression's type.
12985 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
12986                                     const UnaryExprOrTypeTraitExpr *E) {
12987   switch(E->getKind()) {
12988   case UETT_PreferredAlignOf:
12989   case UETT_AlignOf: {
12990     if (E->isArgumentType())
12991       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
12992                      E);
12993     else
12994       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
12995                      E);
12996   }
12997 
12998   case UETT_VecStep: {
12999     QualType Ty = E->getTypeOfArgument();
13000 
13001     if (Ty->isVectorType()) {
13002       unsigned n = Ty->castAs<VectorType>()->getNumElements();
13003 
13004       // The vec_step built-in functions that take a 3-component
13005       // vector return 4. (OpenCL 1.1 spec 6.11.12)
13006       if (n == 3)
13007         n = 4;
13008 
13009       return Success(n, E);
13010     } else
13011       return Success(1, E);
13012   }
13013 
13014   case UETT_SizeOf: {
13015     QualType SrcTy = E->getTypeOfArgument();
13016     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13017     //   the result is the size of the referenced type."
13018     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13019       SrcTy = Ref->getPointeeType();
13020 
13021     CharUnits Sizeof;
13022     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
13023       return false;
13024     return Success(Sizeof, E);
13025   }
13026   case UETT_OpenMPRequiredSimdAlign:
13027     assert(E->isArgumentType());
13028     return Success(
13029         Info.Ctx.toCharUnitsFromBits(
13030                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13031             .getQuantity(),
13032         E);
13033   }
13034 
13035   llvm_unreachable("unknown expr/type trait");
13036 }
13037 
13038 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13039   CharUnits Result;
13040   unsigned n = OOE->getNumComponents();
13041   if (n == 0)
13042     return Error(OOE);
13043   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13044   for (unsigned i = 0; i != n; ++i) {
13045     OffsetOfNode ON = OOE->getComponent(i);
13046     switch (ON.getKind()) {
13047     case OffsetOfNode::Array: {
13048       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13049       APSInt IdxResult;
13050       if (!EvaluateInteger(Idx, IdxResult, Info))
13051         return false;
13052       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13053       if (!AT)
13054         return Error(OOE);
13055       CurrentType = AT->getElementType();
13056       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13057       Result += IdxResult.getSExtValue() * ElementSize;
13058       break;
13059     }
13060 
13061     case OffsetOfNode::Field: {
13062       FieldDecl *MemberDecl = ON.getField();
13063       const RecordType *RT = CurrentType->getAs<RecordType>();
13064       if (!RT)
13065         return Error(OOE);
13066       RecordDecl *RD = RT->getDecl();
13067       if (RD->isInvalidDecl()) return false;
13068       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13069       unsigned i = MemberDecl->getFieldIndex();
13070       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
13071       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13072       CurrentType = MemberDecl->getType().getNonReferenceType();
13073       break;
13074     }
13075 
13076     case OffsetOfNode::Identifier:
13077       llvm_unreachable("dependent __builtin_offsetof");
13078 
13079     case OffsetOfNode::Base: {
13080       CXXBaseSpecifier *BaseSpec = ON.getBase();
13081       if (BaseSpec->isVirtual())
13082         return Error(OOE);
13083 
13084       // Find the layout of the class whose base we are looking into.
13085       const RecordType *RT = CurrentType->getAs<RecordType>();
13086       if (!RT)
13087         return Error(OOE);
13088       RecordDecl *RD = RT->getDecl();
13089       if (RD->isInvalidDecl()) return false;
13090       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13091 
13092       // Find the base class itself.
13093       CurrentType = BaseSpec->getType();
13094       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13095       if (!BaseRT)
13096         return Error(OOE);
13097 
13098       // Add the offset to the base.
13099       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13100       break;
13101     }
13102     }
13103   }
13104   return Success(Result, OOE);
13105 }
13106 
13107 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13108   switch (E->getOpcode()) {
13109   default:
13110     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13111     // See C99 6.6p3.
13112     return Error(E);
13113   case UO_Extension:
13114     // FIXME: Should extension allow i-c-e extension expressions in its scope?
13115     // If so, we could clear the diagnostic ID.
13116     return Visit(E->getSubExpr());
13117   case UO_Plus:
13118     // The result is just the value.
13119     return Visit(E->getSubExpr());
13120   case UO_Minus: {
13121     if (!Visit(E->getSubExpr()))
13122       return false;
13123     if (!Result.isInt()) return Error(E);
13124     const APSInt &Value = Result.getInt();
13125     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
13126         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13127                         E->getType()))
13128       return false;
13129     return Success(-Value, E);
13130   }
13131   case UO_Not: {
13132     if (!Visit(E->getSubExpr()))
13133       return false;
13134     if (!Result.isInt()) return Error(E);
13135     return Success(~Result.getInt(), E);
13136   }
13137   case UO_LNot: {
13138     bool bres;
13139     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13140       return false;
13141     return Success(!bres, E);
13142   }
13143   }
13144 }
13145 
13146 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13147 /// result type is integer.
13148 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13149   const Expr *SubExpr = E->getSubExpr();
13150   QualType DestType = E->getType();
13151   QualType SrcType = SubExpr->getType();
13152 
13153   switch (E->getCastKind()) {
13154   case CK_BaseToDerived:
13155   case CK_DerivedToBase:
13156   case CK_UncheckedDerivedToBase:
13157   case CK_Dynamic:
13158   case CK_ToUnion:
13159   case CK_ArrayToPointerDecay:
13160   case CK_FunctionToPointerDecay:
13161   case CK_NullToPointer:
13162   case CK_NullToMemberPointer:
13163   case CK_BaseToDerivedMemberPointer:
13164   case CK_DerivedToBaseMemberPointer:
13165   case CK_ReinterpretMemberPointer:
13166   case CK_ConstructorConversion:
13167   case CK_IntegralToPointer:
13168   case CK_ToVoid:
13169   case CK_VectorSplat:
13170   case CK_IntegralToFloating:
13171   case CK_FloatingCast:
13172   case CK_CPointerToObjCPointerCast:
13173   case CK_BlockPointerToObjCPointerCast:
13174   case CK_AnyPointerToBlockPointerCast:
13175   case CK_ObjCObjectLValueCast:
13176   case CK_FloatingRealToComplex:
13177   case CK_FloatingComplexToReal:
13178   case CK_FloatingComplexCast:
13179   case CK_FloatingComplexToIntegralComplex:
13180   case CK_IntegralRealToComplex:
13181   case CK_IntegralComplexCast:
13182   case CK_IntegralComplexToFloatingComplex:
13183   case CK_BuiltinFnToFnPtr:
13184   case CK_ZeroToOCLOpaqueType:
13185   case CK_NonAtomicToAtomic:
13186   case CK_AddressSpaceConversion:
13187   case CK_IntToOCLSampler:
13188   case CK_FloatingToFixedPoint:
13189   case CK_FixedPointToFloating:
13190   case CK_FixedPointCast:
13191   case CK_IntegralToFixedPoint:
13192     llvm_unreachable("invalid cast kind for integral value");
13193 
13194   case CK_BitCast:
13195   case CK_Dependent:
13196   case CK_LValueBitCast:
13197   case CK_ARCProduceObject:
13198   case CK_ARCConsumeObject:
13199   case CK_ARCReclaimReturnedObject:
13200   case CK_ARCExtendBlockObject:
13201   case CK_CopyAndAutoreleaseBlockObject:
13202     return Error(E);
13203 
13204   case CK_UserDefinedConversion:
13205   case CK_LValueToRValue:
13206   case CK_AtomicToNonAtomic:
13207   case CK_NoOp:
13208   case CK_LValueToRValueBitCast:
13209     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13210 
13211   case CK_MemberPointerToBoolean:
13212   case CK_PointerToBoolean:
13213   case CK_IntegralToBoolean:
13214   case CK_FloatingToBoolean:
13215   case CK_BooleanToSignedIntegral:
13216   case CK_FloatingComplexToBoolean:
13217   case CK_IntegralComplexToBoolean: {
13218     bool BoolResult;
13219     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13220       return false;
13221     uint64_t IntResult = BoolResult;
13222     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13223       IntResult = (uint64_t)-1;
13224     return Success(IntResult, E);
13225   }
13226 
13227   case CK_FixedPointToIntegral: {
13228     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13229     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13230       return false;
13231     bool Overflowed;
13232     llvm::APSInt Result = Src.convertToInt(
13233         Info.Ctx.getIntWidth(DestType),
13234         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13235     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13236       return false;
13237     return Success(Result, E);
13238   }
13239 
13240   case CK_FixedPointToBoolean: {
13241     // Unsigned padding does not affect this.
13242     APValue Val;
13243     if (!Evaluate(Val, Info, SubExpr))
13244       return false;
13245     return Success(Val.getFixedPoint().getBoolValue(), E);
13246   }
13247 
13248   case CK_IntegralCast: {
13249     if (!Visit(SubExpr))
13250       return false;
13251 
13252     if (!Result.isInt()) {
13253       // Allow casts of address-of-label differences if they are no-ops
13254       // or narrowing.  (The narrowing case isn't actually guaranteed to
13255       // be constant-evaluatable except in some narrow cases which are hard
13256       // to detect here.  We let it through on the assumption the user knows
13257       // what they are doing.)
13258       if (Result.isAddrLabelDiff())
13259         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13260       // Only allow casts of lvalues if they are lossless.
13261       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13262     }
13263 
13264     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13265                                       Result.getInt()), E);
13266   }
13267 
13268   case CK_PointerToIntegral: {
13269     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
13270 
13271     LValue LV;
13272     if (!EvaluatePointer(SubExpr, LV, Info))
13273       return false;
13274 
13275     if (LV.getLValueBase()) {
13276       // Only allow based lvalue casts if they are lossless.
13277       // FIXME: Allow a larger integer size than the pointer size, and allow
13278       // narrowing back down to pointer width in subsequent integral casts.
13279       // FIXME: Check integer type's active bits, not its type size.
13280       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13281         return Error(E);
13282 
13283       LV.Designator.setInvalid();
13284       LV.moveInto(Result);
13285       return true;
13286     }
13287 
13288     APSInt AsInt;
13289     APValue V;
13290     LV.moveInto(V);
13291     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13292       llvm_unreachable("Can't cast this!");
13293 
13294     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13295   }
13296 
13297   case CK_IntegralComplexToReal: {
13298     ComplexValue C;
13299     if (!EvaluateComplex(SubExpr, C, Info))
13300       return false;
13301     return Success(C.getComplexIntReal(), E);
13302   }
13303 
13304   case CK_FloatingToIntegral: {
13305     APFloat F(0.0);
13306     if (!EvaluateFloat(SubExpr, F, Info))
13307       return false;
13308 
13309     APSInt Value;
13310     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13311       return false;
13312     return Success(Value, E);
13313   }
13314   }
13315 
13316   llvm_unreachable("unknown cast resulting in integral value");
13317 }
13318 
13319 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13320   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13321     ComplexValue LV;
13322     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13323       return false;
13324     if (!LV.isComplexInt())
13325       return Error(E);
13326     return Success(LV.getComplexIntReal(), E);
13327   }
13328 
13329   return Visit(E->getSubExpr());
13330 }
13331 
13332 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13333   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13334     ComplexValue LV;
13335     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13336       return false;
13337     if (!LV.isComplexInt())
13338       return Error(E);
13339     return Success(LV.getComplexIntImag(), E);
13340   }
13341 
13342   VisitIgnoredValue(E->getSubExpr());
13343   return Success(0, E);
13344 }
13345 
13346 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13347   return Success(E->getPackLength(), E);
13348 }
13349 
13350 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13351   return Success(E->getValue(), E);
13352 }
13353 
13354 bool IntExprEvaluator::VisitConceptSpecializationExpr(
13355        const ConceptSpecializationExpr *E) {
13356   return Success(E->isSatisfied(), E);
13357 }
13358 
13359 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13360   return Success(E->isSatisfied(), E);
13361 }
13362 
13363 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13364   switch (E->getOpcode()) {
13365     default:
13366       // Invalid unary operators
13367       return Error(E);
13368     case UO_Plus:
13369       // The result is just the value.
13370       return Visit(E->getSubExpr());
13371     case UO_Minus: {
13372       if (!Visit(E->getSubExpr())) return false;
13373       if (!Result.isFixedPoint())
13374         return Error(E);
13375       bool Overflowed;
13376       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13377       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13378         return false;
13379       return Success(Negated, E);
13380     }
13381     case UO_LNot: {
13382       bool bres;
13383       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13384         return false;
13385       return Success(!bres, E);
13386     }
13387   }
13388 }
13389 
13390 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13391   const Expr *SubExpr = E->getSubExpr();
13392   QualType DestType = E->getType();
13393   assert(DestType->isFixedPointType() &&
13394          "Expected destination type to be a fixed point type");
13395   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13396 
13397   switch (E->getCastKind()) {
13398   case CK_FixedPointCast: {
13399     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13400     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13401       return false;
13402     bool Overflowed;
13403     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13404     if (Overflowed) {
13405       if (Info.checkingForUndefinedBehavior())
13406         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13407                                          diag::warn_fixedpoint_constant_overflow)
13408           << Result.toString() << E->getType();
13409       else if (!HandleOverflow(Info, E, Result, E->getType()))
13410         return false;
13411     }
13412     return Success(Result, E);
13413   }
13414   case CK_IntegralToFixedPoint: {
13415     APSInt Src;
13416     if (!EvaluateInteger(SubExpr, Src, Info))
13417       return false;
13418 
13419     bool Overflowed;
13420     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13421         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13422 
13423     if (Overflowed) {
13424       if (Info.checkingForUndefinedBehavior())
13425         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13426                                          diag::warn_fixedpoint_constant_overflow)
13427           << IntResult.toString() << E->getType();
13428       else if (!HandleOverflow(Info, E, IntResult, E->getType()))
13429         return false;
13430     }
13431 
13432     return Success(IntResult, E);
13433   }
13434   case CK_FloatingToFixedPoint: {
13435     APFloat Src(0.0);
13436     if (!EvaluateFloat(SubExpr, Src, Info))
13437       return false;
13438 
13439     bool Overflowed;
13440     APFixedPoint Result = APFixedPoint::getFromFloatValue(
13441         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13442 
13443     if (Overflowed) {
13444       if (Info.checkingForUndefinedBehavior())
13445         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13446                                          diag::warn_fixedpoint_constant_overflow)
13447           << Result.toString() << E->getType();
13448       else if (!HandleOverflow(Info, E, Result, E->getType()))
13449         return false;
13450     }
13451 
13452     return Success(Result, E);
13453   }
13454   case CK_NoOp:
13455   case CK_LValueToRValue:
13456     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13457   default:
13458     return Error(E);
13459   }
13460 }
13461 
13462 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13463   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13464     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13465 
13466   const Expr *LHS = E->getLHS();
13467   const Expr *RHS = E->getRHS();
13468   FixedPointSemantics ResultFXSema =
13469       Info.Ctx.getFixedPointSemantics(E->getType());
13470 
13471   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13472   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13473     return false;
13474   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13475   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13476     return false;
13477 
13478   bool OpOverflow = false, ConversionOverflow = false;
13479   APFixedPoint Result(LHSFX.getSemantics());
13480   switch (E->getOpcode()) {
13481   case BO_Add: {
13482     Result = LHSFX.add(RHSFX, &OpOverflow)
13483                   .convert(ResultFXSema, &ConversionOverflow);
13484     break;
13485   }
13486   case BO_Sub: {
13487     Result = LHSFX.sub(RHSFX, &OpOverflow)
13488                   .convert(ResultFXSema, &ConversionOverflow);
13489     break;
13490   }
13491   case BO_Mul: {
13492     Result = LHSFX.mul(RHSFX, &OpOverflow)
13493                   .convert(ResultFXSema, &ConversionOverflow);
13494     break;
13495   }
13496   case BO_Div: {
13497     if (RHSFX.getValue() == 0) {
13498       Info.FFDiag(E, diag::note_expr_divide_by_zero);
13499       return false;
13500     }
13501     Result = LHSFX.div(RHSFX, &OpOverflow)
13502                   .convert(ResultFXSema, &ConversionOverflow);
13503     break;
13504   }
13505   case BO_Shl:
13506   case BO_Shr: {
13507     FixedPointSemantics LHSSema = LHSFX.getSemantics();
13508     llvm::APSInt RHSVal = RHSFX.getValue();
13509 
13510     unsigned ShiftBW =
13511         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13512     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13513     // Embedded-C 4.1.6.2.2:
13514     //   The right operand must be nonnegative and less than the total number
13515     //   of (nonpadding) bits of the fixed-point operand ...
13516     if (RHSVal.isNegative())
13517       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13518     else if (Amt != RHSVal)
13519       Info.CCEDiag(E, diag::note_constexpr_large_shift)
13520           << RHSVal << E->getType() << ShiftBW;
13521 
13522     if (E->getOpcode() == BO_Shl)
13523       Result = LHSFX.shl(Amt, &OpOverflow);
13524     else
13525       Result = LHSFX.shr(Amt, &OpOverflow);
13526     break;
13527   }
13528   default:
13529     return false;
13530   }
13531   if (OpOverflow || ConversionOverflow) {
13532     if (Info.checkingForUndefinedBehavior())
13533       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13534                                        diag::warn_fixedpoint_constant_overflow)
13535         << Result.toString() << E->getType();
13536     else if (!HandleOverflow(Info, E, Result, E->getType()))
13537       return false;
13538   }
13539   return Success(Result, E);
13540 }
13541 
13542 //===----------------------------------------------------------------------===//
13543 // Float Evaluation
13544 //===----------------------------------------------------------------------===//
13545 
13546 namespace {
13547 class FloatExprEvaluator
13548   : public ExprEvaluatorBase<FloatExprEvaluator> {
13549   APFloat &Result;
13550 public:
13551   FloatExprEvaluator(EvalInfo &info, APFloat &result)
13552     : ExprEvaluatorBaseTy(info), Result(result) {}
13553 
13554   bool Success(const APValue &V, const Expr *e) {
13555     Result = V.getFloat();
13556     return true;
13557   }
13558 
13559   bool ZeroInitialization(const Expr *E) {
13560     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13561     return true;
13562   }
13563 
13564   bool VisitCallExpr(const CallExpr *E);
13565 
13566   bool VisitUnaryOperator(const UnaryOperator *E);
13567   bool VisitBinaryOperator(const BinaryOperator *E);
13568   bool VisitFloatingLiteral(const FloatingLiteral *E);
13569   bool VisitCastExpr(const CastExpr *E);
13570 
13571   bool VisitUnaryReal(const UnaryOperator *E);
13572   bool VisitUnaryImag(const UnaryOperator *E);
13573 
13574   // FIXME: Missing: array subscript of vector, member of vector
13575 };
13576 } // end anonymous namespace
13577 
13578 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13579   assert(!E->isValueDependent());
13580   assert(E->isRValue() && E->getType()->isRealFloatingType());
13581   return FloatExprEvaluator(Info, Result).Visit(E);
13582 }
13583 
13584 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13585                                   QualType ResultTy,
13586                                   const Expr *Arg,
13587                                   bool SNaN,
13588                                   llvm::APFloat &Result) {
13589   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13590   if (!S) return false;
13591 
13592   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13593 
13594   llvm::APInt fill;
13595 
13596   // Treat empty strings as if they were zero.
13597   if (S->getString().empty())
13598     fill = llvm::APInt(32, 0);
13599   else if (S->getString().getAsInteger(0, fill))
13600     return false;
13601 
13602   if (Context.getTargetInfo().isNan2008()) {
13603     if (SNaN)
13604       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13605     else
13606       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13607   } else {
13608     // Prior to IEEE 754-2008, architectures were allowed to choose whether
13609     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13610     // a different encoding to what became a standard in 2008, and for pre-
13611     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13612     // sNaN. This is now known as "legacy NaN" encoding.
13613     if (SNaN)
13614       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13615     else
13616       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13617   }
13618 
13619   return true;
13620 }
13621 
13622 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
13623   switch (E->getBuiltinCallee()) {
13624   default:
13625     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13626 
13627   case Builtin::BI__builtin_huge_val:
13628   case Builtin::BI__builtin_huge_valf:
13629   case Builtin::BI__builtin_huge_vall:
13630   case Builtin::BI__builtin_huge_valf128:
13631   case Builtin::BI__builtin_inf:
13632   case Builtin::BI__builtin_inff:
13633   case Builtin::BI__builtin_infl:
13634   case Builtin::BI__builtin_inff128: {
13635     const llvm::fltSemantics &Sem =
13636       Info.Ctx.getFloatTypeSemantics(E->getType());
13637     Result = llvm::APFloat::getInf(Sem);
13638     return true;
13639   }
13640 
13641   case Builtin::BI__builtin_nans:
13642   case Builtin::BI__builtin_nansf:
13643   case Builtin::BI__builtin_nansl:
13644   case Builtin::BI__builtin_nansf128:
13645     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13646                                true, Result))
13647       return Error(E);
13648     return true;
13649 
13650   case Builtin::BI__builtin_nan:
13651   case Builtin::BI__builtin_nanf:
13652   case Builtin::BI__builtin_nanl:
13653   case Builtin::BI__builtin_nanf128:
13654     // If this is __builtin_nan() turn this into a nan, otherwise we
13655     // can't constant fold it.
13656     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13657                                false, Result))
13658       return Error(E);
13659     return true;
13660 
13661   case Builtin::BI__builtin_fabs:
13662   case Builtin::BI__builtin_fabsf:
13663   case Builtin::BI__builtin_fabsl:
13664   case Builtin::BI__builtin_fabsf128:
13665     // The C standard says "fabs raises no floating-point exceptions,
13666     // even if x is a signaling NaN. The returned value is independent of
13667     // the current rounding direction mode."  Therefore constant folding can
13668     // proceed without regard to the floating point settings.
13669     // Reference, WG14 N2478 F.10.4.3
13670     if (!EvaluateFloat(E->getArg(0), Result, Info))
13671       return false;
13672 
13673     if (Result.isNegative())
13674       Result.changeSign();
13675     return true;
13676 
13677   // FIXME: Builtin::BI__builtin_powi
13678   // FIXME: Builtin::BI__builtin_powif
13679   // FIXME: Builtin::BI__builtin_powil
13680 
13681   case Builtin::BI__builtin_copysign:
13682   case Builtin::BI__builtin_copysignf:
13683   case Builtin::BI__builtin_copysignl:
13684   case Builtin::BI__builtin_copysignf128: {
13685     APFloat RHS(0.);
13686     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
13687         !EvaluateFloat(E->getArg(1), RHS, Info))
13688       return false;
13689     Result.copySign(RHS);
13690     return true;
13691   }
13692   }
13693 }
13694 
13695 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13696   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13697     ComplexValue CV;
13698     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13699       return false;
13700     Result = CV.FloatReal;
13701     return true;
13702   }
13703 
13704   return Visit(E->getSubExpr());
13705 }
13706 
13707 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13708   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13709     ComplexValue CV;
13710     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13711       return false;
13712     Result = CV.FloatImag;
13713     return true;
13714   }
13715 
13716   VisitIgnoredValue(E->getSubExpr());
13717   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
13718   Result = llvm::APFloat::getZero(Sem);
13719   return true;
13720 }
13721 
13722 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13723   switch (E->getOpcode()) {
13724   default: return Error(E);
13725   case UO_Plus:
13726     return EvaluateFloat(E->getSubExpr(), Result, Info);
13727   case UO_Minus:
13728     // In C standard, WG14 N2478 F.3 p4
13729     // "the unary - raises no floating point exceptions,
13730     // even if the operand is signalling."
13731     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
13732       return false;
13733     Result.changeSign();
13734     return true;
13735   }
13736 }
13737 
13738 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13739   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13740     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13741 
13742   APFloat RHS(0.0);
13743   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
13744   if (!LHSOK && !Info.noteFailure())
13745     return false;
13746   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
13747          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
13748 }
13749 
13750 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
13751   Result = E->getValue();
13752   return true;
13753 }
13754 
13755 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
13756   const Expr* SubExpr = E->getSubExpr();
13757 
13758   switch (E->getCastKind()) {
13759   default:
13760     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13761 
13762   case CK_IntegralToFloating: {
13763     APSInt IntResult;
13764     const FPOptions FPO = E->getFPFeaturesInEffect(
13765                                   Info.Ctx.getLangOpts());
13766     return EvaluateInteger(SubExpr, IntResult, Info) &&
13767            HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
13768                                 IntResult, E->getType(), Result);
13769   }
13770 
13771   case CK_FixedPointToFloating: {
13772     APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13773     if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
13774       return false;
13775     Result =
13776         FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
13777     return true;
13778   }
13779 
13780   case CK_FloatingCast: {
13781     if (!Visit(SubExpr))
13782       return false;
13783     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
13784                                   Result);
13785   }
13786 
13787   case CK_FloatingComplexToReal: {
13788     ComplexValue V;
13789     if (!EvaluateComplex(SubExpr, V, Info))
13790       return false;
13791     Result = V.getComplexFloatReal();
13792     return true;
13793   }
13794   }
13795 }
13796 
13797 //===----------------------------------------------------------------------===//
13798 // Complex Evaluation (for float and integer)
13799 //===----------------------------------------------------------------------===//
13800 
13801 namespace {
13802 class ComplexExprEvaluator
13803   : public ExprEvaluatorBase<ComplexExprEvaluator> {
13804   ComplexValue &Result;
13805 
13806 public:
13807   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
13808     : ExprEvaluatorBaseTy(info), Result(Result) {}
13809 
13810   bool Success(const APValue &V, const Expr *e) {
13811     Result.setFrom(V);
13812     return true;
13813   }
13814 
13815   bool ZeroInitialization(const Expr *E);
13816 
13817   //===--------------------------------------------------------------------===//
13818   //                            Visitor Methods
13819   //===--------------------------------------------------------------------===//
13820 
13821   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
13822   bool VisitCastExpr(const CastExpr *E);
13823   bool VisitBinaryOperator(const BinaryOperator *E);
13824   bool VisitUnaryOperator(const UnaryOperator *E);
13825   bool VisitInitListExpr(const InitListExpr *E);
13826   bool VisitCallExpr(const CallExpr *E);
13827 };
13828 } // end anonymous namespace
13829 
13830 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
13831                             EvalInfo &Info) {
13832   assert(!E->isValueDependent());
13833   assert(E->isRValue() && E->getType()->isAnyComplexType());
13834   return ComplexExprEvaluator(Info, Result).Visit(E);
13835 }
13836 
13837 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
13838   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
13839   if (ElemTy->isRealFloatingType()) {
13840     Result.makeComplexFloat();
13841     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
13842     Result.FloatReal = Zero;
13843     Result.FloatImag = Zero;
13844   } else {
13845     Result.makeComplexInt();
13846     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
13847     Result.IntReal = Zero;
13848     Result.IntImag = Zero;
13849   }
13850   return true;
13851 }
13852 
13853 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
13854   const Expr* SubExpr = E->getSubExpr();
13855 
13856   if (SubExpr->getType()->isRealFloatingType()) {
13857     Result.makeComplexFloat();
13858     APFloat &Imag = Result.FloatImag;
13859     if (!EvaluateFloat(SubExpr, Imag, Info))
13860       return false;
13861 
13862     Result.FloatReal = APFloat(Imag.getSemantics());
13863     return true;
13864   } else {
13865     assert(SubExpr->getType()->isIntegerType() &&
13866            "Unexpected imaginary literal.");
13867 
13868     Result.makeComplexInt();
13869     APSInt &Imag = Result.IntImag;
13870     if (!EvaluateInteger(SubExpr, Imag, Info))
13871       return false;
13872 
13873     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
13874     return true;
13875   }
13876 }
13877 
13878 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
13879 
13880   switch (E->getCastKind()) {
13881   case CK_BitCast:
13882   case CK_BaseToDerived:
13883   case CK_DerivedToBase:
13884   case CK_UncheckedDerivedToBase:
13885   case CK_Dynamic:
13886   case CK_ToUnion:
13887   case CK_ArrayToPointerDecay:
13888   case CK_FunctionToPointerDecay:
13889   case CK_NullToPointer:
13890   case CK_NullToMemberPointer:
13891   case CK_BaseToDerivedMemberPointer:
13892   case CK_DerivedToBaseMemberPointer:
13893   case CK_MemberPointerToBoolean:
13894   case CK_ReinterpretMemberPointer:
13895   case CK_ConstructorConversion:
13896   case CK_IntegralToPointer:
13897   case CK_PointerToIntegral:
13898   case CK_PointerToBoolean:
13899   case CK_ToVoid:
13900   case CK_VectorSplat:
13901   case CK_IntegralCast:
13902   case CK_BooleanToSignedIntegral:
13903   case CK_IntegralToBoolean:
13904   case CK_IntegralToFloating:
13905   case CK_FloatingToIntegral:
13906   case CK_FloatingToBoolean:
13907   case CK_FloatingCast:
13908   case CK_CPointerToObjCPointerCast:
13909   case CK_BlockPointerToObjCPointerCast:
13910   case CK_AnyPointerToBlockPointerCast:
13911   case CK_ObjCObjectLValueCast:
13912   case CK_FloatingComplexToReal:
13913   case CK_FloatingComplexToBoolean:
13914   case CK_IntegralComplexToReal:
13915   case CK_IntegralComplexToBoolean:
13916   case CK_ARCProduceObject:
13917   case CK_ARCConsumeObject:
13918   case CK_ARCReclaimReturnedObject:
13919   case CK_ARCExtendBlockObject:
13920   case CK_CopyAndAutoreleaseBlockObject:
13921   case CK_BuiltinFnToFnPtr:
13922   case CK_ZeroToOCLOpaqueType:
13923   case CK_NonAtomicToAtomic:
13924   case CK_AddressSpaceConversion:
13925   case CK_IntToOCLSampler:
13926   case CK_FloatingToFixedPoint:
13927   case CK_FixedPointToFloating:
13928   case CK_FixedPointCast:
13929   case CK_FixedPointToBoolean:
13930   case CK_FixedPointToIntegral:
13931   case CK_IntegralToFixedPoint:
13932     llvm_unreachable("invalid cast kind for complex value");
13933 
13934   case CK_LValueToRValue:
13935   case CK_AtomicToNonAtomic:
13936   case CK_NoOp:
13937   case CK_LValueToRValueBitCast:
13938     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13939 
13940   case CK_Dependent:
13941   case CK_LValueBitCast:
13942   case CK_UserDefinedConversion:
13943     return Error(E);
13944 
13945   case CK_FloatingRealToComplex: {
13946     APFloat &Real = Result.FloatReal;
13947     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
13948       return false;
13949 
13950     Result.makeComplexFloat();
13951     Result.FloatImag = APFloat(Real.getSemantics());
13952     return true;
13953   }
13954 
13955   case CK_FloatingComplexCast: {
13956     if (!Visit(E->getSubExpr()))
13957       return false;
13958 
13959     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13960     QualType From
13961       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13962 
13963     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
13964            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
13965   }
13966 
13967   case CK_FloatingComplexToIntegralComplex: {
13968     if (!Visit(E->getSubExpr()))
13969       return false;
13970 
13971     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13972     QualType From
13973       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13974     Result.makeComplexInt();
13975     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
13976                                 To, Result.IntReal) &&
13977            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
13978                                 To, Result.IntImag);
13979   }
13980 
13981   case CK_IntegralRealToComplex: {
13982     APSInt &Real = Result.IntReal;
13983     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
13984       return false;
13985 
13986     Result.makeComplexInt();
13987     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
13988     return true;
13989   }
13990 
13991   case CK_IntegralComplexCast: {
13992     if (!Visit(E->getSubExpr()))
13993       return false;
13994 
13995     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13996     QualType From
13997       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13998 
13999     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
14000     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
14001     return true;
14002   }
14003 
14004   case CK_IntegralComplexToFloatingComplex: {
14005     if (!Visit(E->getSubExpr()))
14006       return false;
14007 
14008     const FPOptions FPO = E->getFPFeaturesInEffect(
14009                                   Info.Ctx.getLangOpts());
14010     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14011     QualType From
14012       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14013     Result.makeComplexFloat();
14014     return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
14015                                 To, Result.FloatReal) &&
14016            HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
14017                                 To, Result.FloatImag);
14018   }
14019   }
14020 
14021   llvm_unreachable("unknown cast resulting in complex value");
14022 }
14023 
14024 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14025   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14026     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14027 
14028   // Track whether the LHS or RHS is real at the type system level. When this is
14029   // the case we can simplify our evaluation strategy.
14030   bool LHSReal = false, RHSReal = false;
14031 
14032   bool LHSOK;
14033   if (E->getLHS()->getType()->isRealFloatingType()) {
14034     LHSReal = true;
14035     APFloat &Real = Result.FloatReal;
14036     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14037     if (LHSOK) {
14038       Result.makeComplexFloat();
14039       Result.FloatImag = APFloat(Real.getSemantics());
14040     }
14041   } else {
14042     LHSOK = Visit(E->getLHS());
14043   }
14044   if (!LHSOK && !Info.noteFailure())
14045     return false;
14046 
14047   ComplexValue RHS;
14048   if (E->getRHS()->getType()->isRealFloatingType()) {
14049     RHSReal = true;
14050     APFloat &Real = RHS.FloatReal;
14051     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
14052       return false;
14053     RHS.makeComplexFloat();
14054     RHS.FloatImag = APFloat(Real.getSemantics());
14055   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14056     return false;
14057 
14058   assert(!(LHSReal && RHSReal) &&
14059          "Cannot have both operands of a complex operation be real.");
14060   switch (E->getOpcode()) {
14061   default: return Error(E);
14062   case BO_Add:
14063     if (Result.isComplexFloat()) {
14064       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14065                                        APFloat::rmNearestTiesToEven);
14066       if (LHSReal)
14067         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14068       else if (!RHSReal)
14069         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14070                                          APFloat::rmNearestTiesToEven);
14071     } else {
14072       Result.getComplexIntReal() += RHS.getComplexIntReal();
14073       Result.getComplexIntImag() += RHS.getComplexIntImag();
14074     }
14075     break;
14076   case BO_Sub:
14077     if (Result.isComplexFloat()) {
14078       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14079                                             APFloat::rmNearestTiesToEven);
14080       if (LHSReal) {
14081         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14082         Result.getComplexFloatImag().changeSign();
14083       } else if (!RHSReal) {
14084         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14085                                               APFloat::rmNearestTiesToEven);
14086       }
14087     } else {
14088       Result.getComplexIntReal() -= RHS.getComplexIntReal();
14089       Result.getComplexIntImag() -= RHS.getComplexIntImag();
14090     }
14091     break;
14092   case BO_Mul:
14093     if (Result.isComplexFloat()) {
14094       // This is an implementation of complex multiplication according to the
14095       // constraints laid out in C11 Annex G. The implementation uses the
14096       // following naming scheme:
14097       //   (a + ib) * (c + id)
14098       ComplexValue LHS = Result;
14099       APFloat &A = LHS.getComplexFloatReal();
14100       APFloat &B = LHS.getComplexFloatImag();
14101       APFloat &C = RHS.getComplexFloatReal();
14102       APFloat &D = RHS.getComplexFloatImag();
14103       APFloat &ResR = Result.getComplexFloatReal();
14104       APFloat &ResI = Result.getComplexFloatImag();
14105       if (LHSReal) {
14106         assert(!RHSReal && "Cannot have two real operands for a complex op!");
14107         ResR = A * C;
14108         ResI = A * D;
14109       } else if (RHSReal) {
14110         ResR = C * A;
14111         ResI = C * B;
14112       } else {
14113         // In the fully general case, we need to handle NaNs and infinities
14114         // robustly.
14115         APFloat AC = A * C;
14116         APFloat BD = B * D;
14117         APFloat AD = A * D;
14118         APFloat BC = B * C;
14119         ResR = AC - BD;
14120         ResI = AD + BC;
14121         if (ResR.isNaN() && ResI.isNaN()) {
14122           bool Recalc = false;
14123           if (A.isInfinity() || B.isInfinity()) {
14124             A = APFloat::copySign(
14125                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14126             B = APFloat::copySign(
14127                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14128             if (C.isNaN())
14129               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14130             if (D.isNaN())
14131               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14132             Recalc = true;
14133           }
14134           if (C.isInfinity() || D.isInfinity()) {
14135             C = APFloat::copySign(
14136                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14137             D = APFloat::copySign(
14138                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14139             if (A.isNaN())
14140               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14141             if (B.isNaN())
14142               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14143             Recalc = true;
14144           }
14145           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14146                           AD.isInfinity() || BC.isInfinity())) {
14147             if (A.isNaN())
14148               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14149             if (B.isNaN())
14150               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14151             if (C.isNaN())
14152               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14153             if (D.isNaN())
14154               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14155             Recalc = true;
14156           }
14157           if (Recalc) {
14158             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14159             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14160           }
14161         }
14162       }
14163     } else {
14164       ComplexValue LHS = Result;
14165       Result.getComplexIntReal() =
14166         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14167          LHS.getComplexIntImag() * RHS.getComplexIntImag());
14168       Result.getComplexIntImag() =
14169         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14170          LHS.getComplexIntImag() * RHS.getComplexIntReal());
14171     }
14172     break;
14173   case BO_Div:
14174     if (Result.isComplexFloat()) {
14175       // This is an implementation of complex division according to the
14176       // constraints laid out in C11 Annex G. The implementation uses the
14177       // following naming scheme:
14178       //   (a + ib) / (c + id)
14179       ComplexValue LHS = Result;
14180       APFloat &A = LHS.getComplexFloatReal();
14181       APFloat &B = LHS.getComplexFloatImag();
14182       APFloat &C = RHS.getComplexFloatReal();
14183       APFloat &D = RHS.getComplexFloatImag();
14184       APFloat &ResR = Result.getComplexFloatReal();
14185       APFloat &ResI = Result.getComplexFloatImag();
14186       if (RHSReal) {
14187         ResR = A / C;
14188         ResI = B / C;
14189       } else {
14190         if (LHSReal) {
14191           // No real optimizations we can do here, stub out with zero.
14192           B = APFloat::getZero(A.getSemantics());
14193         }
14194         int DenomLogB = 0;
14195         APFloat MaxCD = maxnum(abs(C), abs(D));
14196         if (MaxCD.isFinite()) {
14197           DenomLogB = ilogb(MaxCD);
14198           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14199           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14200         }
14201         APFloat Denom = C * C + D * D;
14202         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14203                       APFloat::rmNearestTiesToEven);
14204         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14205                       APFloat::rmNearestTiesToEven);
14206         if (ResR.isNaN() && ResI.isNaN()) {
14207           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14208             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14209             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14210           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14211                      D.isFinite()) {
14212             A = APFloat::copySign(
14213                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14214             B = APFloat::copySign(
14215                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14216             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14217             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14218           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14219             C = APFloat::copySign(
14220                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14221             D = APFloat::copySign(
14222                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14223             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14224             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14225           }
14226         }
14227       }
14228     } else {
14229       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14230         return Error(E, diag::note_expr_divide_by_zero);
14231 
14232       ComplexValue LHS = Result;
14233       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14234         RHS.getComplexIntImag() * RHS.getComplexIntImag();
14235       Result.getComplexIntReal() =
14236         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14237          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14238       Result.getComplexIntImag() =
14239         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14240          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14241     }
14242     break;
14243   }
14244 
14245   return true;
14246 }
14247 
14248 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14249   // Get the operand value into 'Result'.
14250   if (!Visit(E->getSubExpr()))
14251     return false;
14252 
14253   switch (E->getOpcode()) {
14254   default:
14255     return Error(E);
14256   case UO_Extension:
14257     return true;
14258   case UO_Plus:
14259     // The result is always just the subexpr.
14260     return true;
14261   case UO_Minus:
14262     if (Result.isComplexFloat()) {
14263       Result.getComplexFloatReal().changeSign();
14264       Result.getComplexFloatImag().changeSign();
14265     }
14266     else {
14267       Result.getComplexIntReal() = -Result.getComplexIntReal();
14268       Result.getComplexIntImag() = -Result.getComplexIntImag();
14269     }
14270     return true;
14271   case UO_Not:
14272     if (Result.isComplexFloat())
14273       Result.getComplexFloatImag().changeSign();
14274     else
14275       Result.getComplexIntImag() = -Result.getComplexIntImag();
14276     return true;
14277   }
14278 }
14279 
14280 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14281   if (E->getNumInits() == 2) {
14282     if (E->getType()->isComplexType()) {
14283       Result.makeComplexFloat();
14284       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14285         return false;
14286       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14287         return false;
14288     } else {
14289       Result.makeComplexInt();
14290       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14291         return false;
14292       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14293         return false;
14294     }
14295     return true;
14296   }
14297   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14298 }
14299 
14300 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14301   switch (E->getBuiltinCallee()) {
14302   case Builtin::BI__builtin_complex:
14303     Result.makeComplexFloat();
14304     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14305       return false;
14306     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14307       return false;
14308     return true;
14309 
14310   default:
14311     break;
14312   }
14313 
14314   return ExprEvaluatorBaseTy::VisitCallExpr(E);
14315 }
14316 
14317 //===----------------------------------------------------------------------===//
14318 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14319 // implicit conversion.
14320 //===----------------------------------------------------------------------===//
14321 
14322 namespace {
14323 class AtomicExprEvaluator :
14324     public ExprEvaluatorBase<AtomicExprEvaluator> {
14325   const LValue *This;
14326   APValue &Result;
14327 public:
14328   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14329       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14330 
14331   bool Success(const APValue &V, const Expr *E) {
14332     Result = V;
14333     return true;
14334   }
14335 
14336   bool ZeroInitialization(const Expr *E) {
14337     ImplicitValueInitExpr VIE(
14338         E->getType()->castAs<AtomicType>()->getValueType());
14339     // For atomic-qualified class (and array) types in C++, initialize the
14340     // _Atomic-wrapped subobject directly, in-place.
14341     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14342                 : Evaluate(Result, Info, &VIE);
14343   }
14344 
14345   bool VisitCastExpr(const CastExpr *E) {
14346     switch (E->getCastKind()) {
14347     default:
14348       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14349     case CK_NonAtomicToAtomic:
14350       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14351                   : Evaluate(Result, Info, E->getSubExpr());
14352     }
14353   }
14354 };
14355 } // end anonymous namespace
14356 
14357 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14358                            EvalInfo &Info) {
14359   assert(!E->isValueDependent());
14360   assert(E->isRValue() && E->getType()->isAtomicType());
14361   return AtomicExprEvaluator(Info, This, Result).Visit(E);
14362 }
14363 
14364 //===----------------------------------------------------------------------===//
14365 // Void expression evaluation, primarily for a cast to void on the LHS of a
14366 // comma operator
14367 //===----------------------------------------------------------------------===//
14368 
14369 namespace {
14370 class VoidExprEvaluator
14371   : public ExprEvaluatorBase<VoidExprEvaluator> {
14372 public:
14373   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14374 
14375   bool Success(const APValue &V, const Expr *e) { return true; }
14376 
14377   bool ZeroInitialization(const Expr *E) { return true; }
14378 
14379   bool VisitCastExpr(const CastExpr *E) {
14380     switch (E->getCastKind()) {
14381     default:
14382       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14383     case CK_ToVoid:
14384       VisitIgnoredValue(E->getSubExpr());
14385       return true;
14386     }
14387   }
14388 
14389   bool VisitCallExpr(const CallExpr *E) {
14390     switch (E->getBuiltinCallee()) {
14391     case Builtin::BI__assume:
14392     case Builtin::BI__builtin_assume:
14393       // The argument is not evaluated!
14394       return true;
14395 
14396     case Builtin::BI__builtin_operator_delete:
14397       return HandleOperatorDeleteCall(Info, E);
14398 
14399     default:
14400       break;
14401     }
14402 
14403     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14404   }
14405 
14406   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14407 };
14408 } // end anonymous namespace
14409 
14410 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14411   // We cannot speculatively evaluate a delete expression.
14412   if (Info.SpeculativeEvaluationDepth)
14413     return false;
14414 
14415   FunctionDecl *OperatorDelete = E->getOperatorDelete();
14416   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14417     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14418         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14419     return false;
14420   }
14421 
14422   const Expr *Arg = E->getArgument();
14423 
14424   LValue Pointer;
14425   if (!EvaluatePointer(Arg, Pointer, Info))
14426     return false;
14427   if (Pointer.Designator.Invalid)
14428     return false;
14429 
14430   // Deleting a null pointer has no effect.
14431   if (Pointer.isNullPointer()) {
14432     // This is the only case where we need to produce an extension warning:
14433     // the only other way we can succeed is if we find a dynamic allocation,
14434     // and we will have warned when we allocated it in that case.
14435     if (!Info.getLangOpts().CPlusPlus20)
14436       Info.CCEDiag(E, diag::note_constexpr_new);
14437     return true;
14438   }
14439 
14440   Optional<DynAlloc *> Alloc = CheckDeleteKind(
14441       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14442   if (!Alloc)
14443     return false;
14444   QualType AllocType = Pointer.Base.getDynamicAllocType();
14445 
14446   // For the non-array case, the designator must be empty if the static type
14447   // does not have a virtual destructor.
14448   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14449       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14450     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14451         << Arg->getType()->getPointeeType() << AllocType;
14452     return false;
14453   }
14454 
14455   // For a class type with a virtual destructor, the selected operator delete
14456   // is the one looked up when building the destructor.
14457   if (!E->isArrayForm() && !E->isGlobalDelete()) {
14458     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14459     if (VirtualDelete &&
14460         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14461       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14462           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14463       return false;
14464     }
14465   }
14466 
14467   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14468                          (*Alloc)->Value, AllocType))
14469     return false;
14470 
14471   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14472     // The element was already erased. This means the destructor call also
14473     // deleted the object.
14474     // FIXME: This probably results in undefined behavior before we get this
14475     // far, and should be diagnosed elsewhere first.
14476     Info.FFDiag(E, diag::note_constexpr_double_delete);
14477     return false;
14478   }
14479 
14480   return true;
14481 }
14482 
14483 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14484   assert(!E->isValueDependent());
14485   assert(E->isRValue() && E->getType()->isVoidType());
14486   return VoidExprEvaluator(Info).Visit(E);
14487 }
14488 
14489 //===----------------------------------------------------------------------===//
14490 // Top level Expr::EvaluateAsRValue method.
14491 //===----------------------------------------------------------------------===//
14492 
14493 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14494   assert(!E->isValueDependent());
14495   // In C, function designators are not lvalues, but we evaluate them as if they
14496   // are.
14497   QualType T = E->getType();
14498   if (E->isGLValue() || T->isFunctionType()) {
14499     LValue LV;
14500     if (!EvaluateLValue(E, LV, Info))
14501       return false;
14502     LV.moveInto(Result);
14503   } else if (T->isVectorType()) {
14504     if (!EvaluateVector(E, Result, Info))
14505       return false;
14506   } else if (T->isIntegralOrEnumerationType()) {
14507     if (!IntExprEvaluator(Info, Result).Visit(E))
14508       return false;
14509   } else if (T->hasPointerRepresentation()) {
14510     LValue LV;
14511     if (!EvaluatePointer(E, LV, Info))
14512       return false;
14513     LV.moveInto(Result);
14514   } else if (T->isRealFloatingType()) {
14515     llvm::APFloat F(0.0);
14516     if (!EvaluateFloat(E, F, Info))
14517       return false;
14518     Result = APValue(F);
14519   } else if (T->isAnyComplexType()) {
14520     ComplexValue C;
14521     if (!EvaluateComplex(E, C, Info))
14522       return false;
14523     C.moveInto(Result);
14524   } else if (T->isFixedPointType()) {
14525     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
14526   } else if (T->isMemberPointerType()) {
14527     MemberPtr P;
14528     if (!EvaluateMemberPointer(E, P, Info))
14529       return false;
14530     P.moveInto(Result);
14531     return true;
14532   } else if (T->isArrayType()) {
14533     LValue LV;
14534     APValue &Value =
14535         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14536     if (!EvaluateArray(E, LV, Value, Info))
14537       return false;
14538     Result = Value;
14539   } else if (T->isRecordType()) {
14540     LValue LV;
14541     APValue &Value =
14542         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14543     if (!EvaluateRecord(E, LV, Value, Info))
14544       return false;
14545     Result = Value;
14546   } else if (T->isVoidType()) {
14547     if (!Info.getLangOpts().CPlusPlus11)
14548       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
14549         << E->getType();
14550     if (!EvaluateVoid(E, Info))
14551       return false;
14552   } else if (T->isAtomicType()) {
14553     QualType Unqual = T.getAtomicUnqualifiedType();
14554     if (Unqual->isArrayType() || Unqual->isRecordType()) {
14555       LValue LV;
14556       APValue &Value = Info.CurrentCall->createTemporary(
14557           E, Unqual, ScopeKind::FullExpression, LV);
14558       if (!EvaluateAtomic(E, &LV, Value, Info))
14559         return false;
14560     } else {
14561       if (!EvaluateAtomic(E, nullptr, Result, Info))
14562         return false;
14563     }
14564   } else if (Info.getLangOpts().CPlusPlus11) {
14565     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
14566     return false;
14567   } else {
14568     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14569     return false;
14570   }
14571 
14572   return true;
14573 }
14574 
14575 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
14576 /// cases, the in-place evaluation is essential, since later initializers for
14577 /// an object can indirectly refer to subobjects which were initialized earlier.
14578 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
14579                             const Expr *E, bool AllowNonLiteralTypes) {
14580   assert(!E->isValueDependent());
14581 
14582   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
14583     return false;
14584 
14585   if (E->isRValue()) {
14586     // Evaluate arrays and record types in-place, so that later initializers can
14587     // refer to earlier-initialized members of the object.
14588     QualType T = E->getType();
14589     if (T->isArrayType())
14590       return EvaluateArray(E, This, Result, Info);
14591     else if (T->isRecordType())
14592       return EvaluateRecord(E, This, Result, Info);
14593     else if (T->isAtomicType()) {
14594       QualType Unqual = T.getAtomicUnqualifiedType();
14595       if (Unqual->isArrayType() || Unqual->isRecordType())
14596         return EvaluateAtomic(E, &This, Result, Info);
14597     }
14598   }
14599 
14600   // For any other type, in-place evaluation is unimportant.
14601   return Evaluate(Result, Info, E);
14602 }
14603 
14604 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
14605 /// lvalue-to-rvalue cast if it is an lvalue.
14606 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
14607   assert(!E->isValueDependent());
14608   if (Info.EnableNewConstInterp) {
14609     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
14610       return false;
14611   } else {
14612     if (E->getType().isNull())
14613       return false;
14614 
14615     if (!CheckLiteralType(Info, E))
14616       return false;
14617 
14618     if (!::Evaluate(Result, Info, E))
14619       return false;
14620 
14621     if (E->isGLValue()) {
14622       LValue LV;
14623       LV.setFrom(Info.Ctx, Result);
14624       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14625         return false;
14626     }
14627   }
14628 
14629   // Check this core constant expression is a constant expression.
14630   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
14631                                  ConstantExprKind::Normal) &&
14632          CheckMemoryLeaks(Info);
14633 }
14634 
14635 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
14636                                  const ASTContext &Ctx, bool &IsConst) {
14637   // Fast-path evaluations of integer literals, since we sometimes see files
14638   // containing vast quantities of these.
14639   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
14640     Result.Val = APValue(APSInt(L->getValue(),
14641                                 L->getType()->isUnsignedIntegerType()));
14642     IsConst = true;
14643     return true;
14644   }
14645 
14646   // This case should be rare, but we need to check it before we check on
14647   // the type below.
14648   if (Exp->getType().isNull()) {
14649     IsConst = false;
14650     return true;
14651   }
14652 
14653   // FIXME: Evaluating values of large array and record types can cause
14654   // performance problems. Only do so in C++11 for now.
14655   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
14656                           Exp->getType()->isRecordType()) &&
14657       !Ctx.getLangOpts().CPlusPlus11) {
14658     IsConst = false;
14659     return true;
14660   }
14661   return false;
14662 }
14663 
14664 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
14665                                       Expr::SideEffectsKind SEK) {
14666   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
14667          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
14668 }
14669 
14670 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
14671                              const ASTContext &Ctx, EvalInfo &Info) {
14672   assert(!E->isValueDependent());
14673   bool IsConst;
14674   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
14675     return IsConst;
14676 
14677   return EvaluateAsRValue(Info, E, Result.Val);
14678 }
14679 
14680 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
14681                           const ASTContext &Ctx,
14682                           Expr::SideEffectsKind AllowSideEffects,
14683                           EvalInfo &Info) {
14684   assert(!E->isValueDependent());
14685   if (!E->getType()->isIntegralOrEnumerationType())
14686     return false;
14687 
14688   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
14689       !ExprResult.Val.isInt() ||
14690       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14691     return false;
14692 
14693   return true;
14694 }
14695 
14696 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
14697                                  const ASTContext &Ctx,
14698                                  Expr::SideEffectsKind AllowSideEffects,
14699                                  EvalInfo &Info) {
14700   assert(!E->isValueDependent());
14701   if (!E->getType()->isFixedPointType())
14702     return false;
14703 
14704   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
14705     return false;
14706 
14707   if (!ExprResult.Val.isFixedPoint() ||
14708       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14709     return false;
14710 
14711   return true;
14712 }
14713 
14714 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
14715 /// any crazy technique (that has nothing to do with language standards) that
14716 /// we want to.  If this function returns true, it returns the folded constant
14717 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
14718 /// will be applied to the result.
14719 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
14720                             bool InConstantContext) const {
14721   assert(!isValueDependent() &&
14722          "Expression evaluator can't be called on a dependent expression.");
14723   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14724   Info.InConstantContext = InConstantContext;
14725   return ::EvaluateAsRValue(this, Result, Ctx, Info);
14726 }
14727 
14728 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
14729                                       bool InConstantContext) const {
14730   assert(!isValueDependent() &&
14731          "Expression evaluator can't be called on a dependent expression.");
14732   EvalResult Scratch;
14733   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
14734          HandleConversionToBool(Scratch.Val, Result);
14735 }
14736 
14737 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
14738                          SideEffectsKind AllowSideEffects,
14739                          bool InConstantContext) const {
14740   assert(!isValueDependent() &&
14741          "Expression evaluator can't be called on a dependent expression.");
14742   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14743   Info.InConstantContext = InConstantContext;
14744   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
14745 }
14746 
14747 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
14748                                 SideEffectsKind AllowSideEffects,
14749                                 bool InConstantContext) const {
14750   assert(!isValueDependent() &&
14751          "Expression evaluator can't be called on a dependent expression.");
14752   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14753   Info.InConstantContext = InConstantContext;
14754   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
14755 }
14756 
14757 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
14758                            SideEffectsKind AllowSideEffects,
14759                            bool InConstantContext) const {
14760   assert(!isValueDependent() &&
14761          "Expression evaluator can't be called on a dependent expression.");
14762 
14763   if (!getType()->isRealFloatingType())
14764     return false;
14765 
14766   EvalResult ExprResult;
14767   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
14768       !ExprResult.Val.isFloat() ||
14769       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14770     return false;
14771 
14772   Result = ExprResult.Val.getFloat();
14773   return true;
14774 }
14775 
14776 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
14777                             bool InConstantContext) const {
14778   assert(!isValueDependent() &&
14779          "Expression evaluator can't be called on a dependent expression.");
14780 
14781   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
14782   Info.InConstantContext = InConstantContext;
14783   LValue LV;
14784   CheckedTemporaries CheckedTemps;
14785   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
14786       Result.HasSideEffects ||
14787       !CheckLValueConstantExpression(Info, getExprLoc(),
14788                                      Ctx.getLValueReferenceType(getType()), LV,
14789                                      ConstantExprKind::Normal, CheckedTemps))
14790     return false;
14791 
14792   LV.moveInto(Result.Val);
14793   return true;
14794 }
14795 
14796 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
14797                                 APValue DestroyedValue, QualType Type,
14798                                 SourceLocation Loc, Expr::EvalStatus &EStatus,
14799                                 bool IsConstantDestruction) {
14800   EvalInfo Info(Ctx, EStatus,
14801                 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
14802                                       : EvalInfo::EM_ConstantFold);
14803   Info.setEvaluatingDecl(Base, DestroyedValue,
14804                          EvalInfo::EvaluatingDeclKind::Dtor);
14805   Info.InConstantContext = IsConstantDestruction;
14806 
14807   LValue LVal;
14808   LVal.set(Base);
14809 
14810   if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
14811       EStatus.HasSideEffects)
14812     return false;
14813 
14814   if (!Info.discardCleanups())
14815     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14816 
14817   return true;
14818 }
14819 
14820 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
14821                                   ConstantExprKind Kind) const {
14822   assert(!isValueDependent() &&
14823          "Expression evaluator can't be called on a dependent expression.");
14824 
14825   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
14826   EvalInfo Info(Ctx, Result, EM);
14827   Info.InConstantContext = true;
14828 
14829   // The type of the object we're initializing is 'const T' for a class NTTP.
14830   QualType T = getType();
14831   if (Kind == ConstantExprKind::ClassTemplateArgument)
14832     T.addConst();
14833 
14834   // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
14835   // represent the result of the evaluation. CheckConstantExpression ensures
14836   // this doesn't escape.
14837   MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
14838   APValue::LValueBase Base(&BaseMTE);
14839 
14840   Info.setEvaluatingDecl(Base, Result.Val);
14841   LValue LVal;
14842   LVal.set(Base);
14843 
14844   if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects)
14845     return false;
14846 
14847   if (!Info.discardCleanups())
14848     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14849 
14850   if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
14851                                Result.Val, Kind))
14852     return false;
14853   if (!CheckMemoryLeaks(Info))
14854     return false;
14855 
14856   // If this is a class template argument, it's required to have constant
14857   // destruction too.
14858   if (Kind == ConstantExprKind::ClassTemplateArgument &&
14859       (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
14860                             true) ||
14861        Result.HasSideEffects)) {
14862     // FIXME: Prefix a note to indicate that the problem is lack of constant
14863     // destruction.
14864     return false;
14865   }
14866 
14867   return true;
14868 }
14869 
14870 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
14871                                  const VarDecl *VD,
14872                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
14873   assert(!isValueDependent() &&
14874          "Expression evaluator can't be called on a dependent expression.");
14875 
14876   // FIXME: Evaluating initializers for large array and record types can cause
14877   // performance problems. Only do so in C++11 for now.
14878   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
14879       !Ctx.getLangOpts().CPlusPlus11)
14880     return false;
14881 
14882   Expr::EvalStatus EStatus;
14883   EStatus.Diag = &Notes;
14884 
14885   EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
14886                                       ? EvalInfo::EM_ConstantExpression
14887                                       : EvalInfo::EM_ConstantFold);
14888   Info.setEvaluatingDecl(VD, Value);
14889   Info.InConstantContext = true;
14890 
14891   SourceLocation DeclLoc = VD->getLocation();
14892   QualType DeclTy = VD->getType();
14893 
14894   if (Info.EnableNewConstInterp) {
14895     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
14896     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
14897       return false;
14898   } else {
14899     LValue LVal;
14900     LVal.set(VD);
14901 
14902     if (!EvaluateInPlace(Value, Info, LVal, this,
14903                          /*AllowNonLiteralTypes=*/true) ||
14904         EStatus.HasSideEffects)
14905       return false;
14906 
14907     // At this point, any lifetime-extended temporaries are completely
14908     // initialized.
14909     Info.performLifetimeExtension();
14910 
14911     if (!Info.discardCleanups())
14912       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14913   }
14914   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
14915                                  ConstantExprKind::Normal) &&
14916          CheckMemoryLeaks(Info);
14917 }
14918 
14919 bool VarDecl::evaluateDestruction(
14920     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
14921   Expr::EvalStatus EStatus;
14922   EStatus.Diag = &Notes;
14923 
14924   // Only treat the destruction as constant destruction if we formally have
14925   // constant initialization (or are usable in a constant expression).
14926   bool IsConstantDestruction = hasConstantInitialization();
14927 
14928   // Make a copy of the value for the destructor to mutate, if we know it.
14929   // Otherwise, treat the value as default-initialized; if the destructor works
14930   // anyway, then the destruction is constant (and must be essentially empty).
14931   APValue DestroyedValue;
14932   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
14933     DestroyedValue = *getEvaluatedValue();
14934   else if (!getDefaultInitValue(getType(), DestroyedValue))
14935     return false;
14936 
14937   if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
14938                            getType(), getLocation(), EStatus,
14939                            IsConstantDestruction) ||
14940       EStatus.HasSideEffects)
14941     return false;
14942 
14943   ensureEvaluatedStmt()->HasConstantDestruction = true;
14944   return true;
14945 }
14946 
14947 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
14948 /// constant folded, but discard the result.
14949 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
14950   assert(!isValueDependent() &&
14951          "Expression evaluator can't be called on a dependent expression.");
14952 
14953   EvalResult Result;
14954   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
14955          !hasUnacceptableSideEffect(Result, SEK);
14956 }
14957 
14958 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
14959                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14960   assert(!isValueDependent() &&
14961          "Expression evaluator can't be called on a dependent expression.");
14962 
14963   EvalResult EVResult;
14964   EVResult.Diag = Diag;
14965   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14966   Info.InConstantContext = true;
14967 
14968   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
14969   (void)Result;
14970   assert(Result && "Could not evaluate expression");
14971   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14972 
14973   return EVResult.Val.getInt();
14974 }
14975 
14976 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
14977     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14978   assert(!isValueDependent() &&
14979          "Expression evaluator can't be called on a dependent expression.");
14980 
14981   EvalResult EVResult;
14982   EVResult.Diag = Diag;
14983   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14984   Info.InConstantContext = true;
14985   Info.CheckingForUndefinedBehavior = true;
14986 
14987   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
14988   (void)Result;
14989   assert(Result && "Could not evaluate expression");
14990   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14991 
14992   return EVResult.Val.getInt();
14993 }
14994 
14995 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
14996   assert(!isValueDependent() &&
14997          "Expression evaluator can't be called on a dependent expression.");
14998 
14999   bool IsConst;
15000   EvalResult EVResult;
15001   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
15002     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15003     Info.CheckingForUndefinedBehavior = true;
15004     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
15005   }
15006 }
15007 
15008 bool Expr::EvalResult::isGlobalLValue() const {
15009   assert(Val.isLValue());
15010   return IsGlobalLValue(Val.getLValueBase());
15011 }
15012 
15013 /// isIntegerConstantExpr - this recursive routine will test if an expression is
15014 /// an integer constant expression.
15015 
15016 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
15017 /// comma, etc
15018 
15019 // CheckICE - This function does the fundamental ICE checking: the returned
15020 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15021 // and a (possibly null) SourceLocation indicating the location of the problem.
15022 //
15023 // Note that to reduce code duplication, this helper does no evaluation
15024 // itself; the caller checks whether the expression is evaluatable, and
15025 // in the rare cases where CheckICE actually cares about the evaluated
15026 // value, it calls into Evaluate.
15027 
15028 namespace {
15029 
15030 enum ICEKind {
15031   /// This expression is an ICE.
15032   IK_ICE,
15033   /// This expression is not an ICE, but if it isn't evaluated, it's
15034   /// a legal subexpression for an ICE. This return value is used to handle
15035   /// the comma operator in C99 mode, and non-constant subexpressions.
15036   IK_ICEIfUnevaluated,
15037   /// This expression is not an ICE, and is not a legal subexpression for one.
15038   IK_NotICE
15039 };
15040 
15041 struct ICEDiag {
15042   ICEKind Kind;
15043   SourceLocation Loc;
15044 
15045   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15046 };
15047 
15048 }
15049 
15050 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15051 
15052 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
15053 
15054 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15055   Expr::EvalResult EVResult;
15056   Expr::EvalStatus Status;
15057   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15058 
15059   Info.InConstantContext = true;
15060   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
15061       !EVResult.Val.isInt())
15062     return ICEDiag(IK_NotICE, E->getBeginLoc());
15063 
15064   return NoDiag();
15065 }
15066 
15067 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15068   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
15069   if (!E->getType()->isIntegralOrEnumerationType())
15070     return ICEDiag(IK_NotICE, E->getBeginLoc());
15071 
15072   switch (E->getStmtClass()) {
15073 #define ABSTRACT_STMT(Node)
15074 #define STMT(Node, Base) case Expr::Node##Class:
15075 #define EXPR(Node, Base)
15076 #include "clang/AST/StmtNodes.inc"
15077   case Expr::PredefinedExprClass:
15078   case Expr::FloatingLiteralClass:
15079   case Expr::ImaginaryLiteralClass:
15080   case Expr::StringLiteralClass:
15081   case Expr::ArraySubscriptExprClass:
15082   case Expr::MatrixSubscriptExprClass:
15083   case Expr::OMPArraySectionExprClass:
15084   case Expr::OMPArrayShapingExprClass:
15085   case Expr::OMPIteratorExprClass:
15086   case Expr::MemberExprClass:
15087   case Expr::CompoundAssignOperatorClass:
15088   case Expr::CompoundLiteralExprClass:
15089   case Expr::ExtVectorElementExprClass:
15090   case Expr::DesignatedInitExprClass:
15091   case Expr::ArrayInitLoopExprClass:
15092   case Expr::ArrayInitIndexExprClass:
15093   case Expr::NoInitExprClass:
15094   case Expr::DesignatedInitUpdateExprClass:
15095   case Expr::ImplicitValueInitExprClass:
15096   case Expr::ParenListExprClass:
15097   case Expr::VAArgExprClass:
15098   case Expr::AddrLabelExprClass:
15099   case Expr::StmtExprClass:
15100   case Expr::CXXMemberCallExprClass:
15101   case Expr::CUDAKernelCallExprClass:
15102   case Expr::CXXAddrspaceCastExprClass:
15103   case Expr::CXXDynamicCastExprClass:
15104   case Expr::CXXTypeidExprClass:
15105   case Expr::CXXUuidofExprClass:
15106   case Expr::MSPropertyRefExprClass:
15107   case Expr::MSPropertySubscriptExprClass:
15108   case Expr::CXXNullPtrLiteralExprClass:
15109   case Expr::UserDefinedLiteralClass:
15110   case Expr::CXXThisExprClass:
15111   case Expr::CXXThrowExprClass:
15112   case Expr::CXXNewExprClass:
15113   case Expr::CXXDeleteExprClass:
15114   case Expr::CXXPseudoDestructorExprClass:
15115   case Expr::UnresolvedLookupExprClass:
15116   case Expr::TypoExprClass:
15117   case Expr::RecoveryExprClass:
15118   case Expr::DependentScopeDeclRefExprClass:
15119   case Expr::CXXConstructExprClass:
15120   case Expr::CXXInheritedCtorInitExprClass:
15121   case Expr::CXXStdInitializerListExprClass:
15122   case Expr::CXXBindTemporaryExprClass:
15123   case Expr::ExprWithCleanupsClass:
15124   case Expr::CXXTemporaryObjectExprClass:
15125   case Expr::CXXUnresolvedConstructExprClass:
15126   case Expr::CXXDependentScopeMemberExprClass:
15127   case Expr::UnresolvedMemberExprClass:
15128   case Expr::ObjCStringLiteralClass:
15129   case Expr::ObjCBoxedExprClass:
15130   case Expr::ObjCArrayLiteralClass:
15131   case Expr::ObjCDictionaryLiteralClass:
15132   case Expr::ObjCEncodeExprClass:
15133   case Expr::ObjCMessageExprClass:
15134   case Expr::ObjCSelectorExprClass:
15135   case Expr::ObjCProtocolExprClass:
15136   case Expr::ObjCIvarRefExprClass:
15137   case Expr::ObjCPropertyRefExprClass:
15138   case Expr::ObjCSubscriptRefExprClass:
15139   case Expr::ObjCIsaExprClass:
15140   case Expr::ObjCAvailabilityCheckExprClass:
15141   case Expr::ShuffleVectorExprClass:
15142   case Expr::ConvertVectorExprClass:
15143   case Expr::BlockExprClass:
15144   case Expr::NoStmtClass:
15145   case Expr::OpaqueValueExprClass:
15146   case Expr::PackExpansionExprClass:
15147   case Expr::SubstNonTypeTemplateParmPackExprClass:
15148   case Expr::FunctionParmPackExprClass:
15149   case Expr::AsTypeExprClass:
15150   case Expr::ObjCIndirectCopyRestoreExprClass:
15151   case Expr::MaterializeTemporaryExprClass:
15152   case Expr::PseudoObjectExprClass:
15153   case Expr::AtomicExprClass:
15154   case Expr::LambdaExprClass:
15155   case Expr::CXXFoldExprClass:
15156   case Expr::CoawaitExprClass:
15157   case Expr::DependentCoawaitExprClass:
15158   case Expr::CoyieldExprClass:
15159     return ICEDiag(IK_NotICE, E->getBeginLoc());
15160 
15161   case Expr::InitListExprClass: {
15162     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
15163     // form "T x = { a };" is equivalent to "T x = a;".
15164     // Unless we're initializing a reference, T is a scalar as it is known to be
15165     // of integral or enumeration type.
15166     if (E->isRValue())
15167       if (cast<InitListExpr>(E)->getNumInits() == 1)
15168         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
15169     return ICEDiag(IK_NotICE, E->getBeginLoc());
15170   }
15171 
15172   case Expr::SizeOfPackExprClass:
15173   case Expr::GNUNullExprClass:
15174   case Expr::SourceLocExprClass:
15175     return NoDiag();
15176 
15177   case Expr::SubstNonTypeTemplateParmExprClass:
15178     return
15179       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
15180 
15181   case Expr::ConstantExprClass:
15182     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
15183 
15184   case Expr::ParenExprClass:
15185     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15186   case Expr::GenericSelectionExprClass:
15187     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15188   case Expr::IntegerLiteralClass:
15189   case Expr::FixedPointLiteralClass:
15190   case Expr::CharacterLiteralClass:
15191   case Expr::ObjCBoolLiteralExprClass:
15192   case Expr::CXXBoolLiteralExprClass:
15193   case Expr::CXXScalarValueInitExprClass:
15194   case Expr::TypeTraitExprClass:
15195   case Expr::ConceptSpecializationExprClass:
15196   case Expr::RequiresExprClass:
15197   case Expr::ArrayTypeTraitExprClass:
15198   case Expr::ExpressionTraitExprClass:
15199   case Expr::CXXNoexceptExprClass:
15200     return NoDiag();
15201   case Expr::CallExprClass:
15202   case Expr::CXXOperatorCallExprClass: {
15203     // C99 6.6/3 allows function calls within unevaluated subexpressions of
15204     // constant expressions, but they can never be ICEs because an ICE cannot
15205     // contain an operand of (pointer to) function type.
15206     const CallExpr *CE = cast<CallExpr>(E);
15207     if (CE->getBuiltinCallee())
15208       return CheckEvalInICE(E, Ctx);
15209     return ICEDiag(IK_NotICE, E->getBeginLoc());
15210   }
15211   case Expr::CXXRewrittenBinaryOperatorClass:
15212     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15213                     Ctx);
15214   case Expr::DeclRefExprClass: {
15215     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
15216     if (isa<EnumConstantDecl>(D))
15217       return NoDiag();
15218 
15219     // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
15220     // integer variables in constant expressions:
15221     //
15222     // C++ 7.1.5.1p2
15223     //   A variable of non-volatile const-qualified integral or enumeration
15224     //   type initialized by an ICE can be used in ICEs.
15225     //
15226     // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
15227     // that mode, use of reference variables should not be allowed.
15228     const VarDecl *VD = dyn_cast<VarDecl>(D);
15229     if (VD && VD->isUsableInConstantExpressions(Ctx) &&
15230         !VD->getType()->isReferenceType())
15231       return NoDiag();
15232 
15233     return ICEDiag(IK_NotICE, E->getBeginLoc());
15234   }
15235   case Expr::UnaryOperatorClass: {
15236     const UnaryOperator *Exp = cast<UnaryOperator>(E);
15237     switch (Exp->getOpcode()) {
15238     case UO_PostInc:
15239     case UO_PostDec:
15240     case UO_PreInc:
15241     case UO_PreDec:
15242     case UO_AddrOf:
15243     case UO_Deref:
15244     case UO_Coawait:
15245       // C99 6.6/3 allows increment and decrement within unevaluated
15246       // subexpressions of constant expressions, but they can never be ICEs
15247       // because an ICE cannot contain an lvalue operand.
15248       return ICEDiag(IK_NotICE, E->getBeginLoc());
15249     case UO_Extension:
15250     case UO_LNot:
15251     case UO_Plus:
15252     case UO_Minus:
15253     case UO_Not:
15254     case UO_Real:
15255     case UO_Imag:
15256       return CheckICE(Exp->getSubExpr(), Ctx);
15257     }
15258     llvm_unreachable("invalid unary operator class");
15259   }
15260   case Expr::OffsetOfExprClass: {
15261     // Note that per C99, offsetof must be an ICE. And AFAIK, using
15262     // EvaluateAsRValue matches the proposed gcc behavior for cases like
15263     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
15264     // compliance: we should warn earlier for offsetof expressions with
15265     // array subscripts that aren't ICEs, and if the array subscripts
15266     // are ICEs, the value of the offsetof must be an integer constant.
15267     return CheckEvalInICE(E, Ctx);
15268   }
15269   case Expr::UnaryExprOrTypeTraitExprClass: {
15270     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15271     if ((Exp->getKind() ==  UETT_SizeOf) &&
15272         Exp->getTypeOfArgument()->isVariableArrayType())
15273       return ICEDiag(IK_NotICE, E->getBeginLoc());
15274     return NoDiag();
15275   }
15276   case Expr::BinaryOperatorClass: {
15277     const BinaryOperator *Exp = cast<BinaryOperator>(E);
15278     switch (Exp->getOpcode()) {
15279     case BO_PtrMemD:
15280     case BO_PtrMemI:
15281     case BO_Assign:
15282     case BO_MulAssign:
15283     case BO_DivAssign:
15284     case BO_RemAssign:
15285     case BO_AddAssign:
15286     case BO_SubAssign:
15287     case BO_ShlAssign:
15288     case BO_ShrAssign:
15289     case BO_AndAssign:
15290     case BO_XorAssign:
15291     case BO_OrAssign:
15292       // C99 6.6/3 allows assignments within unevaluated subexpressions of
15293       // constant expressions, but they can never be ICEs because an ICE cannot
15294       // contain an lvalue operand.
15295       return ICEDiag(IK_NotICE, E->getBeginLoc());
15296 
15297     case BO_Mul:
15298     case BO_Div:
15299     case BO_Rem:
15300     case BO_Add:
15301     case BO_Sub:
15302     case BO_Shl:
15303     case BO_Shr:
15304     case BO_LT:
15305     case BO_GT:
15306     case BO_LE:
15307     case BO_GE:
15308     case BO_EQ:
15309     case BO_NE:
15310     case BO_And:
15311     case BO_Xor:
15312     case BO_Or:
15313     case BO_Comma:
15314     case BO_Cmp: {
15315       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15316       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15317       if (Exp->getOpcode() == BO_Div ||
15318           Exp->getOpcode() == BO_Rem) {
15319         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15320         // we don't evaluate one.
15321         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15322           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15323           if (REval == 0)
15324             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15325           if (REval.isSigned() && REval.isAllOnesValue()) {
15326             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15327             if (LEval.isMinSignedValue())
15328               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15329           }
15330         }
15331       }
15332       if (Exp->getOpcode() == BO_Comma) {
15333         if (Ctx.getLangOpts().C99) {
15334           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15335           // if it isn't evaluated.
15336           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15337             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15338         } else {
15339           // In both C89 and C++, commas in ICEs are illegal.
15340           return ICEDiag(IK_NotICE, E->getBeginLoc());
15341         }
15342       }
15343       return Worst(LHSResult, RHSResult);
15344     }
15345     case BO_LAnd:
15346     case BO_LOr: {
15347       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15348       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15349       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15350         // Rare case where the RHS has a comma "side-effect"; we need
15351         // to actually check the condition to see whether the side
15352         // with the comma is evaluated.
15353         if ((Exp->getOpcode() == BO_LAnd) !=
15354             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15355           return RHSResult;
15356         return NoDiag();
15357       }
15358 
15359       return Worst(LHSResult, RHSResult);
15360     }
15361     }
15362     llvm_unreachable("invalid binary operator kind");
15363   }
15364   case Expr::ImplicitCastExprClass:
15365   case Expr::CStyleCastExprClass:
15366   case Expr::CXXFunctionalCastExprClass:
15367   case Expr::CXXStaticCastExprClass:
15368   case Expr::CXXReinterpretCastExprClass:
15369   case Expr::CXXConstCastExprClass:
15370   case Expr::ObjCBridgedCastExprClass: {
15371     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15372     if (isa<ExplicitCastExpr>(E)) {
15373       if (const FloatingLiteral *FL
15374             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15375         unsigned DestWidth = Ctx.getIntWidth(E->getType());
15376         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15377         APSInt IgnoredVal(DestWidth, !DestSigned);
15378         bool Ignored;
15379         // If the value does not fit in the destination type, the behavior is
15380         // undefined, so we are not required to treat it as a constant
15381         // expression.
15382         if (FL->getValue().convertToInteger(IgnoredVal,
15383                                             llvm::APFloat::rmTowardZero,
15384                                             &Ignored) & APFloat::opInvalidOp)
15385           return ICEDiag(IK_NotICE, E->getBeginLoc());
15386         return NoDiag();
15387       }
15388     }
15389     switch (cast<CastExpr>(E)->getCastKind()) {
15390     case CK_LValueToRValue:
15391     case CK_AtomicToNonAtomic:
15392     case CK_NonAtomicToAtomic:
15393     case CK_NoOp:
15394     case CK_IntegralToBoolean:
15395     case CK_IntegralCast:
15396       return CheckICE(SubExpr, Ctx);
15397     default:
15398       return ICEDiag(IK_NotICE, E->getBeginLoc());
15399     }
15400   }
15401   case Expr::BinaryConditionalOperatorClass: {
15402     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
15403     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
15404     if (CommonResult.Kind == IK_NotICE) return CommonResult;
15405     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15406     if (FalseResult.Kind == IK_NotICE) return FalseResult;
15407     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15408     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15409         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15410     return FalseResult;
15411   }
15412   case Expr::ConditionalOperatorClass: {
15413     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15414     // If the condition (ignoring parens) is a __builtin_constant_p call,
15415     // then only the true side is actually considered in an integer constant
15416     // expression, and it is fully evaluated.  This is an important GNU
15417     // extension.  See GCC PR38377 for discussion.
15418     if (const CallExpr *CallCE
15419         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15420       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15421         return CheckEvalInICE(E, Ctx);
15422     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15423     if (CondResult.Kind == IK_NotICE)
15424       return CondResult;
15425 
15426     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15427     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15428 
15429     if (TrueResult.Kind == IK_NotICE)
15430       return TrueResult;
15431     if (FalseResult.Kind == IK_NotICE)
15432       return FalseResult;
15433     if (CondResult.Kind == IK_ICEIfUnevaluated)
15434       return CondResult;
15435     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15436       return NoDiag();
15437     // Rare case where the diagnostics depend on which side is evaluated
15438     // Note that if we get here, CondResult is 0, and at least one of
15439     // TrueResult and FalseResult is non-zero.
15440     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15441       return FalseResult;
15442     return TrueResult;
15443   }
15444   case Expr::CXXDefaultArgExprClass:
15445     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15446   case Expr::CXXDefaultInitExprClass:
15447     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15448   case Expr::ChooseExprClass: {
15449     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15450   }
15451   case Expr::BuiltinBitCastExprClass: {
15452     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15453       return ICEDiag(IK_NotICE, E->getBeginLoc());
15454     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15455   }
15456   }
15457 
15458   llvm_unreachable("Invalid StmtClass!");
15459 }
15460 
15461 /// Evaluate an expression as a C++11 integral constant expression.
15462 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15463                                                     const Expr *E,
15464                                                     llvm::APSInt *Value,
15465                                                     SourceLocation *Loc) {
15466   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15467     if (Loc) *Loc = E->getExprLoc();
15468     return false;
15469   }
15470 
15471   APValue Result;
15472   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15473     return false;
15474 
15475   if (!Result.isInt()) {
15476     if (Loc) *Loc = E->getExprLoc();
15477     return false;
15478   }
15479 
15480   if (Value) *Value = Result.getInt();
15481   return true;
15482 }
15483 
15484 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
15485                                  SourceLocation *Loc) const {
15486   assert(!isValueDependent() &&
15487          "Expression evaluator can't be called on a dependent expression.");
15488 
15489   if (Ctx.getLangOpts().CPlusPlus11)
15490     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
15491 
15492   ICEDiag D = CheckICE(this, Ctx);
15493   if (D.Kind != IK_ICE) {
15494     if (Loc) *Loc = D.Loc;
15495     return false;
15496   }
15497   return true;
15498 }
15499 
15500 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx,
15501                                                     SourceLocation *Loc,
15502                                                     bool isEvaluated) const {
15503   assert(!isValueDependent() &&
15504          "Expression evaluator can't be called on a dependent expression.");
15505 
15506   APSInt Value;
15507 
15508   if (Ctx.getLangOpts().CPlusPlus11) {
15509     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
15510       return Value;
15511     return None;
15512   }
15513 
15514   if (!isIntegerConstantExpr(Ctx, Loc))
15515     return None;
15516 
15517   // The only possible side-effects here are due to UB discovered in the
15518   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
15519   // required to treat the expression as an ICE, so we produce the folded
15520   // value.
15521   EvalResult ExprResult;
15522   Expr::EvalStatus Status;
15523   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
15524   Info.InConstantContext = true;
15525 
15526   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
15527     llvm_unreachable("ICE cannot be evaluated!");
15528 
15529   return ExprResult.Val.getInt();
15530 }
15531 
15532 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
15533   assert(!isValueDependent() &&
15534          "Expression evaluator can't be called on a dependent expression.");
15535 
15536   return CheckICE(this, Ctx).Kind == IK_ICE;
15537 }
15538 
15539 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
15540                                SourceLocation *Loc) const {
15541   assert(!isValueDependent() &&
15542          "Expression evaluator can't be called on a dependent expression.");
15543 
15544   // We support this checking in C++98 mode in order to diagnose compatibility
15545   // issues.
15546   assert(Ctx.getLangOpts().CPlusPlus);
15547 
15548   // Build evaluation settings.
15549   Expr::EvalStatus Status;
15550   SmallVector<PartialDiagnosticAt, 8> Diags;
15551   Status.Diag = &Diags;
15552   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15553 
15554   APValue Scratch;
15555   bool IsConstExpr =
15556       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
15557       // FIXME: We don't produce a diagnostic for this, but the callers that
15558       // call us on arbitrary full-expressions should generally not care.
15559       Info.discardCleanups() && !Status.HasSideEffects;
15560 
15561   if (!Diags.empty()) {
15562     IsConstExpr = false;
15563     if (Loc) *Loc = Diags[0].first;
15564   } else if (!IsConstExpr) {
15565     // FIXME: This shouldn't happen.
15566     if (Loc) *Loc = getExprLoc();
15567   }
15568 
15569   return IsConstExpr;
15570 }
15571 
15572 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
15573                                     const FunctionDecl *Callee,
15574                                     ArrayRef<const Expr*> Args,
15575                                     const Expr *This) const {
15576   assert(!isValueDependent() &&
15577          "Expression evaluator can't be called on a dependent expression.");
15578 
15579   Expr::EvalStatus Status;
15580   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
15581   Info.InConstantContext = true;
15582 
15583   LValue ThisVal;
15584   const LValue *ThisPtr = nullptr;
15585   if (This) {
15586 #ifndef NDEBUG
15587     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
15588     assert(MD && "Don't provide `this` for non-methods.");
15589     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
15590 #endif
15591     if (!This->isValueDependent() &&
15592         EvaluateObjectArgument(Info, This, ThisVal) &&
15593         !Info.EvalStatus.HasSideEffects)
15594       ThisPtr = &ThisVal;
15595 
15596     // Ignore any side-effects from a failed evaluation. This is safe because
15597     // they can't interfere with any other argument evaluation.
15598     Info.EvalStatus.HasSideEffects = false;
15599   }
15600 
15601   CallRef Call = Info.CurrentCall->createCall(Callee);
15602   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
15603        I != E; ++I) {
15604     unsigned Idx = I - Args.begin();
15605     if (Idx >= Callee->getNumParams())
15606       break;
15607     const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
15608     if ((*I)->isValueDependent() ||
15609         !EvaluateCallArg(PVD, *I, Call, Info) ||
15610         Info.EvalStatus.HasSideEffects) {
15611       // If evaluation fails, throw away the argument entirely.
15612       if (APValue *Slot = Info.getParamSlot(Call, PVD))
15613         *Slot = APValue();
15614     }
15615 
15616     // Ignore any side-effects from a failed evaluation. This is safe because
15617     // they can't interfere with any other argument evaluation.
15618     Info.EvalStatus.HasSideEffects = false;
15619   }
15620 
15621   // Parameter cleanups happen in the caller and are not part of this
15622   // evaluation.
15623   Info.discardCleanups();
15624   Info.EvalStatus.HasSideEffects = false;
15625 
15626   // Build fake call to Callee.
15627   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
15628   // FIXME: Missing ExprWithCleanups in enable_if conditions?
15629   FullExpressionRAII Scope(Info);
15630   return Evaluate(Value, Info, this) && Scope.destroy() &&
15631          !Info.EvalStatus.HasSideEffects;
15632 }
15633 
15634 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
15635                                    SmallVectorImpl<
15636                                      PartialDiagnosticAt> &Diags) {
15637   // FIXME: It would be useful to check constexpr function templates, but at the
15638   // moment the constant expression evaluator cannot cope with the non-rigorous
15639   // ASTs which we build for dependent expressions.
15640   if (FD->isDependentContext())
15641     return true;
15642 
15643   Expr::EvalStatus Status;
15644   Status.Diag = &Diags;
15645 
15646   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
15647   Info.InConstantContext = true;
15648   Info.CheckingPotentialConstantExpression = true;
15649 
15650   // The constexpr VM attempts to compile all methods to bytecode here.
15651   if (Info.EnableNewConstInterp) {
15652     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
15653     return Diags.empty();
15654   }
15655 
15656   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
15657   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
15658 
15659   // Fabricate an arbitrary expression on the stack and pretend that it
15660   // is a temporary being used as the 'this' pointer.
15661   LValue This;
15662   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
15663   This.set({&VIE, Info.CurrentCall->Index});
15664 
15665   ArrayRef<const Expr*> Args;
15666 
15667   APValue Scratch;
15668   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
15669     // Evaluate the call as a constant initializer, to allow the construction
15670     // of objects of non-literal types.
15671     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
15672     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
15673   } else {
15674     SourceLocation Loc = FD->getLocation();
15675     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
15676                        Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
15677   }
15678 
15679   return Diags.empty();
15680 }
15681 
15682 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
15683                                               const FunctionDecl *FD,
15684                                               SmallVectorImpl<
15685                                                 PartialDiagnosticAt> &Diags) {
15686   assert(!E->isValueDependent() &&
15687          "Expression evaluator can't be called on a dependent expression.");
15688 
15689   Expr::EvalStatus Status;
15690   Status.Diag = &Diags;
15691 
15692   EvalInfo Info(FD->getASTContext(), Status,
15693                 EvalInfo::EM_ConstantExpressionUnevaluated);
15694   Info.InConstantContext = true;
15695   Info.CheckingPotentialConstantExpression = true;
15696 
15697   // Fabricate a call stack frame to give the arguments a plausible cover story.
15698   CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
15699 
15700   APValue ResultScratch;
15701   Evaluate(ResultScratch, Info, E);
15702   return Diags.empty();
15703 }
15704 
15705 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
15706                                  unsigned Type) const {
15707   if (!getType()->isPointerType())
15708     return false;
15709 
15710   Expr::EvalStatus Status;
15711   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15712   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
15713 }
15714