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 <cstring>
36 #include <functional>
37 #include "Interp/Context.h"
38 #include "Interp/Frame.h"
39 #include "Interp/State.h"
40 #include "clang/AST/APValue.h"
41 #include "clang/AST/ASTContext.h"
42 #include "clang/AST/ASTDiagnostic.h"
43 #include "clang/AST/ASTLambda.h"
44 #include "clang/AST/CXXInheritance.h"
45 #include "clang/AST/CharUnits.h"
46 #include "clang/AST/CurrentSourceLocExprScope.h"
47 #include "clang/AST/Expr.h"
48 #include "clang/AST/OSLog.h"
49 #include "clang/AST/OptionalDiagnostic.h"
50 #include "clang/AST/RecordLayout.h"
51 #include "clang/AST/StmtVisitor.h"
52 #include "clang/AST/TypeLoc.h"
53 #include "clang/Basic/Builtins.h"
54 #include "clang/Basic/FixedPoint.h"
55 #include "clang/Basic/TargetInfo.h"
56 #include "llvm/ADT/Optional.h"
57 #include "llvm/ADT/SmallBitVector.h"
58 #include "llvm/Support/SaveAndRestore.h"
59 #include "llvm/Support/raw_ostream.h"
60 
61 #define DEBUG_TYPE "exprconstant"
62 
63 using namespace clang;
64 using llvm::APInt;
65 using llvm::APSInt;
66 using llvm::APFloat;
67 using llvm::Optional;
68 
69 static bool IsGlobalLValue(APValue::LValueBase B);
70 
71 namespace {
72   struct LValue;
73   class CallStackFrame;
74   class EvalInfo;
75 
76   using SourceLocExprScopeGuard =
77       CurrentSourceLocExprScope::SourceLocExprScopeGuard;
78 
79   static QualType getType(APValue::LValueBase B) {
80     if (!B) return QualType();
81     if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
82       // FIXME: It's unclear where we're supposed to take the type from, and
83       // this actually matters for arrays of unknown bound. Eg:
84       //
85       // extern int arr[]; void f() { extern int arr[3]; };
86       // constexpr int *p = &arr[1]; // valid?
87       //
88       // For now, we take the array bound from the most recent declaration.
89       for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
90            Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
91         QualType T = Redecl->getType();
92         if (!T->isIncompleteArrayType())
93           return T;
94       }
95       return D->getType();
96     }
97 
98     if (B.is<TypeInfoLValue>())
99       return B.getTypeInfoType();
100 
101     const Expr *Base = B.get<const Expr*>();
102 
103     // For a materialized temporary, the type of the temporary we materialized
104     // may not be the type of the expression.
105     if (const MaterializeTemporaryExpr *MTE =
106             dyn_cast<MaterializeTemporaryExpr>(Base)) {
107       SmallVector<const Expr *, 2> CommaLHSs;
108       SmallVector<SubobjectAdjustment, 2> Adjustments;
109       const Expr *Temp = MTE->GetTemporaryExpr();
110       const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
111                                                                Adjustments);
112       // Keep any cv-qualifiers from the reference if we generated a temporary
113       // for it directly. Otherwise use the type after adjustment.
114       if (!Adjustments.empty())
115         return Inner->getType();
116     }
117 
118     return Base->getType();
119   }
120 
121   /// Get an LValue path entry, which is known to not be an array index, as a
122   /// field declaration.
123   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
124     return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
125   }
126   /// Get an LValue path entry, which is known to not be an array index, as a
127   /// base class declaration.
128   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
129     return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
130   }
131   /// Determine whether this LValue path entry for a base class names a virtual
132   /// base class.
133   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
134     return E.getAsBaseOrMember().getInt();
135   }
136 
137   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
138   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
139     const FunctionDecl *Callee = CE->getDirectCallee();
140     return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
141   }
142 
143   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
144   /// This will look through a single cast.
145   ///
146   /// Returns null if we couldn't unwrap a function with alloc_size.
147   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
148     if (!E->getType()->isPointerType())
149       return nullptr;
150 
151     E = E->IgnoreParens();
152     // If we're doing a variable assignment from e.g. malloc(N), there will
153     // probably be a cast of some kind. In exotic cases, we might also see a
154     // top-level ExprWithCleanups. Ignore them either way.
155     if (const auto *FE = dyn_cast<FullExpr>(E))
156       E = FE->getSubExpr()->IgnoreParens();
157 
158     if (const auto *Cast = dyn_cast<CastExpr>(E))
159       E = Cast->getSubExpr()->IgnoreParens();
160 
161     if (const auto *CE = dyn_cast<CallExpr>(E))
162       return getAllocSizeAttr(CE) ? CE : nullptr;
163     return nullptr;
164   }
165 
166   /// Determines whether or not the given Base contains a call to a function
167   /// with the alloc_size attribute.
168   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
169     const auto *E = Base.dyn_cast<const Expr *>();
170     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
171   }
172 
173   /// The bound to claim that an array of unknown bound has.
174   /// The value in MostDerivedArraySize is undefined in this case. So, set it
175   /// to an arbitrary value that's likely to loudly break things if it's used.
176   static const uint64_t AssumedSizeForUnsizedArray =
177       std::numeric_limits<uint64_t>::max() / 2;
178 
179   /// Determines if an LValue with the given LValueBase will have an unsized
180   /// array in its designator.
181   /// Find the path length and type of the most-derived subobject in the given
182   /// path, and find the size of the containing array, if any.
183   static unsigned
184   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
185                            ArrayRef<APValue::LValuePathEntry> Path,
186                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
187                            bool &FirstEntryIsUnsizedArray) {
188     // This only accepts LValueBases from APValues, and APValues don't support
189     // arrays that lack size info.
190     assert(!isBaseAnAllocSizeCall(Base) &&
191            "Unsized arrays shouldn't appear here");
192     unsigned MostDerivedLength = 0;
193     Type = getType(Base);
194 
195     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
196       if (Type->isArrayType()) {
197         const ArrayType *AT = Ctx.getAsArrayType(Type);
198         Type = AT->getElementType();
199         MostDerivedLength = I + 1;
200         IsArray = true;
201 
202         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
203           ArraySize = CAT->getSize().getZExtValue();
204         } else {
205           assert(I == 0 && "unexpected unsized array designator");
206           FirstEntryIsUnsizedArray = true;
207           ArraySize = AssumedSizeForUnsizedArray;
208         }
209       } else if (Type->isAnyComplexType()) {
210         const ComplexType *CT = Type->castAs<ComplexType>();
211         Type = CT->getElementType();
212         ArraySize = 2;
213         MostDerivedLength = I + 1;
214         IsArray = true;
215       } else if (const FieldDecl *FD = getAsField(Path[I])) {
216         Type = FD->getType();
217         ArraySize = 0;
218         MostDerivedLength = I + 1;
219         IsArray = false;
220       } else {
221         // Path[I] describes a base class.
222         ArraySize = 0;
223         IsArray = false;
224       }
225     }
226     return MostDerivedLength;
227   }
228 
229   /// A path from a glvalue to a subobject of that glvalue.
230   struct SubobjectDesignator {
231     /// True if the subobject was named in a manner not supported by C++11. Such
232     /// lvalues can still be folded, but they are not core constant expressions
233     /// and we cannot perform lvalue-to-rvalue conversions on them.
234     unsigned Invalid : 1;
235 
236     /// Is this a pointer one past the end of an object?
237     unsigned IsOnePastTheEnd : 1;
238 
239     /// Indicator of whether the first entry is an unsized array.
240     unsigned FirstEntryIsAnUnsizedArray : 1;
241 
242     /// Indicator of whether the most-derived object is an array element.
243     unsigned MostDerivedIsArrayElement : 1;
244 
245     /// The length of the path to the most-derived object of which this is a
246     /// subobject.
247     unsigned MostDerivedPathLength : 28;
248 
249     /// The size of the array of which the most-derived object is an element.
250     /// This will always be 0 if the most-derived object is not an array
251     /// element. 0 is not an indicator of whether or not the most-derived object
252     /// is an array, however, because 0-length arrays are allowed.
253     ///
254     /// If the current array is an unsized array, the value of this is
255     /// undefined.
256     uint64_t MostDerivedArraySize;
257 
258     /// The type of the most derived object referred to by this address.
259     QualType MostDerivedType;
260 
261     typedef APValue::LValuePathEntry PathEntry;
262 
263     /// The entries on the path from the glvalue to the designated subobject.
264     SmallVector<PathEntry, 8> Entries;
265 
266     SubobjectDesignator() : Invalid(true) {}
267 
268     explicit SubobjectDesignator(QualType T)
269         : Invalid(false), IsOnePastTheEnd(false),
270           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
271           MostDerivedPathLength(0), MostDerivedArraySize(0),
272           MostDerivedType(T) {}
273 
274     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
275         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
276           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
277           MostDerivedPathLength(0), MostDerivedArraySize(0) {
278       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
279       if (!Invalid) {
280         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
281         ArrayRef<PathEntry> VEntries = V.getLValuePath();
282         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
283         if (V.getLValueBase()) {
284           bool IsArray = false;
285           bool FirstIsUnsizedArray = false;
286           MostDerivedPathLength = findMostDerivedSubobject(
287               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
288               MostDerivedType, IsArray, FirstIsUnsizedArray);
289           MostDerivedIsArrayElement = IsArray;
290           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
291         }
292       }
293     }
294 
295     void truncate(ASTContext &Ctx, APValue::LValueBase Base,
296                   unsigned NewLength) {
297       if (Invalid)
298         return;
299 
300       assert(Base && "cannot truncate path for null pointer");
301       assert(NewLength <= Entries.size() && "not a truncation");
302 
303       if (NewLength == Entries.size())
304         return;
305       Entries.resize(NewLength);
306 
307       bool IsArray = false;
308       bool FirstIsUnsizedArray = false;
309       MostDerivedPathLength = findMostDerivedSubobject(
310           Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
311           FirstIsUnsizedArray);
312       MostDerivedIsArrayElement = IsArray;
313       FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
314     }
315 
316     void setInvalid() {
317       Invalid = true;
318       Entries.clear();
319     }
320 
321     /// Determine whether the most derived subobject is an array without a
322     /// known bound.
323     bool isMostDerivedAnUnsizedArray() const {
324       assert(!Invalid && "Calling this makes no sense on invalid designators");
325       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
326     }
327 
328     /// Determine what the most derived array's size is. Results in an assertion
329     /// failure if the most derived array lacks a size.
330     uint64_t getMostDerivedArraySize() const {
331       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
332       return MostDerivedArraySize;
333     }
334 
335     /// Determine whether this is a one-past-the-end pointer.
336     bool isOnePastTheEnd() const {
337       assert(!Invalid);
338       if (IsOnePastTheEnd)
339         return true;
340       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
341           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
342               MostDerivedArraySize)
343         return true;
344       return false;
345     }
346 
347     /// Get the range of valid index adjustments in the form
348     ///   {maximum value that can be subtracted from this pointer,
349     ///    maximum value that can be added to this pointer}
350     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
351       if (Invalid || isMostDerivedAnUnsizedArray())
352         return {0, 0};
353 
354       // [expr.add]p4: For the purposes of these operators, a pointer to a
355       // nonarray object behaves the same as a pointer to the first element of
356       // an array of length one with the type of the object as its element type.
357       bool IsArray = MostDerivedPathLength == Entries.size() &&
358                      MostDerivedIsArrayElement;
359       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
360                                     : (uint64_t)IsOnePastTheEnd;
361       uint64_t ArraySize =
362           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
363       return {ArrayIndex, ArraySize - ArrayIndex};
364     }
365 
366     /// Check that this refers to a valid subobject.
367     bool isValidSubobject() const {
368       if (Invalid)
369         return false;
370       return !isOnePastTheEnd();
371     }
372     /// Check that this refers to a valid subobject, and if not, produce a
373     /// relevant diagnostic and set the designator as invalid.
374     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
375 
376     /// Get the type of the designated object.
377     QualType getType(ASTContext &Ctx) const {
378       assert(!Invalid && "invalid designator has no subobject type");
379       return MostDerivedPathLength == Entries.size()
380                  ? MostDerivedType
381                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
382     }
383 
384     /// Update this designator to refer to the first element within this array.
385     void addArrayUnchecked(const ConstantArrayType *CAT) {
386       Entries.push_back(PathEntry::ArrayIndex(0));
387 
388       // This is a most-derived object.
389       MostDerivedType = CAT->getElementType();
390       MostDerivedIsArrayElement = true;
391       MostDerivedArraySize = CAT->getSize().getZExtValue();
392       MostDerivedPathLength = Entries.size();
393     }
394     /// Update this designator to refer to the first element within the array of
395     /// elements of type T. This is an array of unknown size.
396     void addUnsizedArrayUnchecked(QualType ElemTy) {
397       Entries.push_back(PathEntry::ArrayIndex(0));
398 
399       MostDerivedType = ElemTy;
400       MostDerivedIsArrayElement = true;
401       // The value in MostDerivedArraySize is undefined in this case. So, set it
402       // to an arbitrary value that's likely to loudly break things if it's
403       // used.
404       MostDerivedArraySize = AssumedSizeForUnsizedArray;
405       MostDerivedPathLength = Entries.size();
406     }
407     /// Update this designator to refer to the given base or member of this
408     /// object.
409     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
410       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
411 
412       // If this isn't a base class, it's a new most-derived object.
413       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
414         MostDerivedType = FD->getType();
415         MostDerivedIsArrayElement = false;
416         MostDerivedArraySize = 0;
417         MostDerivedPathLength = Entries.size();
418       }
419     }
420     /// Update this designator to refer to the given complex component.
421     void addComplexUnchecked(QualType EltTy, bool Imag) {
422       Entries.push_back(PathEntry::ArrayIndex(Imag));
423 
424       // This is technically a most-derived object, though in practice this
425       // is unlikely to matter.
426       MostDerivedType = EltTy;
427       MostDerivedIsArrayElement = true;
428       MostDerivedArraySize = 2;
429       MostDerivedPathLength = Entries.size();
430     }
431     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
432     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
433                                    const APSInt &N);
434     /// Add N to the address of this subobject.
435     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
436       if (Invalid || !N) return;
437       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
438       if (isMostDerivedAnUnsizedArray()) {
439         diagnoseUnsizedArrayPointerArithmetic(Info, E);
440         // Can't verify -- trust that the user is doing the right thing (or if
441         // not, trust that the caller will catch the bad behavior).
442         // FIXME: Should we reject if this overflows, at least?
443         Entries.back() = PathEntry::ArrayIndex(
444             Entries.back().getAsArrayIndex() + TruncatedN);
445         return;
446       }
447 
448       // [expr.add]p4: For the purposes of these operators, a pointer to a
449       // nonarray object behaves the same as a pointer to the first element of
450       // an array of length one with the type of the object as its element type.
451       bool IsArray = MostDerivedPathLength == Entries.size() &&
452                      MostDerivedIsArrayElement;
453       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
454                                     : (uint64_t)IsOnePastTheEnd;
455       uint64_t ArraySize =
456           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
457 
458       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
459         // Calculate the actual index in a wide enough type, so we can include
460         // it in the note.
461         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
462         (llvm::APInt&)N += ArrayIndex;
463         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
464         diagnosePointerArithmetic(Info, E, N);
465         setInvalid();
466         return;
467       }
468 
469       ArrayIndex += TruncatedN;
470       assert(ArrayIndex <= ArraySize &&
471              "bounds check succeeded for out-of-bounds index");
472 
473       if (IsArray)
474         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
475       else
476         IsOnePastTheEnd = (ArrayIndex != 0);
477     }
478   };
479 
480   /// A stack frame in the constexpr call stack.
481   class CallStackFrame : public interp::Frame {
482   public:
483     EvalInfo &Info;
484 
485     /// Parent - The caller of this stack frame.
486     CallStackFrame *Caller;
487 
488     /// Callee - The function which was called.
489     const FunctionDecl *Callee;
490 
491     /// This - The binding for the this pointer in this call, if any.
492     const LValue *This;
493 
494     /// Arguments - Parameter bindings for this function call, indexed by
495     /// parameters' function scope indices.
496     APValue *Arguments;
497 
498     /// Source location information about the default argument or default
499     /// initializer expression we're evaluating, if any.
500     CurrentSourceLocExprScope CurSourceLocExprScope;
501 
502     // Note that we intentionally use std::map here so that references to
503     // values are stable.
504     typedef std::pair<const void *, unsigned> MapKeyTy;
505     typedef std::map<MapKeyTy, APValue> MapTy;
506     /// Temporaries - Temporary lvalues materialized within this stack frame.
507     MapTy Temporaries;
508 
509     /// CallLoc - The location of the call expression for this call.
510     SourceLocation CallLoc;
511 
512     /// Index - The call index of this call.
513     unsigned Index;
514 
515     /// The stack of integers for tracking version numbers for temporaries.
516     SmallVector<unsigned, 2> TempVersionStack = {1};
517     unsigned CurTempVersion = TempVersionStack.back();
518 
519     unsigned getTempVersion() const { return TempVersionStack.back(); }
520 
521     void pushTempVersion() {
522       TempVersionStack.push_back(++CurTempVersion);
523     }
524 
525     void popTempVersion() {
526       TempVersionStack.pop_back();
527     }
528 
529     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
530     // on the overall stack usage of deeply-recursing constexpr evaluations.
531     // (We should cache this map rather than recomputing it repeatedly.)
532     // But let's try this and see how it goes; we can look into caching the map
533     // as a later change.
534 
535     /// LambdaCaptureFields - Mapping from captured variables/this to
536     /// corresponding data members in the closure class.
537     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
538     FieldDecl *LambdaThisCaptureField;
539 
540     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
541                    const FunctionDecl *Callee, const LValue *This,
542                    APValue *Arguments);
543     ~CallStackFrame();
544 
545     // Return the temporary for Key whose version number is Version.
546     APValue *getTemporary(const void *Key, unsigned Version) {
547       MapKeyTy KV(Key, Version);
548       auto LB = Temporaries.lower_bound(KV);
549       if (LB != Temporaries.end() && LB->first == KV)
550         return &LB->second;
551       // Pair (Key,Version) wasn't found in the map. Check that no elements
552       // in the map have 'Key' as their key.
553       assert((LB == Temporaries.end() || LB->first.first != Key) &&
554              (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
555              "Element with key 'Key' found in map");
556       return nullptr;
557     }
558 
559     // Return the current temporary for Key in the map.
560     APValue *getCurrentTemporary(const void *Key) {
561       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
562       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
563         return &std::prev(UB)->second;
564       return nullptr;
565     }
566 
567     // Return the version number of the current temporary for Key.
568     unsigned getCurrentTemporaryVersion(const void *Key) const {
569       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
570       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
571         return std::prev(UB)->first.second;
572       return 0;
573     }
574 
575     APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
576 
577     void describe(llvm::raw_ostream &OS) override;
578 
579     Frame *getCaller() const override { return Caller; }
580     SourceLocation getCallLocation() const override { return CallLoc; }
581     const FunctionDecl *getCallee() const override { return Callee; }
582   };
583 
584   /// Temporarily override 'this'.
585   class ThisOverrideRAII {
586   public:
587     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
588         : Frame(Frame), OldThis(Frame.This) {
589       if (Enable)
590         Frame.This = NewThis;
591     }
592     ~ThisOverrideRAII() {
593       Frame.This = OldThis;
594     }
595   private:
596     CallStackFrame &Frame;
597     const LValue *OldThis;
598   };
599 
600   /// A cleanup, and a flag indicating whether it is lifetime-extended.
601   class Cleanup {
602     llvm::PointerIntPair<APValue*, 1, bool> Value;
603 
604   public:
605     Cleanup(APValue *Val, bool IsLifetimeExtended)
606         : Value(Val, IsLifetimeExtended) {}
607 
608     bool isLifetimeExtended() const { return Value.getInt(); }
609     void endLifetime() {
610       *Value.getPointer() = APValue();
611     }
612   };
613 
614   /// A reference to an object whose construction we are currently evaluating.
615   struct ObjectUnderConstruction {
616     APValue::LValueBase Base;
617     ArrayRef<APValue::LValuePathEntry> Path;
618     friend bool operator==(const ObjectUnderConstruction &LHS,
619                            const ObjectUnderConstruction &RHS) {
620       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
621     }
622     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
623       return llvm::hash_combine(Obj.Base, Obj.Path);
624     }
625   };
626   enum class ConstructionPhase { None, Bases, AfterBases };
627 }
628 
629 namespace llvm {
630 template<> struct DenseMapInfo<ObjectUnderConstruction> {
631   using Base = DenseMapInfo<APValue::LValueBase>;
632   static ObjectUnderConstruction getEmptyKey() {
633     return {Base::getEmptyKey(), {}}; }
634   static ObjectUnderConstruction getTombstoneKey() {
635     return {Base::getTombstoneKey(), {}};
636   }
637   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
638     return hash_value(Object);
639   }
640   static bool isEqual(const ObjectUnderConstruction &LHS,
641                       const ObjectUnderConstruction &RHS) {
642     return LHS == RHS;
643   }
644 };
645 }
646 
647 namespace {
648   /// EvalInfo - This is a private struct used by the evaluator to capture
649   /// information about a subexpression as it is folded.  It retains information
650   /// about the AST context, but also maintains information about the folded
651   /// expression.
652   ///
653   /// If an expression could be evaluated, it is still possible it is not a C
654   /// "integer constant expression" or constant expression.  If not, this struct
655   /// captures information about how and why not.
656   ///
657   /// One bit of information passed *into* the request for constant folding
658   /// indicates whether the subexpression is "evaluated" or not according to C
659   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
660   /// evaluate the expression regardless of what the RHS is, but C only allows
661   /// certain things in certain situations.
662   class EvalInfo : public interp::State {
663   public:
664     ASTContext &Ctx;
665 
666     /// EvalStatus - Contains information about the evaluation.
667     Expr::EvalStatus &EvalStatus;
668 
669     /// CurrentCall - The top of the constexpr call stack.
670     CallStackFrame *CurrentCall;
671 
672     /// CallStackDepth - The number of calls in the call stack right now.
673     unsigned CallStackDepth;
674 
675     /// NextCallIndex - The next call index to assign.
676     unsigned NextCallIndex;
677 
678     /// StepsLeft - The remaining number of evaluation steps we're permitted
679     /// to perform. This is essentially a limit for the number of statements
680     /// we will evaluate.
681     unsigned StepsLeft;
682 
683     /// Force the use of the experimental new constant interpreter, bailing out
684     /// with an error if a feature is not supported.
685     bool ForceNewConstInterp;
686 
687     /// Enable the experimental new constant interpreter.
688     bool EnableNewConstInterp;
689 
690     /// BottomFrame - The frame in which evaluation started. This must be
691     /// initialized after CurrentCall and CallStackDepth.
692     CallStackFrame BottomFrame;
693 
694     /// A stack of values whose lifetimes end at the end of some surrounding
695     /// evaluation frame.
696     llvm::SmallVector<Cleanup, 16> CleanupStack;
697 
698     /// EvaluatingDecl - This is the declaration whose initializer is being
699     /// evaluated, if any.
700     APValue::LValueBase EvaluatingDecl;
701 
702     /// EvaluatingDeclValue - This is the value being constructed for the
703     /// declaration whose initializer is being evaluated, if any.
704     APValue *EvaluatingDeclValue;
705 
706     /// Set of objects that are currently being constructed.
707     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
708         ObjectsUnderConstruction;
709 
710     struct EvaluatingConstructorRAII {
711       EvalInfo &EI;
712       ObjectUnderConstruction Object;
713       bool DidInsert;
714       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
715                                 bool HasBases)
716           : EI(EI), Object(Object) {
717         DidInsert =
718             EI.ObjectsUnderConstruction
719                 .insert({Object, HasBases ? ConstructionPhase::Bases
720                                           : ConstructionPhase::AfterBases})
721                 .second;
722       }
723       void finishedConstructingBases() {
724         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
725       }
726       ~EvaluatingConstructorRAII() {
727         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
728       }
729     };
730 
731     ConstructionPhase
732     isEvaluatingConstructor(APValue::LValueBase Base,
733                             ArrayRef<APValue::LValuePathEntry> Path) {
734       return ObjectsUnderConstruction.lookup({Base, Path});
735     }
736 
737     /// If we're currently speculatively evaluating, the outermost call stack
738     /// depth at which we can mutate state, otherwise 0.
739     unsigned SpeculativeEvaluationDepth = 0;
740 
741     /// The current array initialization index, if we're performing array
742     /// initialization.
743     uint64_t ArrayInitIndex = -1;
744 
745     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
746     /// notes attached to it will also be stored, otherwise they will not be.
747     bool HasActiveDiagnostic;
748 
749     /// Have we emitted a diagnostic explaining why we couldn't constant
750     /// fold (not just why it's not strictly a constant expression)?
751     bool HasFoldFailureDiagnostic;
752 
753     /// Whether or not we're in a context where the front end requires a
754     /// constant value.
755     bool InConstantContext;
756 
757     /// Whether we're checking that an expression is a potential constant
758     /// expression. If so, do not fail on constructs that could become constant
759     /// later on (such as a use of an undefined global).
760     bool CheckingPotentialConstantExpression = false;
761 
762     /// Whether we're checking for an expression that has undefined behavior.
763     /// If so, we will produce warnings if we encounter an operation that is
764     /// always undefined.
765     bool CheckingForUndefinedBehavior = false;
766 
767     enum EvaluationMode {
768       /// Evaluate as a constant expression. Stop if we find that the expression
769       /// is not a constant expression.
770       EM_ConstantExpression,
771 
772       /// Evaluate as a constant expression. Stop if we find that the expression
773       /// is not a constant expression. Some expressions can be retried in the
774       /// optimizer if we don't constant fold them here, but in an unevaluated
775       /// context we try to fold them immediately since the optimizer never
776       /// gets a chance to look at it.
777       EM_ConstantExpressionUnevaluated,
778 
779       /// Fold the expression to a constant. Stop if we hit a side-effect that
780       /// we can't model.
781       EM_ConstantFold,
782 
783       /// Evaluate in any way we know how. Don't worry about side-effects that
784       /// can't be modeled.
785       EM_IgnoreSideEffects,
786     } EvalMode;
787 
788     /// Are we checking whether the expression is a potential constant
789     /// expression?
790     bool checkingPotentialConstantExpression() const override  {
791       return CheckingPotentialConstantExpression;
792     }
793 
794     /// Are we checking an expression for overflow?
795     // FIXME: We should check for any kind of undefined or suspicious behavior
796     // in such constructs, not just overflow.
797     bool checkingForUndefinedBehavior() const override {
798       return CheckingForUndefinedBehavior;
799     }
800 
801     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
802         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
803           CallStackDepth(0), NextCallIndex(1),
804           StepsLeft(getLangOpts().ConstexprStepLimit),
805           ForceNewConstInterp(getLangOpts().ForceNewConstInterp),
806           EnableNewConstInterp(ForceNewConstInterp ||
807                                getLangOpts().EnableNewConstInterp),
808           BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
809           EvaluatingDecl((const ValueDecl *)nullptr),
810           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
811           HasFoldFailureDiagnostic(false), InConstantContext(false),
812           EvalMode(Mode) {}
813 
814     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
815       EvaluatingDecl = Base;
816       EvaluatingDeclValue = &Value;
817     }
818 
819     bool CheckCallLimit(SourceLocation Loc) {
820       // Don't perform any constexpr calls (other than the call we're checking)
821       // when checking a potential constant expression.
822       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
823         return false;
824       if (NextCallIndex == 0) {
825         // NextCallIndex has wrapped around.
826         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
827         return false;
828       }
829       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
830         return true;
831       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
832         << getLangOpts().ConstexprCallDepth;
833       return false;
834     }
835 
836     std::pair<CallStackFrame *, unsigned>
837     getCallFrameAndDepth(unsigned CallIndex) {
838       assert(CallIndex && "no call index in getCallFrameAndDepth");
839       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
840       // be null in this loop.
841       unsigned Depth = CallStackDepth;
842       CallStackFrame *Frame = CurrentCall;
843       while (Frame->Index > CallIndex) {
844         Frame = Frame->Caller;
845         --Depth;
846       }
847       if (Frame->Index == CallIndex)
848         return {Frame, Depth};
849       return {nullptr, 0};
850     }
851 
852     bool nextStep(const Stmt *S) {
853       if (!StepsLeft) {
854         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
855         return false;
856       }
857       --StepsLeft;
858       return true;
859     }
860 
861   private:
862     interp::Frame *getCurrentFrame() override { return CurrentCall; }
863     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
864 
865     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
866     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
867 
868     void setFoldFailureDiagnostic(bool Flag) override {
869       HasFoldFailureDiagnostic = Flag;
870     }
871 
872     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
873 
874     ASTContext &getCtx() const override { return Ctx; }
875 
876     // If we have a prior diagnostic, it will be noting that the expression
877     // isn't a constant expression. This diagnostic is more important,
878     // unless we require this evaluation to produce a constant expression.
879     //
880     // FIXME: We might want to show both diagnostics to the user in
881     // EM_ConstantFold mode.
882     bool hasPriorDiagnostic() override {
883       if (!EvalStatus.Diag->empty()) {
884         switch (EvalMode) {
885         case EM_ConstantFold:
886         case EM_IgnoreSideEffects:
887           if (!HasFoldFailureDiagnostic)
888             break;
889           // We've already failed to fold something. Keep that diagnostic.
890           LLVM_FALLTHROUGH;
891         case EM_ConstantExpression:
892         case EM_ConstantExpressionUnevaluated:
893           setActiveDiagnostic(false);
894           return true;
895         }
896       }
897       return false;
898     }
899 
900     unsigned getCallStackDepth() override { return CallStackDepth; }
901 
902   public:
903     /// Should we continue evaluation after encountering a side-effect that we
904     /// couldn't model?
905     bool keepEvaluatingAfterSideEffect() {
906       switch (EvalMode) {
907       case EM_IgnoreSideEffects:
908         return true;
909 
910       case EM_ConstantExpression:
911       case EM_ConstantExpressionUnevaluated:
912       case EM_ConstantFold:
913         // By default, assume any side effect might be valid in some other
914         // evaluation of this expression from a different context.
915         return checkingPotentialConstantExpression() ||
916                checkingForUndefinedBehavior();
917       }
918       llvm_unreachable("Missed EvalMode case");
919     }
920 
921     /// Note that we have had a side-effect, and determine whether we should
922     /// keep evaluating.
923     bool noteSideEffect() {
924       EvalStatus.HasSideEffects = true;
925       return keepEvaluatingAfterSideEffect();
926     }
927 
928     /// Should we continue evaluation after encountering undefined behavior?
929     bool keepEvaluatingAfterUndefinedBehavior() {
930       switch (EvalMode) {
931       case EM_IgnoreSideEffects:
932       case EM_ConstantFold:
933         return true;
934 
935       case EM_ConstantExpression:
936       case EM_ConstantExpressionUnevaluated:
937         return checkingForUndefinedBehavior();
938       }
939       llvm_unreachable("Missed EvalMode case");
940     }
941 
942     /// Note that we hit something that was technically undefined behavior, but
943     /// that we can evaluate past it (such as signed overflow or floating-point
944     /// division by zero.)
945     bool noteUndefinedBehavior() override {
946       EvalStatus.HasUndefinedBehavior = true;
947       return keepEvaluatingAfterUndefinedBehavior();
948     }
949 
950     /// Should we continue evaluation as much as possible after encountering a
951     /// construct which can't be reduced to a value?
952     bool keepEvaluatingAfterFailure() const override {
953       if (!StepsLeft)
954         return false;
955 
956       switch (EvalMode) {
957       case EM_ConstantExpression:
958       case EM_ConstantExpressionUnevaluated:
959       case EM_ConstantFold:
960       case EM_IgnoreSideEffects:
961         return checkingPotentialConstantExpression() ||
962                checkingForUndefinedBehavior();
963       }
964       llvm_unreachable("Missed EvalMode case");
965     }
966 
967     /// Notes that we failed to evaluate an expression that other expressions
968     /// directly depend on, and determine if we should keep evaluating. This
969     /// should only be called if we actually intend to keep evaluating.
970     ///
971     /// Call noteSideEffect() instead if we may be able to ignore the value that
972     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
973     ///
974     /// (Foo(), 1)      // use noteSideEffect
975     /// (Foo() || true) // use noteSideEffect
976     /// Foo() + 1       // use noteFailure
977     LLVM_NODISCARD bool noteFailure() {
978       // Failure when evaluating some expression often means there is some
979       // subexpression whose evaluation was skipped. Therefore, (because we
980       // don't track whether we skipped an expression when unwinding after an
981       // evaluation failure) every evaluation failure that bubbles up from a
982       // subexpression implies that a side-effect has potentially happened. We
983       // skip setting the HasSideEffects flag to true until we decide to
984       // continue evaluating after that point, which happens here.
985       bool KeepGoing = keepEvaluatingAfterFailure();
986       EvalStatus.HasSideEffects |= KeepGoing;
987       return KeepGoing;
988     }
989 
990     class ArrayInitLoopIndex {
991       EvalInfo &Info;
992       uint64_t OuterIndex;
993 
994     public:
995       ArrayInitLoopIndex(EvalInfo &Info)
996           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
997         Info.ArrayInitIndex = 0;
998       }
999       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1000 
1001       operator uint64_t&() { return Info.ArrayInitIndex; }
1002     };
1003   };
1004 
1005   /// Object used to treat all foldable expressions as constant expressions.
1006   struct FoldConstant {
1007     EvalInfo &Info;
1008     bool Enabled;
1009     bool HadNoPriorDiags;
1010     EvalInfo::EvaluationMode OldMode;
1011 
1012     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1013       : Info(Info),
1014         Enabled(Enabled),
1015         HadNoPriorDiags(Info.EvalStatus.Diag &&
1016                         Info.EvalStatus.Diag->empty() &&
1017                         !Info.EvalStatus.HasSideEffects),
1018         OldMode(Info.EvalMode) {
1019       if (Enabled)
1020         Info.EvalMode = EvalInfo::EM_ConstantFold;
1021     }
1022     void keepDiagnostics() { Enabled = false; }
1023     ~FoldConstant() {
1024       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1025           !Info.EvalStatus.HasSideEffects)
1026         Info.EvalStatus.Diag->clear();
1027       Info.EvalMode = OldMode;
1028     }
1029   };
1030 
1031   /// RAII object used to set the current evaluation mode to ignore
1032   /// side-effects.
1033   struct IgnoreSideEffectsRAII {
1034     EvalInfo &Info;
1035     EvalInfo::EvaluationMode OldMode;
1036     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1037         : Info(Info), OldMode(Info.EvalMode) {
1038       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1039     }
1040 
1041     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1042   };
1043 
1044   /// RAII object used to optionally suppress diagnostics and side-effects from
1045   /// a speculative evaluation.
1046   class SpeculativeEvaluationRAII {
1047     EvalInfo *Info = nullptr;
1048     Expr::EvalStatus OldStatus;
1049     unsigned OldSpeculativeEvaluationDepth;
1050 
1051     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1052       Info = Other.Info;
1053       OldStatus = Other.OldStatus;
1054       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1055       Other.Info = nullptr;
1056     }
1057 
1058     void maybeRestoreState() {
1059       if (!Info)
1060         return;
1061 
1062       Info->EvalStatus = OldStatus;
1063       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1064     }
1065 
1066   public:
1067     SpeculativeEvaluationRAII() = default;
1068 
1069     SpeculativeEvaluationRAII(
1070         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1071         : Info(&Info), OldStatus(Info.EvalStatus),
1072           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1073       Info.EvalStatus.Diag = NewDiag;
1074       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1075     }
1076 
1077     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1078     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1079       moveFromAndCancel(std::move(Other));
1080     }
1081 
1082     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1083       maybeRestoreState();
1084       moveFromAndCancel(std::move(Other));
1085       return *this;
1086     }
1087 
1088     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1089   };
1090 
1091   /// RAII object wrapping a full-expression or block scope, and handling
1092   /// the ending of the lifetime of temporaries created within it.
1093   template<bool IsFullExpression>
1094   class ScopeRAII {
1095     EvalInfo &Info;
1096     unsigned OldStackSize;
1097   public:
1098     ScopeRAII(EvalInfo &Info)
1099         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1100       // Push a new temporary version. This is needed to distinguish between
1101       // temporaries created in different iterations of a loop.
1102       Info.CurrentCall->pushTempVersion();
1103     }
1104     ~ScopeRAII() {
1105       // Body moved to a static method to encourage the compiler to inline away
1106       // instances of this class.
1107       cleanup(Info, OldStackSize);
1108       Info.CurrentCall->popTempVersion();
1109     }
1110   private:
1111     static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1112       unsigned NewEnd = OldStackSize;
1113       for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1114            I != N; ++I) {
1115         if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1116           // Full-expression cleanup of a lifetime-extended temporary: nothing
1117           // to do, just move this cleanup to the right place in the stack.
1118           std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1119           ++NewEnd;
1120         } else {
1121           // End the lifetime of the object.
1122           Info.CleanupStack[I].endLifetime();
1123         }
1124       }
1125       Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1126                               Info.CleanupStack.end());
1127     }
1128   };
1129   typedef ScopeRAII<false> BlockScopeRAII;
1130   typedef ScopeRAII<true> FullExpressionRAII;
1131 }
1132 
1133 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1134                                          CheckSubobjectKind CSK) {
1135   if (Invalid)
1136     return false;
1137   if (isOnePastTheEnd()) {
1138     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1139       << CSK;
1140     setInvalid();
1141     return false;
1142   }
1143   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1144   // must actually be at least one array element; even a VLA cannot have a
1145   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1146   return true;
1147 }
1148 
1149 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1150                                                                 const Expr *E) {
1151   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1152   // Do not set the designator as invalid: we can represent this situation,
1153   // and correct handling of __builtin_object_size requires us to do so.
1154 }
1155 
1156 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1157                                                     const Expr *E,
1158                                                     const APSInt &N) {
1159   // If we're complaining, we must be able to statically determine the size of
1160   // the most derived array.
1161   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1162     Info.CCEDiag(E, diag::note_constexpr_array_index)
1163       << N << /*array*/ 0
1164       << static_cast<unsigned>(getMostDerivedArraySize());
1165   else
1166     Info.CCEDiag(E, diag::note_constexpr_array_index)
1167       << N << /*non-array*/ 1;
1168   setInvalid();
1169 }
1170 
1171 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1172                                const FunctionDecl *Callee, const LValue *This,
1173                                APValue *Arguments)
1174     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1175       Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1176   Info.CurrentCall = this;
1177   ++Info.CallStackDepth;
1178 }
1179 
1180 CallStackFrame::~CallStackFrame() {
1181   assert(Info.CurrentCall == this && "calls retired out of order");
1182   --Info.CallStackDepth;
1183   Info.CurrentCall = Caller;
1184 }
1185 
1186 APValue &CallStackFrame::createTemporary(const void *Key,
1187                                          bool IsLifetimeExtended) {
1188   unsigned Version = Info.CurrentCall->getTempVersion();
1189   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1190   assert(Result.isAbsent() && "temporary created multiple times");
1191   Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1192   return Result;
1193 }
1194 
1195 static bool isRead(AccessKinds AK) {
1196   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1197 }
1198 
1199 static bool isModification(AccessKinds AK) {
1200   switch (AK) {
1201   case AK_Read:
1202   case AK_ReadObjectRepresentation:
1203   case AK_MemberCall:
1204   case AK_DynamicCast:
1205   case AK_TypeId:
1206     return false;
1207   case AK_Assign:
1208   case AK_Increment:
1209   case AK_Decrement:
1210     return true;
1211   }
1212   llvm_unreachable("unknown access kind");
1213 }
1214 
1215 /// Is this an access per the C++ definition?
1216 static bool isFormalAccess(AccessKinds AK) {
1217   return isRead(AK) || isModification(AK);
1218 }
1219 
1220 namespace {
1221   struct ComplexValue {
1222   private:
1223     bool IsInt;
1224 
1225   public:
1226     APSInt IntReal, IntImag;
1227     APFloat FloatReal, FloatImag;
1228 
1229     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1230 
1231     void makeComplexFloat() { IsInt = false; }
1232     bool isComplexFloat() const { return !IsInt; }
1233     APFloat &getComplexFloatReal() { return FloatReal; }
1234     APFloat &getComplexFloatImag() { return FloatImag; }
1235 
1236     void makeComplexInt() { IsInt = true; }
1237     bool isComplexInt() const { return IsInt; }
1238     APSInt &getComplexIntReal() { return IntReal; }
1239     APSInt &getComplexIntImag() { return IntImag; }
1240 
1241     void moveInto(APValue &v) const {
1242       if (isComplexFloat())
1243         v = APValue(FloatReal, FloatImag);
1244       else
1245         v = APValue(IntReal, IntImag);
1246     }
1247     void setFrom(const APValue &v) {
1248       assert(v.isComplexFloat() || v.isComplexInt());
1249       if (v.isComplexFloat()) {
1250         makeComplexFloat();
1251         FloatReal = v.getComplexFloatReal();
1252         FloatImag = v.getComplexFloatImag();
1253       } else {
1254         makeComplexInt();
1255         IntReal = v.getComplexIntReal();
1256         IntImag = v.getComplexIntImag();
1257       }
1258     }
1259   };
1260 
1261   struct LValue {
1262     APValue::LValueBase Base;
1263     CharUnits Offset;
1264     SubobjectDesignator Designator;
1265     bool IsNullPtr : 1;
1266     bool InvalidBase : 1;
1267 
1268     const APValue::LValueBase getLValueBase() const { return Base; }
1269     CharUnits &getLValueOffset() { return Offset; }
1270     const CharUnits &getLValueOffset() const { return Offset; }
1271     SubobjectDesignator &getLValueDesignator() { return Designator; }
1272     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1273     bool isNullPointer() const { return IsNullPtr;}
1274 
1275     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1276     unsigned getLValueVersion() const { return Base.getVersion(); }
1277 
1278     void moveInto(APValue &V) const {
1279       if (Designator.Invalid)
1280         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1281       else {
1282         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1283         V = APValue(Base, Offset, Designator.Entries,
1284                     Designator.IsOnePastTheEnd, IsNullPtr);
1285       }
1286     }
1287     void setFrom(ASTContext &Ctx, const APValue &V) {
1288       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1289       Base = V.getLValueBase();
1290       Offset = V.getLValueOffset();
1291       InvalidBase = false;
1292       Designator = SubobjectDesignator(Ctx, V);
1293       IsNullPtr = V.isNullPointer();
1294     }
1295 
1296     void set(APValue::LValueBase B, bool BInvalid = false) {
1297 #ifndef NDEBUG
1298       // We only allow a few types of invalid bases. Enforce that here.
1299       if (BInvalid) {
1300         const auto *E = B.get<const Expr *>();
1301         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1302                "Unexpected type of invalid base");
1303       }
1304 #endif
1305 
1306       Base = B;
1307       Offset = CharUnits::fromQuantity(0);
1308       InvalidBase = BInvalid;
1309       Designator = SubobjectDesignator(getType(B));
1310       IsNullPtr = false;
1311     }
1312 
1313     void setNull(QualType PointerTy, uint64_t TargetVal) {
1314       Base = (Expr *)nullptr;
1315       Offset = CharUnits::fromQuantity(TargetVal);
1316       InvalidBase = false;
1317       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1318       IsNullPtr = true;
1319     }
1320 
1321     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1322       set(B, true);
1323     }
1324 
1325   private:
1326     // Check that this LValue is not based on a null pointer. If it is, produce
1327     // a diagnostic and mark the designator as invalid.
1328     template <typename GenDiagType>
1329     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1330       if (Designator.Invalid)
1331         return false;
1332       if (IsNullPtr) {
1333         GenDiag();
1334         Designator.setInvalid();
1335         return false;
1336       }
1337       return true;
1338     }
1339 
1340   public:
1341     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1342                           CheckSubobjectKind CSK) {
1343       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1344         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1345       });
1346     }
1347 
1348     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1349                                        AccessKinds AK) {
1350       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1351         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1352       });
1353     }
1354 
1355     // Check this LValue refers to an object. If not, set the designator to be
1356     // invalid and emit a diagnostic.
1357     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1358       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1359              Designator.checkSubobject(Info, E, CSK);
1360     }
1361 
1362     void addDecl(EvalInfo &Info, const Expr *E,
1363                  const Decl *D, bool Virtual = false) {
1364       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1365         Designator.addDeclUnchecked(D, Virtual);
1366     }
1367     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1368       if (!Designator.Entries.empty()) {
1369         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1370         Designator.setInvalid();
1371         return;
1372       }
1373       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1374         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1375         Designator.FirstEntryIsAnUnsizedArray = true;
1376         Designator.addUnsizedArrayUnchecked(ElemTy);
1377       }
1378     }
1379     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1380       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1381         Designator.addArrayUnchecked(CAT);
1382     }
1383     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1384       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1385         Designator.addComplexUnchecked(EltTy, Imag);
1386     }
1387     void clearIsNullPointer() {
1388       IsNullPtr = false;
1389     }
1390     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1391                               const APSInt &Index, CharUnits ElementSize) {
1392       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1393       // but we're not required to diagnose it and it's valid in C++.)
1394       if (!Index)
1395         return;
1396 
1397       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1398       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1399       // offsets.
1400       uint64_t Offset64 = Offset.getQuantity();
1401       uint64_t ElemSize64 = ElementSize.getQuantity();
1402       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1403       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1404 
1405       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1406         Designator.adjustIndex(Info, E, Index);
1407       clearIsNullPointer();
1408     }
1409     void adjustOffset(CharUnits N) {
1410       Offset += N;
1411       if (N.getQuantity())
1412         clearIsNullPointer();
1413     }
1414   };
1415 
1416   struct MemberPtr {
1417     MemberPtr() {}
1418     explicit MemberPtr(const ValueDecl *Decl) :
1419       DeclAndIsDerivedMember(Decl, false), Path() {}
1420 
1421     /// The member or (direct or indirect) field referred to by this member
1422     /// pointer, or 0 if this is a null member pointer.
1423     const ValueDecl *getDecl() const {
1424       return DeclAndIsDerivedMember.getPointer();
1425     }
1426     /// Is this actually a member of some type derived from the relevant class?
1427     bool isDerivedMember() const {
1428       return DeclAndIsDerivedMember.getInt();
1429     }
1430     /// Get the class which the declaration actually lives in.
1431     const CXXRecordDecl *getContainingRecord() const {
1432       return cast<CXXRecordDecl>(
1433           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1434     }
1435 
1436     void moveInto(APValue &V) const {
1437       V = APValue(getDecl(), isDerivedMember(), Path);
1438     }
1439     void setFrom(const APValue &V) {
1440       assert(V.isMemberPointer());
1441       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1442       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1443       Path.clear();
1444       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1445       Path.insert(Path.end(), P.begin(), P.end());
1446     }
1447 
1448     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1449     /// whether the member is a member of some class derived from the class type
1450     /// of the member pointer.
1451     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1452     /// Path - The path of base/derived classes from the member declaration's
1453     /// class (exclusive) to the class type of the member pointer (inclusive).
1454     SmallVector<const CXXRecordDecl*, 4> Path;
1455 
1456     /// Perform a cast towards the class of the Decl (either up or down the
1457     /// hierarchy).
1458     bool castBack(const CXXRecordDecl *Class) {
1459       assert(!Path.empty());
1460       const CXXRecordDecl *Expected;
1461       if (Path.size() >= 2)
1462         Expected = Path[Path.size() - 2];
1463       else
1464         Expected = getContainingRecord();
1465       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1466         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1467         // if B does not contain the original member and is not a base or
1468         // derived class of the class containing the original member, the result
1469         // of the cast is undefined.
1470         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1471         // (D::*). We consider that to be a language defect.
1472         return false;
1473       }
1474       Path.pop_back();
1475       return true;
1476     }
1477     /// Perform a base-to-derived member pointer cast.
1478     bool castToDerived(const CXXRecordDecl *Derived) {
1479       if (!getDecl())
1480         return true;
1481       if (!isDerivedMember()) {
1482         Path.push_back(Derived);
1483         return true;
1484       }
1485       if (!castBack(Derived))
1486         return false;
1487       if (Path.empty())
1488         DeclAndIsDerivedMember.setInt(false);
1489       return true;
1490     }
1491     /// Perform a derived-to-base member pointer cast.
1492     bool castToBase(const CXXRecordDecl *Base) {
1493       if (!getDecl())
1494         return true;
1495       if (Path.empty())
1496         DeclAndIsDerivedMember.setInt(true);
1497       if (isDerivedMember()) {
1498         Path.push_back(Base);
1499         return true;
1500       }
1501       return castBack(Base);
1502     }
1503   };
1504 
1505   /// Compare two member pointers, which are assumed to be of the same type.
1506   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1507     if (!LHS.getDecl() || !RHS.getDecl())
1508       return !LHS.getDecl() && !RHS.getDecl();
1509     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1510       return false;
1511     return LHS.Path == RHS.Path;
1512   }
1513 }
1514 
1515 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1516 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1517                             const LValue &This, const Expr *E,
1518                             bool AllowNonLiteralTypes = false);
1519 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1520                            bool InvalidBaseOK = false);
1521 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1522                             bool InvalidBaseOK = false);
1523 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1524                                   EvalInfo &Info);
1525 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1526 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1527 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1528                                     EvalInfo &Info);
1529 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1530 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1531 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1532                            EvalInfo &Info);
1533 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1534 
1535 /// Evaluate an integer or fixed point expression into an APResult.
1536 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1537                                         EvalInfo &Info);
1538 
1539 /// Evaluate only a fixed point expression into an APResult.
1540 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1541                                EvalInfo &Info);
1542 
1543 //===----------------------------------------------------------------------===//
1544 // Misc utilities
1545 //===----------------------------------------------------------------------===//
1546 
1547 /// A helper function to create a temporary and set an LValue.
1548 template <class KeyTy>
1549 static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1550                                 LValue &LV, CallStackFrame &Frame) {
1551   LV.set({Key, Frame.Info.CurrentCall->Index,
1552           Frame.Info.CurrentCall->getTempVersion()});
1553   return Frame.createTemporary(Key, IsLifetimeExtended);
1554 }
1555 
1556 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1557 /// preserving its value (by extending by up to one bit as needed).
1558 static void negateAsSigned(APSInt &Int) {
1559   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1560     Int = Int.extend(Int.getBitWidth() + 1);
1561     Int.setIsSigned(true);
1562   }
1563   Int = -Int;
1564 }
1565 
1566 /// Produce a string describing the given constexpr call.
1567 void CallStackFrame::describe(raw_ostream &Out) {
1568   unsigned ArgIndex = 0;
1569   bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1570                       !isa<CXXConstructorDecl>(Callee) &&
1571                       cast<CXXMethodDecl>(Callee)->isInstance();
1572 
1573   if (!IsMemberCall)
1574     Out << *Callee << '(';
1575 
1576   if (This && IsMemberCall) {
1577     APValue Val;
1578     This->moveInto(Val);
1579     Val.printPretty(Out, Info.Ctx,
1580                     This->Designator.MostDerivedType);
1581     // FIXME: Add parens around Val if needed.
1582     Out << "->" << *Callee << '(';
1583     IsMemberCall = false;
1584   }
1585 
1586   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1587        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1588     if (ArgIndex > (unsigned)IsMemberCall)
1589       Out << ", ";
1590 
1591     const ParmVarDecl *Param = *I;
1592     const APValue &Arg = Arguments[ArgIndex];
1593     Arg.printPretty(Out, Info.Ctx, Param->getType());
1594 
1595     if (ArgIndex == 0 && IsMemberCall)
1596       Out << "->" << *Callee << '(';
1597   }
1598 
1599   Out << ')';
1600 }
1601 
1602 /// Evaluate an expression to see if it had side-effects, and discard its
1603 /// result.
1604 /// \return \c true if the caller should keep evaluating.
1605 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1606   APValue Scratch;
1607   if (!Evaluate(Scratch, Info, E))
1608     // We don't need the value, but we might have skipped a side effect here.
1609     return Info.noteSideEffect();
1610   return true;
1611 }
1612 
1613 /// Should this call expression be treated as a string literal?
1614 static bool IsStringLiteralCall(const CallExpr *E) {
1615   unsigned Builtin = E->getBuiltinCallee();
1616   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1617           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1618 }
1619 
1620 static bool IsGlobalLValue(APValue::LValueBase B) {
1621   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1622   // constant expression of pointer type that evaluates to...
1623 
1624   // ... a null pointer value, or a prvalue core constant expression of type
1625   // std::nullptr_t.
1626   if (!B) return true;
1627 
1628   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1629     // ... the address of an object with static storage duration,
1630     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1631       return VD->hasGlobalStorage();
1632     // ... the address of a function,
1633     return isa<FunctionDecl>(D);
1634   }
1635 
1636   if (B.is<TypeInfoLValue>())
1637     return true;
1638 
1639   const Expr *E = B.get<const Expr*>();
1640   switch (E->getStmtClass()) {
1641   default:
1642     return false;
1643   case Expr::CompoundLiteralExprClass: {
1644     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1645     return CLE->isFileScope() && CLE->isLValue();
1646   }
1647   case Expr::MaterializeTemporaryExprClass:
1648     // A materialized temporary might have been lifetime-extended to static
1649     // storage duration.
1650     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1651   // A string literal has static storage duration.
1652   case Expr::StringLiteralClass:
1653   case Expr::PredefinedExprClass:
1654   case Expr::ObjCStringLiteralClass:
1655   case Expr::ObjCEncodeExprClass:
1656   case Expr::CXXUuidofExprClass:
1657     return true;
1658   case Expr::ObjCBoxedExprClass:
1659     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
1660   case Expr::CallExprClass:
1661     return IsStringLiteralCall(cast<CallExpr>(E));
1662   // For GCC compatibility, &&label has static storage duration.
1663   case Expr::AddrLabelExprClass:
1664     return true;
1665   // A Block literal expression may be used as the initialization value for
1666   // Block variables at global or local static scope.
1667   case Expr::BlockExprClass:
1668     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1669   case Expr::ImplicitValueInitExprClass:
1670     // FIXME:
1671     // We can never form an lvalue with an implicit value initialization as its
1672     // base through expression evaluation, so these only appear in one case: the
1673     // implicit variable declaration we invent when checking whether a constexpr
1674     // constructor can produce a constant expression. We must assume that such
1675     // an expression might be a global lvalue.
1676     return true;
1677   }
1678 }
1679 
1680 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1681   return LVal.Base.dyn_cast<const ValueDecl*>();
1682 }
1683 
1684 static bool IsLiteralLValue(const LValue &Value) {
1685   if (Value.getLValueCallIndex())
1686     return false;
1687   const Expr *E = Value.Base.dyn_cast<const Expr*>();
1688   return E && !isa<MaterializeTemporaryExpr>(E);
1689 }
1690 
1691 static bool IsWeakLValue(const LValue &Value) {
1692   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1693   return Decl && Decl->isWeak();
1694 }
1695 
1696 static bool isZeroSized(const LValue &Value) {
1697   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1698   if (Decl && isa<VarDecl>(Decl)) {
1699     QualType Ty = Decl->getType();
1700     if (Ty->isArrayType())
1701       return Ty->isIncompleteType() ||
1702              Decl->getASTContext().getTypeSize(Ty) == 0;
1703   }
1704   return false;
1705 }
1706 
1707 static bool HasSameBase(const LValue &A, const LValue &B) {
1708   if (!A.getLValueBase())
1709     return !B.getLValueBase();
1710   if (!B.getLValueBase())
1711     return false;
1712 
1713   if (A.getLValueBase().getOpaqueValue() !=
1714       B.getLValueBase().getOpaqueValue()) {
1715     const Decl *ADecl = GetLValueBaseDecl(A);
1716     if (!ADecl)
1717       return false;
1718     const Decl *BDecl = GetLValueBaseDecl(B);
1719     if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1720       return false;
1721   }
1722 
1723   return IsGlobalLValue(A.getLValueBase()) ||
1724          (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1725           A.getLValueVersion() == B.getLValueVersion());
1726 }
1727 
1728 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1729   assert(Base && "no location for a null lvalue");
1730   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1731   if (VD)
1732     Info.Note(VD->getLocation(), diag::note_declared_at);
1733   else if (const Expr *E = Base.dyn_cast<const Expr*>())
1734     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
1735   // We have no information to show for a typeid(T) object.
1736 }
1737 
1738 /// Check that this reference or pointer core constant expression is a valid
1739 /// value for an address or reference constant expression. Return true if we
1740 /// can fold this expression, whether or not it's a constant expression.
1741 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1742                                           QualType Type, const LValue &LVal,
1743                                           Expr::ConstExprUsage Usage) {
1744   bool IsReferenceType = Type->isReferenceType();
1745 
1746   APValue::LValueBase Base = LVal.getLValueBase();
1747   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1748 
1749   // Check that the object is a global. Note that the fake 'this' object we
1750   // manufacture when checking potential constant expressions is conservatively
1751   // assumed to be global here.
1752   if (!IsGlobalLValue(Base)) {
1753     if (Info.getLangOpts().CPlusPlus11) {
1754       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1755       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
1756         << IsReferenceType << !Designator.Entries.empty()
1757         << !!VD << VD;
1758       NoteLValueLocation(Info, Base);
1759     } else {
1760       Info.FFDiag(Loc);
1761     }
1762     // Don't allow references to temporaries to escape.
1763     return false;
1764   }
1765   assert((Info.checkingPotentialConstantExpression() ||
1766           LVal.getLValueCallIndex() == 0) &&
1767          "have call index for global lvalue");
1768 
1769   if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1770     if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1771       // Check if this is a thread-local variable.
1772       if (Var->getTLSKind())
1773         return false;
1774 
1775       // A dllimport variable never acts like a constant.
1776       if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
1777         return false;
1778     }
1779     if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1780       // __declspec(dllimport) must be handled very carefully:
1781       // We must never initialize an expression with the thunk in C++.
1782       // Doing otherwise would allow the same id-expression to yield
1783       // different addresses for the same function in different translation
1784       // units.  However, this means that we must dynamically initialize the
1785       // expression with the contents of the import address table at runtime.
1786       //
1787       // The C language has no notion of ODR; furthermore, it has no notion of
1788       // dynamic initialization.  This means that we are permitted to
1789       // perform initialization with the address of the thunk.
1790       if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1791           FD->hasAttr<DLLImportAttr>())
1792         return false;
1793     }
1794   }
1795 
1796   // Allow address constant expressions to be past-the-end pointers. This is
1797   // an extension: the standard requires them to point to an object.
1798   if (!IsReferenceType)
1799     return true;
1800 
1801   // A reference constant expression must refer to an object.
1802   if (!Base) {
1803     // FIXME: diagnostic
1804     Info.CCEDiag(Loc);
1805     return true;
1806   }
1807 
1808   // Does this refer one past the end of some object?
1809   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1810     const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1811     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
1812       << !Designator.Entries.empty() << !!VD << VD;
1813     NoteLValueLocation(Info, Base);
1814   }
1815 
1816   return true;
1817 }
1818 
1819 /// Member pointers are constant expressions unless they point to a
1820 /// non-virtual dllimport member function.
1821 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1822                                                  SourceLocation Loc,
1823                                                  QualType Type,
1824                                                  const APValue &Value,
1825                                                  Expr::ConstExprUsage Usage) {
1826   const ValueDecl *Member = Value.getMemberPointerDecl();
1827   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1828   if (!FD)
1829     return true;
1830   return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
1831          !FD->hasAttr<DLLImportAttr>();
1832 }
1833 
1834 /// Check that this core constant expression is of literal type, and if not,
1835 /// produce an appropriate diagnostic.
1836 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1837                              const LValue *This = nullptr) {
1838   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1839     return true;
1840 
1841   // C++1y: A constant initializer for an object o [...] may also invoke
1842   // constexpr constructors for o and its subobjects even if those objects
1843   // are of non-literal class types.
1844   //
1845   // C++11 missed this detail for aggregates, so classes like this:
1846   //   struct foo_t { union { int i; volatile int j; } u; };
1847   // are not (obviously) initializable like so:
1848   //   __attribute__((__require_constant_initialization__))
1849   //   static const foo_t x = {{0}};
1850   // because "i" is a subobject with non-literal initialization (due to the
1851   // volatile member of the union). See:
1852   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1853   // Therefore, we use the C++1y behavior.
1854   if (This && Info.EvaluatingDecl == This->getLValueBase())
1855     return true;
1856 
1857   // Prvalue constant expressions must be of literal types.
1858   if (Info.getLangOpts().CPlusPlus11)
1859     Info.FFDiag(E, diag::note_constexpr_nonliteral)
1860       << E->getType();
1861   else
1862     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1863   return false;
1864 }
1865 
1866 enum class CheckEvaluationResultKind {
1867   ConstantExpression,
1868   FullyInitialized,
1869 };
1870 
1871 static bool
1872 CheckEvaluationResult(CheckEvaluationResultKind CERK, EvalInfo &Info,
1873                       SourceLocation DiagLoc, QualType Type,
1874                       const APValue &Value, Expr::ConstExprUsage Usage,
1875                       SourceLocation SubobjectLoc = SourceLocation()) {
1876   if (!Value.hasValue()) {
1877     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
1878       << true << Type;
1879     if (SubobjectLoc.isValid())
1880       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
1881     return false;
1882   }
1883 
1884   // We allow _Atomic(T) to be initialized from anything that T can be
1885   // initialized from.
1886   if (const AtomicType *AT = Type->getAs<AtomicType>())
1887     Type = AT->getValueType();
1888 
1889   // Core issue 1454: For a literal constant expression of array or class type,
1890   // each subobject of its value shall have been initialized by a constant
1891   // expression.
1892   if (Value.isArray()) {
1893     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1894     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1895       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
1896                                  Value.getArrayInitializedElt(I), Usage,
1897                                  SubobjectLoc))
1898         return false;
1899     }
1900     if (!Value.hasArrayFiller())
1901       return true;
1902     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
1903                                  Value.getArrayFiller(), Usage, SubobjectLoc);
1904   }
1905   if (Value.isUnion() && Value.getUnionField()) {
1906     return CheckEvaluationResult(
1907         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
1908         Value.getUnionValue(), Usage, Value.getUnionField()->getLocation());
1909   }
1910   if (Value.isStruct()) {
1911     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1912     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1913       unsigned BaseIndex = 0;
1914       for (const CXXBaseSpecifier &BS : CD->bases()) {
1915         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
1916                                    Value.getStructBase(BaseIndex), Usage,
1917                                    BS.getBeginLoc()))
1918           return false;
1919         ++BaseIndex;
1920       }
1921     }
1922     for (const auto *I : RD->fields()) {
1923       if (I->isUnnamedBitfield())
1924         continue;
1925 
1926       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
1927                                  Value.getStructField(I->getFieldIndex()),
1928                                  Usage, I->getLocation()))
1929         return false;
1930     }
1931   }
1932 
1933   if (Value.isLValue() &&
1934       CERK == CheckEvaluationResultKind::ConstantExpression) {
1935     LValue LVal;
1936     LVal.setFrom(Info.Ctx, Value);
1937     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
1938   }
1939 
1940   if (Value.isMemberPointer() &&
1941       CERK == CheckEvaluationResultKind::ConstantExpression)
1942     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
1943 
1944   // Everything else is fine.
1945   return true;
1946 }
1947 
1948 /// Check that this core constant expression value is a valid value for a
1949 /// constant expression. If not, report an appropriate diagnostic. Does not
1950 /// check that the expression is of literal type.
1951 static bool
1952 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
1953                         const APValue &Value,
1954                         Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
1955   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
1956                                Info, DiagLoc, Type, Value, Usage);
1957 }
1958 
1959 /// Check that this evaluated value is fully-initialized and can be loaded by
1960 /// an lvalue-to-rvalue conversion.
1961 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
1962                                   QualType Type, const APValue &Value) {
1963   return CheckEvaluationResult(CheckEvaluationResultKind::FullyInitialized,
1964                                Info, DiagLoc, Type, Value,
1965                                Expr::EvaluateForCodeGen);
1966 }
1967 
1968 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1969   // A null base expression indicates a null pointer.  These are always
1970   // evaluatable, and they are false unless the offset is zero.
1971   if (!Value.getLValueBase()) {
1972     Result = !Value.getLValueOffset().isZero();
1973     return true;
1974   }
1975 
1976   // We have a non-null base.  These are generally known to be true, but if it's
1977   // a weak declaration it can be null at runtime.
1978   Result = true;
1979   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1980   return !Decl || !Decl->isWeak();
1981 }
1982 
1983 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1984   switch (Val.getKind()) {
1985   case APValue::None:
1986   case APValue::Indeterminate:
1987     return false;
1988   case APValue::Int:
1989     Result = Val.getInt().getBoolValue();
1990     return true;
1991   case APValue::FixedPoint:
1992     Result = Val.getFixedPoint().getBoolValue();
1993     return true;
1994   case APValue::Float:
1995     Result = !Val.getFloat().isZero();
1996     return true;
1997   case APValue::ComplexInt:
1998     Result = Val.getComplexIntReal().getBoolValue() ||
1999              Val.getComplexIntImag().getBoolValue();
2000     return true;
2001   case APValue::ComplexFloat:
2002     Result = !Val.getComplexFloatReal().isZero() ||
2003              !Val.getComplexFloatImag().isZero();
2004     return true;
2005   case APValue::LValue:
2006     return EvalPointerValueAsBool(Val, Result);
2007   case APValue::MemberPointer:
2008     Result = Val.getMemberPointerDecl();
2009     return true;
2010   case APValue::Vector:
2011   case APValue::Array:
2012   case APValue::Struct:
2013   case APValue::Union:
2014   case APValue::AddrLabelDiff:
2015     return false;
2016   }
2017 
2018   llvm_unreachable("unknown APValue kind");
2019 }
2020 
2021 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2022                                        EvalInfo &Info) {
2023   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2024   APValue Val;
2025   if (!Evaluate(Val, Info, E))
2026     return false;
2027   return HandleConversionToBool(Val, Result);
2028 }
2029 
2030 template<typename T>
2031 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2032                            const T &SrcValue, QualType DestType) {
2033   Info.CCEDiag(E, diag::note_constexpr_overflow)
2034     << SrcValue << DestType;
2035   return Info.noteUndefinedBehavior();
2036 }
2037 
2038 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2039                                  QualType SrcType, const APFloat &Value,
2040                                  QualType DestType, APSInt &Result) {
2041   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2042   // Determine whether we are converting to unsigned or signed.
2043   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2044 
2045   Result = APSInt(DestWidth, !DestSigned);
2046   bool ignored;
2047   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2048       & APFloat::opInvalidOp)
2049     return HandleOverflow(Info, E, Value, DestType);
2050   return true;
2051 }
2052 
2053 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2054                                    QualType SrcType, QualType DestType,
2055                                    APFloat &Result) {
2056   APFloat Value = Result;
2057   bool ignored;
2058   Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2059                  APFloat::rmNearestTiesToEven, &ignored);
2060   return true;
2061 }
2062 
2063 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2064                                  QualType DestType, QualType SrcType,
2065                                  const APSInt &Value) {
2066   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2067   // Figure out if this is a truncate, extend or noop cast.
2068   // If the input is signed, do a sign extend, noop, or truncate.
2069   APSInt Result = Value.extOrTrunc(DestWidth);
2070   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2071   if (DestType->isBooleanType())
2072     Result = Value.getBoolValue();
2073   return Result;
2074 }
2075 
2076 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2077                                  QualType SrcType, const APSInt &Value,
2078                                  QualType DestType, APFloat &Result) {
2079   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2080   Result.convertFromAPInt(Value, Value.isSigned(),
2081                           APFloat::rmNearestTiesToEven);
2082   return true;
2083 }
2084 
2085 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2086                                   APValue &Value, const FieldDecl *FD) {
2087   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2088 
2089   if (!Value.isInt()) {
2090     // Trying to store a pointer-cast-to-integer into a bitfield.
2091     // FIXME: In this case, we should provide the diagnostic for casting
2092     // a pointer to an integer.
2093     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2094     Info.FFDiag(E);
2095     return false;
2096   }
2097 
2098   APSInt &Int = Value.getInt();
2099   unsigned OldBitWidth = Int.getBitWidth();
2100   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2101   if (NewBitWidth < OldBitWidth)
2102     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2103   return true;
2104 }
2105 
2106 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2107                                   llvm::APInt &Res) {
2108   APValue SVal;
2109   if (!Evaluate(SVal, Info, E))
2110     return false;
2111   if (SVal.isInt()) {
2112     Res = SVal.getInt();
2113     return true;
2114   }
2115   if (SVal.isFloat()) {
2116     Res = SVal.getFloat().bitcastToAPInt();
2117     return true;
2118   }
2119   if (SVal.isVector()) {
2120     QualType VecTy = E->getType();
2121     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2122     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2123     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2124     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2125     Res = llvm::APInt::getNullValue(VecSize);
2126     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2127       APValue &Elt = SVal.getVectorElt(i);
2128       llvm::APInt EltAsInt;
2129       if (Elt.isInt()) {
2130         EltAsInt = Elt.getInt();
2131       } else if (Elt.isFloat()) {
2132         EltAsInt = Elt.getFloat().bitcastToAPInt();
2133       } else {
2134         // Don't try to handle vectors of anything other than int or float
2135         // (not sure if it's possible to hit this case).
2136         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2137         return false;
2138       }
2139       unsigned BaseEltSize = EltAsInt.getBitWidth();
2140       if (BigEndian)
2141         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2142       else
2143         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2144     }
2145     return true;
2146   }
2147   // Give up if the input isn't an int, float, or vector.  For example, we
2148   // reject "(v4i16)(intptr_t)&a".
2149   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2150   return false;
2151 }
2152 
2153 /// Perform the given integer operation, which is known to need at most BitWidth
2154 /// bits, and check for overflow in the original type (if that type was not an
2155 /// unsigned type).
2156 template<typename Operation>
2157 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2158                                  const APSInt &LHS, const APSInt &RHS,
2159                                  unsigned BitWidth, Operation Op,
2160                                  APSInt &Result) {
2161   if (LHS.isUnsigned()) {
2162     Result = Op(LHS, RHS);
2163     return true;
2164   }
2165 
2166   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2167   Result = Value.trunc(LHS.getBitWidth());
2168   if (Result.extend(BitWidth) != Value) {
2169     if (Info.checkingForUndefinedBehavior())
2170       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2171                                        diag::warn_integer_constant_overflow)
2172           << Result.toString(10) << E->getType();
2173     else
2174       return HandleOverflow(Info, E, Value, E->getType());
2175   }
2176   return true;
2177 }
2178 
2179 /// Perform the given binary integer operation.
2180 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2181                               BinaryOperatorKind Opcode, APSInt RHS,
2182                               APSInt &Result) {
2183   switch (Opcode) {
2184   default:
2185     Info.FFDiag(E);
2186     return false;
2187   case BO_Mul:
2188     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2189                                 std::multiplies<APSInt>(), Result);
2190   case BO_Add:
2191     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2192                                 std::plus<APSInt>(), Result);
2193   case BO_Sub:
2194     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2195                                 std::minus<APSInt>(), Result);
2196   case BO_And: Result = LHS & RHS; return true;
2197   case BO_Xor: Result = LHS ^ RHS; return true;
2198   case BO_Or:  Result = LHS | RHS; return true;
2199   case BO_Div:
2200   case BO_Rem:
2201     if (RHS == 0) {
2202       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2203       return false;
2204     }
2205     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2206     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2207     // this operation and gives the two's complement result.
2208     if (RHS.isNegative() && RHS.isAllOnesValue() &&
2209         LHS.isSigned() && LHS.isMinSignedValue())
2210       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2211                             E->getType());
2212     return true;
2213   case BO_Shl: {
2214     if (Info.getLangOpts().OpenCL)
2215       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2216       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2217                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2218                     RHS.isUnsigned());
2219     else if (RHS.isSigned() && RHS.isNegative()) {
2220       // During constant-folding, a negative shift is an opposite shift. Such
2221       // a shift is not a constant expression.
2222       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2223       RHS = -RHS;
2224       goto shift_right;
2225     }
2226   shift_left:
2227     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2228     // the shifted type.
2229     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2230     if (SA != RHS) {
2231       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2232         << RHS << E->getType() << LHS.getBitWidth();
2233     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) {
2234       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2235       // operand, and must not overflow the corresponding unsigned type.
2236       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2237       // E1 x 2^E2 module 2^N.
2238       if (LHS.isNegative())
2239         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2240       else if (LHS.countLeadingZeros() < SA)
2241         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2242     }
2243     Result = LHS << SA;
2244     return true;
2245   }
2246   case BO_Shr: {
2247     if (Info.getLangOpts().OpenCL)
2248       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2249       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2250                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2251                     RHS.isUnsigned());
2252     else if (RHS.isSigned() && RHS.isNegative()) {
2253       // During constant-folding, a negative shift is an opposite shift. Such a
2254       // shift is not a constant expression.
2255       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2256       RHS = -RHS;
2257       goto shift_left;
2258     }
2259   shift_right:
2260     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2261     // shifted type.
2262     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2263     if (SA != RHS)
2264       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2265         << RHS << E->getType() << LHS.getBitWidth();
2266     Result = LHS >> SA;
2267     return true;
2268   }
2269 
2270   case BO_LT: Result = LHS < RHS; return true;
2271   case BO_GT: Result = LHS > RHS; return true;
2272   case BO_LE: Result = LHS <= RHS; return true;
2273   case BO_GE: Result = LHS >= RHS; return true;
2274   case BO_EQ: Result = LHS == RHS; return true;
2275   case BO_NE: Result = LHS != RHS; return true;
2276   case BO_Cmp:
2277     llvm_unreachable("BO_Cmp should be handled elsewhere");
2278   }
2279 }
2280 
2281 /// Perform the given binary floating-point operation, in-place, on LHS.
2282 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2283                                   APFloat &LHS, BinaryOperatorKind Opcode,
2284                                   const APFloat &RHS) {
2285   switch (Opcode) {
2286   default:
2287     Info.FFDiag(E);
2288     return false;
2289   case BO_Mul:
2290     LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2291     break;
2292   case BO_Add:
2293     LHS.add(RHS, APFloat::rmNearestTiesToEven);
2294     break;
2295   case BO_Sub:
2296     LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2297     break;
2298   case BO_Div:
2299     // [expr.mul]p4:
2300     //   If the second operand of / or % is zero the behavior is undefined.
2301     if (RHS.isZero())
2302       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2303     LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2304     break;
2305   }
2306 
2307   // [expr.pre]p4:
2308   //   If during the evaluation of an expression, the result is not
2309   //   mathematically defined [...], the behavior is undefined.
2310   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2311   if (LHS.isNaN()) {
2312     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2313     return Info.noteUndefinedBehavior();
2314   }
2315   return true;
2316 }
2317 
2318 /// Cast an lvalue referring to a base subobject to a derived class, by
2319 /// truncating the lvalue's path to the given length.
2320 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2321                                const RecordDecl *TruncatedType,
2322                                unsigned TruncatedElements) {
2323   SubobjectDesignator &D = Result.Designator;
2324 
2325   // Check we actually point to a derived class object.
2326   if (TruncatedElements == D.Entries.size())
2327     return true;
2328   assert(TruncatedElements >= D.MostDerivedPathLength &&
2329          "not casting to a derived class");
2330   if (!Result.checkSubobject(Info, E, CSK_Derived))
2331     return false;
2332 
2333   // Truncate the path to the subobject, and remove any derived-to-base offsets.
2334   const RecordDecl *RD = TruncatedType;
2335   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2336     if (RD->isInvalidDecl()) return false;
2337     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2338     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2339     if (isVirtualBaseClass(D.Entries[I]))
2340       Result.Offset -= Layout.getVBaseClassOffset(Base);
2341     else
2342       Result.Offset -= Layout.getBaseClassOffset(Base);
2343     RD = Base;
2344   }
2345   D.Entries.resize(TruncatedElements);
2346   return true;
2347 }
2348 
2349 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2350                                    const CXXRecordDecl *Derived,
2351                                    const CXXRecordDecl *Base,
2352                                    const ASTRecordLayout *RL = nullptr) {
2353   if (!RL) {
2354     if (Derived->isInvalidDecl()) return false;
2355     RL = &Info.Ctx.getASTRecordLayout(Derived);
2356   }
2357 
2358   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2359   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2360   return true;
2361 }
2362 
2363 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2364                              const CXXRecordDecl *DerivedDecl,
2365                              const CXXBaseSpecifier *Base) {
2366   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2367 
2368   if (!Base->isVirtual())
2369     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2370 
2371   SubobjectDesignator &D = Obj.Designator;
2372   if (D.Invalid)
2373     return false;
2374 
2375   // Extract most-derived object and corresponding type.
2376   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2377   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2378     return false;
2379 
2380   // Find the virtual base class.
2381   if (DerivedDecl->isInvalidDecl()) return false;
2382   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2383   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2384   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2385   return true;
2386 }
2387 
2388 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2389                                  QualType Type, LValue &Result) {
2390   for (CastExpr::path_const_iterator PathI = E->path_begin(),
2391                                      PathE = E->path_end();
2392        PathI != PathE; ++PathI) {
2393     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2394                           *PathI))
2395       return false;
2396     Type = (*PathI)->getType();
2397   }
2398   return true;
2399 }
2400 
2401 /// Cast an lvalue referring to a derived class to a known base subobject.
2402 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2403                             const CXXRecordDecl *DerivedRD,
2404                             const CXXRecordDecl *BaseRD) {
2405   CXXBasePaths Paths(/*FindAmbiguities=*/false,
2406                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
2407   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2408     llvm_unreachable("Class must be derived from the passed in base class!");
2409 
2410   for (CXXBasePathElement &Elem : Paths.front())
2411     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2412       return false;
2413   return true;
2414 }
2415 
2416 /// Update LVal to refer to the given field, which must be a member of the type
2417 /// currently described by LVal.
2418 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2419                                const FieldDecl *FD,
2420                                const ASTRecordLayout *RL = nullptr) {
2421   if (!RL) {
2422     if (FD->getParent()->isInvalidDecl()) return false;
2423     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2424   }
2425 
2426   unsigned I = FD->getFieldIndex();
2427   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2428   LVal.addDecl(Info, E, FD);
2429   return true;
2430 }
2431 
2432 /// Update LVal to refer to the given indirect field.
2433 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2434                                        LValue &LVal,
2435                                        const IndirectFieldDecl *IFD) {
2436   for (const auto *C : IFD->chain())
2437     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2438       return false;
2439   return true;
2440 }
2441 
2442 /// Get the size of the given type in char units.
2443 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2444                          QualType Type, CharUnits &Size) {
2445   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2446   // extension.
2447   if (Type->isVoidType() || Type->isFunctionType()) {
2448     Size = CharUnits::One();
2449     return true;
2450   }
2451 
2452   if (Type->isDependentType()) {
2453     Info.FFDiag(Loc);
2454     return false;
2455   }
2456 
2457   if (!Type->isConstantSizeType()) {
2458     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2459     // FIXME: Better diagnostic.
2460     Info.FFDiag(Loc);
2461     return false;
2462   }
2463 
2464   Size = Info.Ctx.getTypeSizeInChars(Type);
2465   return true;
2466 }
2467 
2468 /// Update a pointer value to model pointer arithmetic.
2469 /// \param Info - Information about the ongoing evaluation.
2470 /// \param E - The expression being evaluated, for diagnostic purposes.
2471 /// \param LVal - The pointer value to be updated.
2472 /// \param EltTy - The pointee type represented by LVal.
2473 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2474 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2475                                         LValue &LVal, QualType EltTy,
2476                                         APSInt Adjustment) {
2477   CharUnits SizeOfPointee;
2478   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2479     return false;
2480 
2481   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2482   return true;
2483 }
2484 
2485 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2486                                         LValue &LVal, QualType EltTy,
2487                                         int64_t Adjustment) {
2488   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2489                                      APSInt::get(Adjustment));
2490 }
2491 
2492 /// Update an lvalue to refer to a component of a complex number.
2493 /// \param Info - Information about the ongoing evaluation.
2494 /// \param LVal - The lvalue to be updated.
2495 /// \param EltTy - The complex number's component type.
2496 /// \param Imag - False for the real component, true for the imaginary.
2497 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2498                                        LValue &LVal, QualType EltTy,
2499                                        bool Imag) {
2500   if (Imag) {
2501     CharUnits SizeOfComponent;
2502     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2503       return false;
2504     LVal.Offset += SizeOfComponent;
2505   }
2506   LVal.addComplex(Info, E, EltTy, Imag);
2507   return true;
2508 }
2509 
2510 /// Try to evaluate the initializer for a variable declaration.
2511 ///
2512 /// \param Info   Information about the ongoing evaluation.
2513 /// \param E      An expression to be used when printing diagnostics.
2514 /// \param VD     The variable whose initializer should be obtained.
2515 /// \param Frame  The frame in which the variable was created. Must be null
2516 ///               if this variable is not local to the evaluation.
2517 /// \param Result Filled in with a pointer to the value of the variable.
2518 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2519                                 const VarDecl *VD, CallStackFrame *Frame,
2520                                 APValue *&Result, const LValue *LVal) {
2521 
2522   // If this is a parameter to an active constexpr function call, perform
2523   // argument substitution.
2524   if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2525     // Assume arguments of a potential constant expression are unknown
2526     // constant expressions.
2527     if (Info.checkingPotentialConstantExpression())
2528       return false;
2529     if (!Frame || !Frame->Arguments) {
2530       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2531       return false;
2532     }
2533     Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2534     return true;
2535   }
2536 
2537   // If this is a local variable, dig out its value.
2538   if (Frame) {
2539     Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2540                   : Frame->getCurrentTemporary(VD);
2541     if (!Result) {
2542       // Assume variables referenced within a lambda's call operator that were
2543       // not declared within the call operator are captures and during checking
2544       // of a potential constant expression, assume they are unknown constant
2545       // expressions.
2546       assert(isLambdaCallOperator(Frame->Callee) &&
2547              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2548              "missing value for local variable");
2549       if (Info.checkingPotentialConstantExpression())
2550         return false;
2551       // FIXME: implement capture evaluation during constant expr evaluation.
2552       Info.FFDiag(E->getBeginLoc(),
2553                   diag::note_unimplemented_constexpr_lambda_feature_ast)
2554           << "captures not currently allowed";
2555       return false;
2556     }
2557     return true;
2558   }
2559 
2560   // Dig out the initializer, and use the declaration which it's attached to.
2561   const Expr *Init = VD->getAnyInitializer(VD);
2562   if (!Init || Init->isValueDependent()) {
2563     // If we're checking a potential constant expression, the variable could be
2564     // initialized later.
2565     if (!Info.checkingPotentialConstantExpression())
2566       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2567     return false;
2568   }
2569 
2570   // If we're currently evaluating the initializer of this declaration, use that
2571   // in-flight value.
2572   if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2573     Result = Info.EvaluatingDeclValue;
2574     return true;
2575   }
2576 
2577   // Never evaluate the initializer of a weak variable. We can't be sure that
2578   // this is the definition which will be used.
2579   if (VD->isWeak()) {
2580     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2581     return false;
2582   }
2583 
2584   // Check that we can fold the initializer. In C++, we will have already done
2585   // this in the cases where it matters for conformance.
2586   SmallVector<PartialDiagnosticAt, 8> Notes;
2587   if (!VD->evaluateValue(Notes)) {
2588     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2589               Notes.size() + 1) << VD;
2590     Info.Note(VD->getLocation(), diag::note_declared_at);
2591     Info.addNotes(Notes);
2592     return false;
2593   } else if (!VD->checkInitIsICE()) {
2594     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2595                  Notes.size() + 1) << VD;
2596     Info.Note(VD->getLocation(), diag::note_declared_at);
2597     Info.addNotes(Notes);
2598   }
2599 
2600   Result = VD->getEvaluatedValue();
2601   return true;
2602 }
2603 
2604 static bool IsConstNonVolatile(QualType T) {
2605   Qualifiers Quals = T.getQualifiers();
2606   return Quals.hasConst() && !Quals.hasVolatile();
2607 }
2608 
2609 /// Get the base index of the given base class within an APValue representing
2610 /// the given derived class.
2611 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2612                              const CXXRecordDecl *Base) {
2613   Base = Base->getCanonicalDecl();
2614   unsigned Index = 0;
2615   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2616          E = Derived->bases_end(); I != E; ++I, ++Index) {
2617     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2618       return Index;
2619   }
2620 
2621   llvm_unreachable("base class missing from derived class's bases list");
2622 }
2623 
2624 /// Extract the value of a character from a string literal.
2625 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2626                                             uint64_t Index) {
2627   assert(!isa<SourceLocExpr>(Lit) &&
2628          "SourceLocExpr should have already been converted to a StringLiteral");
2629 
2630   // FIXME: Support MakeStringConstant
2631   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2632     std::string Str;
2633     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2634     assert(Index <= Str.size() && "Index too large");
2635     return APSInt::getUnsigned(Str.c_str()[Index]);
2636   }
2637 
2638   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2639     Lit = PE->getFunctionName();
2640   const StringLiteral *S = cast<StringLiteral>(Lit);
2641   const ConstantArrayType *CAT =
2642       Info.Ctx.getAsConstantArrayType(S->getType());
2643   assert(CAT && "string literal isn't an array");
2644   QualType CharType = CAT->getElementType();
2645   assert(CharType->isIntegerType() && "unexpected character type");
2646 
2647   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2648                CharType->isUnsignedIntegerType());
2649   if (Index < S->getLength())
2650     Value = S->getCodeUnit(Index);
2651   return Value;
2652 }
2653 
2654 // Expand a string literal into an array of characters.
2655 //
2656 // FIXME: This is inefficient; we should probably introduce something similar
2657 // to the LLVM ConstantDataArray to make this cheaper.
2658 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
2659                                 APValue &Result) {
2660   const ConstantArrayType *CAT =
2661       Info.Ctx.getAsConstantArrayType(S->getType());
2662   assert(CAT && "string literal isn't an array");
2663   QualType CharType = CAT->getElementType();
2664   assert(CharType->isIntegerType() && "unexpected character type");
2665 
2666   unsigned Elts = CAT->getSize().getZExtValue();
2667   Result = APValue(APValue::UninitArray(),
2668                    std::min(S->getLength(), Elts), Elts);
2669   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2670                CharType->isUnsignedIntegerType());
2671   if (Result.hasArrayFiller())
2672     Result.getArrayFiller() = APValue(Value);
2673   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2674     Value = S->getCodeUnit(I);
2675     Result.getArrayInitializedElt(I) = APValue(Value);
2676   }
2677 }
2678 
2679 // Expand an array so that it has more than Index filled elements.
2680 static void expandArray(APValue &Array, unsigned Index) {
2681   unsigned Size = Array.getArraySize();
2682   assert(Index < Size);
2683 
2684   // Always at least double the number of elements for which we store a value.
2685   unsigned OldElts = Array.getArrayInitializedElts();
2686   unsigned NewElts = std::max(Index+1, OldElts * 2);
2687   NewElts = std::min(Size, std::max(NewElts, 8u));
2688 
2689   // Copy the data across.
2690   APValue NewValue(APValue::UninitArray(), NewElts, Size);
2691   for (unsigned I = 0; I != OldElts; ++I)
2692     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2693   for (unsigned I = OldElts; I != NewElts; ++I)
2694     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2695   if (NewValue.hasArrayFiller())
2696     NewValue.getArrayFiller() = Array.getArrayFiller();
2697   Array.swap(NewValue);
2698 }
2699 
2700 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2701 /// conversion. If it's of class type, we may assume that the copy operation
2702 /// is trivial. Note that this is never true for a union type with fields
2703 /// (because the copy always "reads" the active member) and always true for
2704 /// a non-class type.
2705 static bool isReadByLvalueToRvalueConversion(QualType T) {
2706   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2707   if (!RD || (RD->isUnion() && !RD->field_empty()))
2708     return true;
2709   if (RD->isEmpty())
2710     return false;
2711 
2712   for (auto *Field : RD->fields())
2713     if (isReadByLvalueToRvalueConversion(Field->getType()))
2714       return true;
2715 
2716   for (auto &BaseSpec : RD->bases())
2717     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2718       return true;
2719 
2720   return false;
2721 }
2722 
2723 /// Diagnose an attempt to read from any unreadable field within the specified
2724 /// type, which might be a class type.
2725 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2726                                      QualType T) {
2727   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2728   if (!RD)
2729     return false;
2730 
2731   if (!RD->hasMutableFields())
2732     return false;
2733 
2734   for (auto *Field : RD->fields()) {
2735     // If we're actually going to read this field in some way, then it can't
2736     // be mutable. If we're in a union, then assigning to a mutable field
2737     // (even an empty one) can change the active member, so that's not OK.
2738     // FIXME: Add core issue number for the union case.
2739     if (Field->isMutable() &&
2740         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2741       Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2742       Info.Note(Field->getLocation(), diag::note_declared_at);
2743       return true;
2744     }
2745 
2746     if (diagnoseUnreadableFields(Info, E, Field->getType()))
2747       return true;
2748   }
2749 
2750   for (auto &BaseSpec : RD->bases())
2751     if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2752       return true;
2753 
2754   // All mutable fields were empty, and thus not actually read.
2755   return false;
2756 }
2757 
2758 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
2759                                         APValue::LValueBase Base) {
2760   // A temporary we created.
2761   if (Base.getCallIndex())
2762     return true;
2763 
2764   auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2765   if (!Evaluating)
2766     return false;
2767 
2768   // The variable whose initializer we're evaluating.
2769   if (auto *BaseD = Base.dyn_cast<const ValueDecl*>())
2770     if (declaresSameEntity(Evaluating, BaseD))
2771       return true;
2772 
2773   // A temporary lifetime-extended by the variable whose initializer we're
2774   // evaluating.
2775   if (auto *BaseE = Base.dyn_cast<const Expr *>())
2776     if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
2777       if (declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating))
2778         return true;
2779 
2780   return false;
2781 }
2782 
2783 namespace {
2784 /// A handle to a complete object (an object that is not a subobject of
2785 /// another object).
2786 struct CompleteObject {
2787   /// The identity of the object.
2788   APValue::LValueBase Base;
2789   /// The value of the complete object.
2790   APValue *Value;
2791   /// The type of the complete object.
2792   QualType Type;
2793 
2794   CompleteObject() : Value(nullptr) {}
2795   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
2796       : Base(Base), Value(Value), Type(Type) {}
2797 
2798   bool mayReadMutableMembers(EvalInfo &Info) const {
2799     // In C++14 onwards, it is permitted to read a mutable member whose
2800     // lifetime began within the evaluation.
2801     // FIXME: Should we also allow this in C++11?
2802     if (!Info.getLangOpts().CPlusPlus14)
2803       return false;
2804     return lifetimeStartedInEvaluation(Info, Base);
2805   }
2806 
2807   explicit operator bool() const { return !Type.isNull(); }
2808 };
2809 } // end anonymous namespace
2810 
2811 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
2812                                  bool IsMutable = false) {
2813   // C++ [basic.type.qualifier]p1:
2814   // - A const object is an object of type const T or a non-mutable subobject
2815   //   of a const object.
2816   if (ObjType.isConstQualified() && !IsMutable)
2817     SubobjType.addConst();
2818   // - A volatile object is an object of type const T or a subobject of a
2819   //   volatile object.
2820   if (ObjType.isVolatileQualified())
2821     SubobjType.addVolatile();
2822   return SubobjType;
2823 }
2824 
2825 /// Find the designated sub-object of an rvalue.
2826 template<typename SubobjectHandler>
2827 typename SubobjectHandler::result_type
2828 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2829               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2830   if (Sub.Invalid)
2831     // A diagnostic will have already been produced.
2832     return handler.failed();
2833   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
2834     if (Info.getLangOpts().CPlusPlus11)
2835       Info.FFDiag(E, Sub.isOnePastTheEnd()
2836                          ? diag::note_constexpr_access_past_end
2837                          : diag::note_constexpr_access_unsized_array)
2838           << handler.AccessKind;
2839     else
2840       Info.FFDiag(E);
2841     return handler.failed();
2842   }
2843 
2844   APValue *O = Obj.Value;
2845   QualType ObjType = Obj.Type;
2846   const FieldDecl *LastField = nullptr;
2847   const FieldDecl *VolatileField = nullptr;
2848 
2849   // Walk the designator's path to find the subobject.
2850   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2851     // Reading an indeterminate value is undefined, but assigning over one is OK.
2852     if (O->isAbsent() ||
2853         (O->isIndeterminate() && handler.AccessKind != AK_Assign &&
2854          handler.AccessKind != AK_ReadObjectRepresentation)) {
2855       if (!Info.checkingPotentialConstantExpression())
2856         Info.FFDiag(E, diag::note_constexpr_access_uninit)
2857             << handler.AccessKind << O->isIndeterminate();
2858       return handler.failed();
2859     }
2860 
2861     // C++ [class.ctor]p5:
2862     //    const and volatile semantics are not applied on an object under
2863     //    construction.
2864     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
2865         ObjType->isRecordType() &&
2866         Info.isEvaluatingConstructor(
2867             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
2868                                          Sub.Entries.begin() + I)) !=
2869                           ConstructionPhase::None) {
2870       ObjType = Info.Ctx.getCanonicalType(ObjType);
2871       ObjType.removeLocalConst();
2872       ObjType.removeLocalVolatile();
2873     }
2874 
2875     // If this is our last pass, check that the final object type is OK.
2876     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
2877       // Accesses to volatile objects are prohibited.
2878       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
2879         if (Info.getLangOpts().CPlusPlus) {
2880           int DiagKind;
2881           SourceLocation Loc;
2882           const NamedDecl *Decl = nullptr;
2883           if (VolatileField) {
2884             DiagKind = 2;
2885             Loc = VolatileField->getLocation();
2886             Decl = VolatileField;
2887           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
2888             DiagKind = 1;
2889             Loc = VD->getLocation();
2890             Decl = VD;
2891           } else {
2892             DiagKind = 0;
2893             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
2894               Loc = E->getExprLoc();
2895           }
2896           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2897               << handler.AccessKind << DiagKind << Decl;
2898           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
2899         } else {
2900           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2901         }
2902         return handler.failed();
2903       }
2904 
2905       // If we are reading an object of class type, there may still be more
2906       // things we need to check: if there are any mutable subobjects, we
2907       // cannot perform this read. (This only happens when performing a trivial
2908       // copy or assignment.)
2909       if (ObjType->isRecordType() && isRead(handler.AccessKind) &&
2910           !Obj.mayReadMutableMembers(Info) &&
2911           diagnoseUnreadableFields(Info, E, ObjType))
2912         return handler.failed();
2913     }
2914 
2915     if (I == N) {
2916       if (!handler.found(*O, ObjType))
2917         return false;
2918 
2919       // If we modified a bit-field, truncate it to the right width.
2920       if (isModification(handler.AccessKind) &&
2921           LastField && LastField->isBitField() &&
2922           !truncateBitfieldValue(Info, E, *O, LastField))
2923         return false;
2924 
2925       return true;
2926     }
2927 
2928     LastField = nullptr;
2929     if (ObjType->isArrayType()) {
2930       // Next subobject is an array element.
2931       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2932       assert(CAT && "vla in literal type?");
2933       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
2934       if (CAT->getSize().ule(Index)) {
2935         // Note, it should not be possible to form a pointer with a valid
2936         // designator which points more than one past the end of the array.
2937         if (Info.getLangOpts().CPlusPlus11)
2938           Info.FFDiag(E, diag::note_constexpr_access_past_end)
2939             << handler.AccessKind;
2940         else
2941           Info.FFDiag(E);
2942         return handler.failed();
2943       }
2944 
2945       ObjType = CAT->getElementType();
2946 
2947       if (O->getArrayInitializedElts() > Index)
2948         O = &O->getArrayInitializedElt(Index);
2949       else if (!isRead(handler.AccessKind)) {
2950         expandArray(*O, Index);
2951         O = &O->getArrayInitializedElt(Index);
2952       } else
2953         O = &O->getArrayFiller();
2954     } else if (ObjType->isAnyComplexType()) {
2955       // Next subobject is a complex number.
2956       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
2957       if (Index > 1) {
2958         if (Info.getLangOpts().CPlusPlus11)
2959           Info.FFDiag(E, diag::note_constexpr_access_past_end)
2960             << handler.AccessKind;
2961         else
2962           Info.FFDiag(E);
2963         return handler.failed();
2964       }
2965 
2966       ObjType = getSubobjectType(
2967           ObjType, ObjType->castAs<ComplexType>()->getElementType());
2968 
2969       assert(I == N - 1 && "extracting subobject of scalar?");
2970       if (O->isComplexInt()) {
2971         return handler.found(Index ? O->getComplexIntImag()
2972                                    : O->getComplexIntReal(), ObjType);
2973       } else {
2974         assert(O->isComplexFloat());
2975         return handler.found(Index ? O->getComplexFloatImag()
2976                                    : O->getComplexFloatReal(), ObjType);
2977       }
2978     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2979       if (Field->isMutable() && isRead(handler.AccessKind) &&
2980           !Obj.mayReadMutableMembers(Info)) {
2981         Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
2982           << Field;
2983         Info.Note(Field->getLocation(), diag::note_declared_at);
2984         return handler.failed();
2985       }
2986 
2987       // Next subobject is a class, struct or union field.
2988       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2989       if (RD->isUnion()) {
2990         const FieldDecl *UnionField = O->getUnionField();
2991         if (!UnionField ||
2992             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2993           Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
2994             << handler.AccessKind << Field << !UnionField << UnionField;
2995           return handler.failed();
2996         }
2997         O = &O->getUnionValue();
2998       } else
2999         O = &O->getStructField(Field->getFieldIndex());
3000 
3001       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3002       LastField = Field;
3003       if (Field->getType().isVolatileQualified())
3004         VolatileField = Field;
3005     } else {
3006       // Next subobject is a base class.
3007       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3008       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3009       O = &O->getStructBase(getBaseIndex(Derived, Base));
3010 
3011       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3012     }
3013   }
3014 }
3015 
3016 namespace {
3017 struct ExtractSubobjectHandler {
3018   EvalInfo &Info;
3019   const Expr *E;
3020   APValue &Result;
3021   const AccessKinds AccessKind;
3022 
3023   typedef bool result_type;
3024   bool failed() { return false; }
3025   bool found(APValue &Subobj, QualType SubobjType) {
3026     Result = Subobj;
3027     if (AccessKind == AK_ReadObjectRepresentation)
3028       return true;
3029     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3030   }
3031   bool found(APSInt &Value, QualType SubobjType) {
3032     Result = APValue(Value);
3033     return true;
3034   }
3035   bool found(APFloat &Value, QualType SubobjType) {
3036     Result = APValue(Value);
3037     return true;
3038   }
3039 };
3040 } // end anonymous namespace
3041 
3042 /// Extract the designated sub-object of an rvalue.
3043 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3044                              const CompleteObject &Obj,
3045                              const SubobjectDesignator &Sub, APValue &Result,
3046                              AccessKinds AK = AK_Read) {
3047   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3048   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3049   return findSubobject(Info, E, Obj, Sub, Handler);
3050 }
3051 
3052 namespace {
3053 struct ModifySubobjectHandler {
3054   EvalInfo &Info;
3055   APValue &NewVal;
3056   const Expr *E;
3057 
3058   typedef bool result_type;
3059   static const AccessKinds AccessKind = AK_Assign;
3060 
3061   bool checkConst(QualType QT) {
3062     // Assigning to a const object has undefined behavior.
3063     if (QT.isConstQualified()) {
3064       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3065       return false;
3066     }
3067     return true;
3068   }
3069 
3070   bool failed() { return false; }
3071   bool found(APValue &Subobj, QualType SubobjType) {
3072     if (!checkConst(SubobjType))
3073       return false;
3074     // We've been given ownership of NewVal, so just swap it in.
3075     Subobj.swap(NewVal);
3076     return true;
3077   }
3078   bool found(APSInt &Value, QualType SubobjType) {
3079     if (!checkConst(SubobjType))
3080       return false;
3081     if (!NewVal.isInt()) {
3082       // Maybe trying to write a cast pointer value into a complex?
3083       Info.FFDiag(E);
3084       return false;
3085     }
3086     Value = NewVal.getInt();
3087     return true;
3088   }
3089   bool found(APFloat &Value, QualType SubobjType) {
3090     if (!checkConst(SubobjType))
3091       return false;
3092     Value = NewVal.getFloat();
3093     return true;
3094   }
3095 };
3096 } // end anonymous namespace
3097 
3098 const AccessKinds ModifySubobjectHandler::AccessKind;
3099 
3100 /// Update the designated sub-object of an rvalue to the given value.
3101 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3102                             const CompleteObject &Obj,
3103                             const SubobjectDesignator &Sub,
3104                             APValue &NewVal) {
3105   ModifySubobjectHandler Handler = { Info, NewVal, E };
3106   return findSubobject(Info, E, Obj, Sub, Handler);
3107 }
3108 
3109 /// Find the position where two subobject designators diverge, or equivalently
3110 /// the length of the common initial subsequence.
3111 static unsigned FindDesignatorMismatch(QualType ObjType,
3112                                        const SubobjectDesignator &A,
3113                                        const SubobjectDesignator &B,
3114                                        bool &WasArrayIndex) {
3115   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3116   for (/**/; I != N; ++I) {
3117     if (!ObjType.isNull() &&
3118         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3119       // Next subobject is an array element.
3120       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3121         WasArrayIndex = true;
3122         return I;
3123       }
3124       if (ObjType->isAnyComplexType())
3125         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3126       else
3127         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3128     } else {
3129       if (A.Entries[I].getAsBaseOrMember() !=
3130           B.Entries[I].getAsBaseOrMember()) {
3131         WasArrayIndex = false;
3132         return I;
3133       }
3134       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3135         // Next subobject is a field.
3136         ObjType = FD->getType();
3137       else
3138         // Next subobject is a base class.
3139         ObjType = QualType();
3140     }
3141   }
3142   WasArrayIndex = false;
3143   return I;
3144 }
3145 
3146 /// Determine whether the given subobject designators refer to elements of the
3147 /// same array object.
3148 static bool AreElementsOfSameArray(QualType ObjType,
3149                                    const SubobjectDesignator &A,
3150                                    const SubobjectDesignator &B) {
3151   if (A.Entries.size() != B.Entries.size())
3152     return false;
3153 
3154   bool IsArray = A.MostDerivedIsArrayElement;
3155   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3156     // A is a subobject of the array element.
3157     return false;
3158 
3159   // If A (and B) designates an array element, the last entry will be the array
3160   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3161   // of length 1' case, and the entire path must match.
3162   bool WasArrayIndex;
3163   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3164   return CommonLength >= A.Entries.size() - IsArray;
3165 }
3166 
3167 /// Find the complete object to which an LValue refers.
3168 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3169                                          AccessKinds AK, const LValue &LVal,
3170                                          QualType LValType) {
3171   if (LVal.InvalidBase) {
3172     Info.FFDiag(E);
3173     return CompleteObject();
3174   }
3175 
3176   if (!LVal.Base) {
3177     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3178     return CompleteObject();
3179   }
3180 
3181   CallStackFrame *Frame = nullptr;
3182   unsigned Depth = 0;
3183   if (LVal.getLValueCallIndex()) {
3184     std::tie(Frame, Depth) =
3185         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3186     if (!Frame) {
3187       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3188         << AK << LVal.Base.is<const ValueDecl*>();
3189       NoteLValueLocation(Info, LVal.Base);
3190       return CompleteObject();
3191     }
3192   }
3193 
3194   bool IsAccess = isFormalAccess(AK);
3195 
3196   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3197   // is not a constant expression (even if the object is non-volatile). We also
3198   // apply this rule to C++98, in order to conform to the expected 'volatile'
3199   // semantics.
3200   if (IsAccess && LValType.isVolatileQualified()) {
3201     if (Info.getLangOpts().CPlusPlus)
3202       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3203         << AK << LValType;
3204     else
3205       Info.FFDiag(E);
3206     return CompleteObject();
3207   }
3208 
3209   // Compute value storage location and type of base object.
3210   APValue *BaseVal = nullptr;
3211   QualType BaseType = getType(LVal.Base);
3212 
3213   if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3214     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3215     // In C++11, constexpr, non-volatile variables initialized with constant
3216     // expressions are constant expressions too. Inside constexpr functions,
3217     // parameters are constant expressions even if they're non-const.
3218     // In C++1y, objects local to a constant expression (those with a Frame) are
3219     // both readable and writable inside constant expressions.
3220     // In C, such things can also be folded, although they are not ICEs.
3221     const VarDecl *VD = dyn_cast<VarDecl>(D);
3222     if (VD) {
3223       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3224         VD = VDef;
3225     }
3226     if (!VD || VD->isInvalidDecl()) {
3227       Info.FFDiag(E);
3228       return CompleteObject();
3229     }
3230 
3231     // Unless we're looking at a local variable or argument in a constexpr call,
3232     // the variable we're reading must be const.
3233     if (!Frame) {
3234       if (Info.getLangOpts().CPlusPlus14 &&
3235           declaresSameEntity(
3236               VD, Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) {
3237         // OK, we can read and modify an object if we're in the process of
3238         // evaluating its initializer, because its lifetime began in this
3239         // evaluation.
3240       } else if (isModification(AK)) {
3241         // All the remaining cases do not permit modification of the object.
3242         Info.FFDiag(E, diag::note_constexpr_modify_global);
3243         return CompleteObject();
3244       } else if (VD->isConstexpr()) {
3245         // OK, we can read this variable.
3246       } else if (BaseType->isIntegralOrEnumerationType()) {
3247         // In OpenCL if a variable is in constant address space it is a const
3248         // value.
3249         if (!(BaseType.isConstQualified() ||
3250               (Info.getLangOpts().OpenCL &&
3251                BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3252           if (!IsAccess)
3253             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3254           if (Info.getLangOpts().CPlusPlus) {
3255             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3256             Info.Note(VD->getLocation(), diag::note_declared_at);
3257           } else {
3258             Info.FFDiag(E);
3259           }
3260           return CompleteObject();
3261         }
3262       } else if (!IsAccess) {
3263         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3264       } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3265         // We support folding of const floating-point types, in order to make
3266         // static const data members of such types (supported as an extension)
3267         // more useful.
3268         if (Info.getLangOpts().CPlusPlus11) {
3269           Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3270           Info.Note(VD->getLocation(), diag::note_declared_at);
3271         } else {
3272           Info.CCEDiag(E);
3273         }
3274       } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3275         Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3276         // Keep evaluating to see what we can do.
3277       } else {
3278         // FIXME: Allow folding of values of any literal type in all languages.
3279         if (Info.checkingPotentialConstantExpression() &&
3280             VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3281           // The definition of this variable could be constexpr. We can't
3282           // access it right now, but may be able to in future.
3283         } else if (Info.getLangOpts().CPlusPlus11) {
3284           Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3285           Info.Note(VD->getLocation(), diag::note_declared_at);
3286         } else {
3287           Info.FFDiag(E);
3288         }
3289         return CompleteObject();
3290       }
3291     }
3292 
3293     if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
3294       return CompleteObject();
3295   } else {
3296     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3297 
3298     if (!Frame) {
3299       if (const MaterializeTemporaryExpr *MTE =
3300               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
3301         assert(MTE->getStorageDuration() == SD_Static &&
3302                "should have a frame for a non-global materialized temporary");
3303 
3304         // Per C++1y [expr.const]p2:
3305         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3306         //   - a [...] glvalue of integral or enumeration type that refers to
3307         //     a non-volatile const object [...]
3308         //   [...]
3309         //   - a [...] glvalue of literal type that refers to a non-volatile
3310         //     object whose lifetime began within the evaluation of e.
3311         //
3312         // C++11 misses the 'began within the evaluation of e' check and
3313         // instead allows all temporaries, including things like:
3314         //   int &&r = 1;
3315         //   int x = ++r;
3316         //   constexpr int k = r;
3317         // Therefore we use the C++14 rules in C++11 too.
3318         const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3319         const ValueDecl *ED = MTE->getExtendingDecl();
3320         if (!(BaseType.isConstQualified() &&
3321               BaseType->isIntegralOrEnumerationType()) &&
3322             !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
3323           if (!IsAccess)
3324             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3325           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3326           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3327           return CompleteObject();
3328         }
3329 
3330         BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3331         assert(BaseVal && "got reference to unevaluated temporary");
3332       } else {
3333         if (!IsAccess)
3334           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3335         APValue Val;
3336         LVal.moveInto(Val);
3337         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3338             << AK
3339             << Val.getAsString(Info.Ctx,
3340                                Info.Ctx.getLValueReferenceType(LValType));
3341         NoteLValueLocation(Info, LVal.Base);
3342         return CompleteObject();
3343       }
3344     } else {
3345       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
3346       assert(BaseVal && "missing value for temporary");
3347     }
3348   }
3349 
3350   // In C++14, we can't safely access any mutable state when we might be
3351   // evaluating after an unmodeled side effect.
3352   //
3353   // FIXME: Not all local state is mutable. Allow local constant subobjects
3354   // to be read here (but take care with 'mutable' fields).
3355   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3356        Info.EvalStatus.HasSideEffects) ||
3357       (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
3358     return CompleteObject();
3359 
3360   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
3361 }
3362 
3363 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
3364 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3365 /// glvalue referred to by an entity of reference type.
3366 ///
3367 /// \param Info - Information about the ongoing evaluation.
3368 /// \param Conv - The expression for which we are performing the conversion.
3369 ///               Used for diagnostics.
3370 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3371 ///               case of a non-class type).
3372 /// \param LVal - The glvalue on which we are attempting to perform this action.
3373 /// \param RVal - The produced value will be placed here.
3374 /// \param WantObjectRepresentation - If true, we're looking for the object
3375 ///               representation rather than the value, and in particular,
3376 ///               there is no requirement that the result be fully initialized.
3377 static bool
3378 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
3379                                const LValue &LVal, APValue &RVal,
3380                                bool WantObjectRepresentation = false) {
3381   if (LVal.Designator.Invalid)
3382     return false;
3383 
3384   // Check for special cases where there is no existing APValue to look at.
3385   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3386 
3387   AccessKinds AK =
3388       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
3389 
3390   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
3391     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3392       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3393       // initializer until now for such expressions. Such an expression can't be
3394       // an ICE in C, so this only matters for fold.
3395       if (Type.isVolatileQualified()) {
3396         Info.FFDiag(Conv);
3397         return false;
3398       }
3399       APValue Lit;
3400       if (!Evaluate(Lit, Info, CLE->getInitializer()))
3401         return false;
3402       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
3403       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
3404     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3405       // Special-case character extraction so we don't have to construct an
3406       // APValue for the whole string.
3407       assert(LVal.Designator.Entries.size() <= 1 &&
3408              "Can only read characters from string literals");
3409       if (LVal.Designator.Entries.empty()) {
3410         // Fail for now for LValue to RValue conversion of an array.
3411         // (This shouldn't show up in C/C++, but it could be triggered by a
3412         // weird EvaluateAsRValue call from a tool.)
3413         Info.FFDiag(Conv);
3414         return false;
3415       }
3416       if (LVal.Designator.isOnePastTheEnd()) {
3417         if (Info.getLangOpts().CPlusPlus11)
3418           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
3419         else
3420           Info.FFDiag(Conv);
3421         return false;
3422       }
3423       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
3424       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3425       return true;
3426     }
3427   }
3428 
3429   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
3430   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
3431 }
3432 
3433 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3434 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3435                              QualType LValType, APValue &Val) {
3436   if (LVal.Designator.Invalid)
3437     return false;
3438 
3439   if (!Info.getLangOpts().CPlusPlus14) {
3440     Info.FFDiag(E);
3441     return false;
3442   }
3443 
3444   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3445   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3446 }
3447 
3448 namespace {
3449 struct CompoundAssignSubobjectHandler {
3450   EvalInfo &Info;
3451   const Expr *E;
3452   QualType PromotedLHSType;
3453   BinaryOperatorKind Opcode;
3454   const APValue &RHS;
3455 
3456   static const AccessKinds AccessKind = AK_Assign;
3457 
3458   typedef bool result_type;
3459 
3460   bool checkConst(QualType QT) {
3461     // Assigning to a const object has undefined behavior.
3462     if (QT.isConstQualified()) {
3463       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3464       return false;
3465     }
3466     return true;
3467   }
3468 
3469   bool failed() { return false; }
3470   bool found(APValue &Subobj, QualType SubobjType) {
3471     switch (Subobj.getKind()) {
3472     case APValue::Int:
3473       return found(Subobj.getInt(), SubobjType);
3474     case APValue::Float:
3475       return found(Subobj.getFloat(), SubobjType);
3476     case APValue::ComplexInt:
3477     case APValue::ComplexFloat:
3478       // FIXME: Implement complex compound assignment.
3479       Info.FFDiag(E);
3480       return false;
3481     case APValue::LValue:
3482       return foundPointer(Subobj, SubobjType);
3483     default:
3484       // FIXME: can this happen?
3485       Info.FFDiag(E);
3486       return false;
3487     }
3488   }
3489   bool found(APSInt &Value, QualType SubobjType) {
3490     if (!checkConst(SubobjType))
3491       return false;
3492 
3493     if (!SubobjType->isIntegerType()) {
3494       // We don't support compound assignment on integer-cast-to-pointer
3495       // values.
3496       Info.FFDiag(E);
3497       return false;
3498     }
3499 
3500     if (RHS.isInt()) {
3501       APSInt LHS =
3502           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3503       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3504         return false;
3505       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3506       return true;
3507     } else if (RHS.isFloat()) {
3508       APFloat FValue(0.0);
3509       return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3510                                   FValue) &&
3511              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3512              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3513                                   Value);
3514     }
3515 
3516     Info.FFDiag(E);
3517     return false;
3518   }
3519   bool found(APFloat &Value, QualType SubobjType) {
3520     return checkConst(SubobjType) &&
3521            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3522                                   Value) &&
3523            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3524            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3525   }
3526   bool foundPointer(APValue &Subobj, QualType SubobjType) {
3527     if (!checkConst(SubobjType))
3528       return false;
3529 
3530     QualType PointeeType;
3531     if (const PointerType *PT = SubobjType->getAs<PointerType>())
3532       PointeeType = PT->getPointeeType();
3533 
3534     if (PointeeType.isNull() || !RHS.isInt() ||
3535         (Opcode != BO_Add && Opcode != BO_Sub)) {
3536       Info.FFDiag(E);
3537       return false;
3538     }
3539 
3540     APSInt Offset = RHS.getInt();
3541     if (Opcode == BO_Sub)
3542       negateAsSigned(Offset);
3543 
3544     LValue LVal;
3545     LVal.setFrom(Info.Ctx, Subobj);
3546     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3547       return false;
3548     LVal.moveInto(Subobj);
3549     return true;
3550   }
3551 };
3552 } // end anonymous namespace
3553 
3554 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3555 
3556 /// Perform a compound assignment of LVal <op>= RVal.
3557 static bool handleCompoundAssignment(
3558     EvalInfo &Info, const Expr *E,
3559     const LValue &LVal, QualType LValType, QualType PromotedLValType,
3560     BinaryOperatorKind Opcode, const APValue &RVal) {
3561   if (LVal.Designator.Invalid)
3562     return false;
3563 
3564   if (!Info.getLangOpts().CPlusPlus14) {
3565     Info.FFDiag(E);
3566     return false;
3567   }
3568 
3569   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3570   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3571                                              RVal };
3572   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3573 }
3574 
3575 namespace {
3576 struct IncDecSubobjectHandler {
3577   EvalInfo &Info;
3578   const UnaryOperator *E;
3579   AccessKinds AccessKind;
3580   APValue *Old;
3581 
3582   typedef bool result_type;
3583 
3584   bool checkConst(QualType QT) {
3585     // Assigning to a const object has undefined behavior.
3586     if (QT.isConstQualified()) {
3587       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3588       return false;
3589     }
3590     return true;
3591   }
3592 
3593   bool failed() { return false; }
3594   bool found(APValue &Subobj, QualType SubobjType) {
3595     // Stash the old value. Also clear Old, so we don't clobber it later
3596     // if we're post-incrementing a complex.
3597     if (Old) {
3598       *Old = Subobj;
3599       Old = nullptr;
3600     }
3601 
3602     switch (Subobj.getKind()) {
3603     case APValue::Int:
3604       return found(Subobj.getInt(), SubobjType);
3605     case APValue::Float:
3606       return found(Subobj.getFloat(), SubobjType);
3607     case APValue::ComplexInt:
3608       return found(Subobj.getComplexIntReal(),
3609                    SubobjType->castAs<ComplexType>()->getElementType()
3610                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3611     case APValue::ComplexFloat:
3612       return found(Subobj.getComplexFloatReal(),
3613                    SubobjType->castAs<ComplexType>()->getElementType()
3614                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3615     case APValue::LValue:
3616       return foundPointer(Subobj, SubobjType);
3617     default:
3618       // FIXME: can this happen?
3619       Info.FFDiag(E);
3620       return false;
3621     }
3622   }
3623   bool found(APSInt &Value, QualType SubobjType) {
3624     if (!checkConst(SubobjType))
3625       return false;
3626 
3627     if (!SubobjType->isIntegerType()) {
3628       // We don't support increment / decrement on integer-cast-to-pointer
3629       // values.
3630       Info.FFDiag(E);
3631       return false;
3632     }
3633 
3634     if (Old) *Old = APValue(Value);
3635 
3636     // bool arithmetic promotes to int, and the conversion back to bool
3637     // doesn't reduce mod 2^n, so special-case it.
3638     if (SubobjType->isBooleanType()) {
3639       if (AccessKind == AK_Increment)
3640         Value = 1;
3641       else
3642         Value = !Value;
3643       return true;
3644     }
3645 
3646     bool WasNegative = Value.isNegative();
3647     if (AccessKind == AK_Increment) {
3648       ++Value;
3649 
3650       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3651         APSInt ActualValue(Value, /*IsUnsigned*/true);
3652         return HandleOverflow(Info, E, ActualValue, SubobjType);
3653       }
3654     } else {
3655       --Value;
3656 
3657       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3658         unsigned BitWidth = Value.getBitWidth();
3659         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3660         ActualValue.setBit(BitWidth);
3661         return HandleOverflow(Info, E, ActualValue, SubobjType);
3662       }
3663     }
3664     return true;
3665   }
3666   bool found(APFloat &Value, QualType SubobjType) {
3667     if (!checkConst(SubobjType))
3668       return false;
3669 
3670     if (Old) *Old = APValue(Value);
3671 
3672     APFloat One(Value.getSemantics(), 1);
3673     if (AccessKind == AK_Increment)
3674       Value.add(One, APFloat::rmNearestTiesToEven);
3675     else
3676       Value.subtract(One, APFloat::rmNearestTiesToEven);
3677     return true;
3678   }
3679   bool foundPointer(APValue &Subobj, QualType SubobjType) {
3680     if (!checkConst(SubobjType))
3681       return false;
3682 
3683     QualType PointeeType;
3684     if (const PointerType *PT = SubobjType->getAs<PointerType>())
3685       PointeeType = PT->getPointeeType();
3686     else {
3687       Info.FFDiag(E);
3688       return false;
3689     }
3690 
3691     LValue LVal;
3692     LVal.setFrom(Info.Ctx, Subobj);
3693     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3694                                      AccessKind == AK_Increment ? 1 : -1))
3695       return false;
3696     LVal.moveInto(Subobj);
3697     return true;
3698   }
3699 };
3700 } // end anonymous namespace
3701 
3702 /// Perform an increment or decrement on LVal.
3703 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3704                          QualType LValType, bool IsIncrement, APValue *Old) {
3705   if (LVal.Designator.Invalid)
3706     return false;
3707 
3708   if (!Info.getLangOpts().CPlusPlus14) {
3709     Info.FFDiag(E);
3710     return false;
3711   }
3712 
3713   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3714   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3715   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3716   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3717 }
3718 
3719 /// Build an lvalue for the object argument of a member function call.
3720 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3721                                    LValue &This) {
3722   if (Object->getType()->isPointerType())
3723     return EvaluatePointer(Object, This, Info);
3724 
3725   if (Object->isGLValue())
3726     return EvaluateLValue(Object, This, Info);
3727 
3728   if (Object->getType()->isLiteralType(Info.Ctx))
3729     return EvaluateTemporary(Object, This, Info);
3730 
3731   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3732   return false;
3733 }
3734 
3735 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3736 /// lvalue referring to the result.
3737 ///
3738 /// \param Info - Information about the ongoing evaluation.
3739 /// \param LV - An lvalue referring to the base of the member pointer.
3740 /// \param RHS - The member pointer expression.
3741 /// \param IncludeMember - Specifies whether the member itself is included in
3742 ///        the resulting LValue subobject designator. This is not possible when
3743 ///        creating a bound member function.
3744 /// \return The field or method declaration to which the member pointer refers,
3745 ///         or 0 if evaluation fails.
3746 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3747                                                   QualType LVType,
3748                                                   LValue &LV,
3749                                                   const Expr *RHS,
3750                                                   bool IncludeMember = true) {
3751   MemberPtr MemPtr;
3752   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3753     return nullptr;
3754 
3755   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3756   // member value, the behavior is undefined.
3757   if (!MemPtr.getDecl()) {
3758     // FIXME: Specific diagnostic.
3759     Info.FFDiag(RHS);
3760     return nullptr;
3761   }
3762 
3763   if (MemPtr.isDerivedMember()) {
3764     // This is a member of some derived class. Truncate LV appropriately.
3765     // The end of the derived-to-base path for the base object must match the
3766     // derived-to-base path for the member pointer.
3767     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3768         LV.Designator.Entries.size()) {
3769       Info.FFDiag(RHS);
3770       return nullptr;
3771     }
3772     unsigned PathLengthToMember =
3773         LV.Designator.Entries.size() - MemPtr.Path.size();
3774     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3775       const CXXRecordDecl *LVDecl = getAsBaseClass(
3776           LV.Designator.Entries[PathLengthToMember + I]);
3777       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3778       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3779         Info.FFDiag(RHS);
3780         return nullptr;
3781       }
3782     }
3783 
3784     // Truncate the lvalue to the appropriate derived class.
3785     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3786                             PathLengthToMember))
3787       return nullptr;
3788   } else if (!MemPtr.Path.empty()) {
3789     // Extend the LValue path with the member pointer's path.
3790     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3791                                   MemPtr.Path.size() + IncludeMember);
3792 
3793     // Walk down to the appropriate base class.
3794     if (const PointerType *PT = LVType->getAs<PointerType>())
3795       LVType = PT->getPointeeType();
3796     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3797     assert(RD && "member pointer access on non-class-type expression");
3798     // The first class in the path is that of the lvalue.
3799     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3800       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3801       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3802         return nullptr;
3803       RD = Base;
3804     }
3805     // Finally cast to the class containing the member.
3806     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3807                                 MemPtr.getContainingRecord()))
3808       return nullptr;
3809   }
3810 
3811   // Add the member. Note that we cannot build bound member functions here.
3812   if (IncludeMember) {
3813     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3814       if (!HandleLValueMember(Info, RHS, LV, FD))
3815         return nullptr;
3816     } else if (const IndirectFieldDecl *IFD =
3817                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3818       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3819         return nullptr;
3820     } else {
3821       llvm_unreachable("can't construct reference to bound member function");
3822     }
3823   }
3824 
3825   return MemPtr.getDecl();
3826 }
3827 
3828 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3829                                                   const BinaryOperator *BO,
3830                                                   LValue &LV,
3831                                                   bool IncludeMember = true) {
3832   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3833 
3834   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3835     if (Info.noteFailure()) {
3836       MemberPtr MemPtr;
3837       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3838     }
3839     return nullptr;
3840   }
3841 
3842   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3843                                    BO->getRHS(), IncludeMember);
3844 }
3845 
3846 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3847 /// the provided lvalue, which currently refers to the base object.
3848 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3849                                     LValue &Result) {
3850   SubobjectDesignator &D = Result.Designator;
3851   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3852     return false;
3853 
3854   QualType TargetQT = E->getType();
3855   if (const PointerType *PT = TargetQT->getAs<PointerType>())
3856     TargetQT = PT->getPointeeType();
3857 
3858   // Check this cast lands within the final derived-to-base subobject path.
3859   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3860     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3861       << D.MostDerivedType << TargetQT;
3862     return false;
3863   }
3864 
3865   // Check the type of the final cast. We don't need to check the path,
3866   // since a cast can only be formed if the path is unique.
3867   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3868   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3869   const CXXRecordDecl *FinalType;
3870   if (NewEntriesSize == D.MostDerivedPathLength)
3871     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3872   else
3873     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3874   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3875     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3876       << D.MostDerivedType << TargetQT;
3877     return false;
3878   }
3879 
3880   // Truncate the lvalue to the appropriate derived class.
3881   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3882 }
3883 
3884 /// Get the value to use for a default-initialized object of type T.
3885 static APValue getDefaultInitValue(QualType T) {
3886   if (auto *RD = T->getAsCXXRecordDecl()) {
3887     if (RD->isUnion())
3888       return APValue((const FieldDecl*)nullptr);
3889 
3890     APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
3891                    std::distance(RD->field_begin(), RD->field_end()));
3892 
3893     unsigned Index = 0;
3894     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
3895            End = RD->bases_end(); I != End; ++I, ++Index)
3896       Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
3897 
3898     for (const auto *I : RD->fields()) {
3899       if (I->isUnnamedBitfield())
3900         continue;
3901       Struct.getStructField(I->getFieldIndex()) =
3902           getDefaultInitValue(I->getType());
3903     }
3904     return Struct;
3905   }
3906 
3907   if (auto *AT =
3908           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
3909     APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
3910     if (Array.hasArrayFiller())
3911       Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
3912     return Array;
3913   }
3914 
3915   return APValue::IndeterminateValue();
3916 }
3917 
3918 namespace {
3919 enum EvalStmtResult {
3920   /// Evaluation failed.
3921   ESR_Failed,
3922   /// Hit a 'return' statement.
3923   ESR_Returned,
3924   /// Evaluation succeeded.
3925   ESR_Succeeded,
3926   /// Hit a 'continue' statement.
3927   ESR_Continue,
3928   /// Hit a 'break' statement.
3929   ESR_Break,
3930   /// Still scanning for 'case' or 'default' statement.
3931   ESR_CaseNotFound
3932 };
3933 }
3934 
3935 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3936   // We don't need to evaluate the initializer for a static local.
3937   if (!VD->hasLocalStorage())
3938     return true;
3939 
3940   LValue Result;
3941   APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
3942 
3943   const Expr *InitE = VD->getInit();
3944   if (!InitE) {
3945     Val = getDefaultInitValue(VD->getType());
3946     return true;
3947   }
3948 
3949   if (InitE->isValueDependent())
3950     return false;
3951 
3952   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3953     // Wipe out any partially-computed value, to allow tracking that this
3954     // evaluation failed.
3955     Val = APValue();
3956     return false;
3957   }
3958 
3959   return true;
3960 }
3961 
3962 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3963   bool OK = true;
3964 
3965   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3966     OK &= EvaluateVarDecl(Info, VD);
3967 
3968   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3969     for (auto *BD : DD->bindings())
3970       if (auto *VD = BD->getHoldingVar())
3971         OK &= EvaluateDecl(Info, VD);
3972 
3973   return OK;
3974 }
3975 
3976 
3977 /// Evaluate a condition (either a variable declaration or an expression).
3978 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3979                          const Expr *Cond, bool &Result) {
3980   FullExpressionRAII Scope(Info);
3981   if (CondDecl && !EvaluateDecl(Info, CondDecl))
3982     return false;
3983   return EvaluateAsBooleanCondition(Cond, Result, Info);
3984 }
3985 
3986 namespace {
3987 /// A location where the result (returned value) of evaluating a
3988 /// statement should be stored.
3989 struct StmtResult {
3990   /// The APValue that should be filled in with the returned value.
3991   APValue &Value;
3992   /// The location containing the result, if any (used to support RVO).
3993   const LValue *Slot;
3994 };
3995 
3996 struct TempVersionRAII {
3997   CallStackFrame &Frame;
3998 
3999   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4000     Frame.pushTempVersion();
4001   }
4002 
4003   ~TempVersionRAII() {
4004     Frame.popTempVersion();
4005   }
4006 };
4007 
4008 }
4009 
4010 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4011                                    const Stmt *S,
4012                                    const SwitchCase *SC = nullptr);
4013 
4014 /// Evaluate the body of a loop, and translate the result as appropriate.
4015 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4016                                        const Stmt *Body,
4017                                        const SwitchCase *Case = nullptr) {
4018   BlockScopeRAII Scope(Info);
4019   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
4020   case ESR_Break:
4021     return ESR_Succeeded;
4022   case ESR_Succeeded:
4023   case ESR_Continue:
4024     return ESR_Continue;
4025   case ESR_Failed:
4026   case ESR_Returned:
4027   case ESR_CaseNotFound:
4028     return ESR;
4029   }
4030   llvm_unreachable("Invalid EvalStmtResult!");
4031 }
4032 
4033 /// Evaluate a switch statement.
4034 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4035                                      const SwitchStmt *SS) {
4036   BlockScopeRAII Scope(Info);
4037 
4038   // Evaluate the switch condition.
4039   APSInt Value;
4040   {
4041     FullExpressionRAII Scope(Info);
4042     if (const Stmt *Init = SS->getInit()) {
4043       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4044       if (ESR != ESR_Succeeded)
4045         return ESR;
4046     }
4047     if (SS->getConditionVariable() &&
4048         !EvaluateDecl(Info, SS->getConditionVariable()))
4049       return ESR_Failed;
4050     if (!EvaluateInteger(SS->getCond(), Value, Info))
4051       return ESR_Failed;
4052   }
4053 
4054   // Find the switch case corresponding to the value of the condition.
4055   // FIXME: Cache this lookup.
4056   const SwitchCase *Found = nullptr;
4057   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4058        SC = SC->getNextSwitchCase()) {
4059     if (isa<DefaultStmt>(SC)) {
4060       Found = SC;
4061       continue;
4062     }
4063 
4064     const CaseStmt *CS = cast<CaseStmt>(SC);
4065     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4066     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4067                               : LHS;
4068     if (LHS <= Value && Value <= RHS) {
4069       Found = SC;
4070       break;
4071     }
4072   }
4073 
4074   if (!Found)
4075     return ESR_Succeeded;
4076 
4077   // Search the switch body for the switch case and evaluate it from there.
4078   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
4079   case ESR_Break:
4080     return ESR_Succeeded;
4081   case ESR_Succeeded:
4082   case ESR_Continue:
4083   case ESR_Failed:
4084   case ESR_Returned:
4085     return ESR;
4086   case ESR_CaseNotFound:
4087     // This can only happen if the switch case is nested within a statement
4088     // expression. We have no intention of supporting that.
4089     Info.FFDiag(Found->getBeginLoc(),
4090                 diag::note_constexpr_stmt_expr_unsupported);
4091     return ESR_Failed;
4092   }
4093   llvm_unreachable("Invalid EvalStmtResult!");
4094 }
4095 
4096 // Evaluate a statement.
4097 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4098                                    const Stmt *S, const SwitchCase *Case) {
4099   if (!Info.nextStep(S))
4100     return ESR_Failed;
4101 
4102   // If we're hunting down a 'case' or 'default' label, recurse through
4103   // substatements until we hit the label.
4104   if (Case) {
4105     // FIXME: We don't start the lifetime of objects whose initialization we
4106     // jump over. However, such objects must be of class type with a trivial
4107     // default constructor that initialize all subobjects, so must be empty,
4108     // so this almost never matters.
4109     switch (S->getStmtClass()) {
4110     case Stmt::CompoundStmtClass:
4111       // FIXME: Precompute which substatement of a compound statement we
4112       // would jump to, and go straight there rather than performing a
4113       // linear scan each time.
4114     case Stmt::LabelStmtClass:
4115     case Stmt::AttributedStmtClass:
4116     case Stmt::DoStmtClass:
4117       break;
4118 
4119     case Stmt::CaseStmtClass:
4120     case Stmt::DefaultStmtClass:
4121       if (Case == S)
4122         Case = nullptr;
4123       break;
4124 
4125     case Stmt::IfStmtClass: {
4126       // FIXME: Precompute which side of an 'if' we would jump to, and go
4127       // straight there rather than scanning both sides.
4128       const IfStmt *IS = cast<IfStmt>(S);
4129 
4130       // Wrap the evaluation in a block scope, in case it's a DeclStmt
4131       // preceded by our switch label.
4132       BlockScopeRAII Scope(Info);
4133 
4134       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4135       if (ESR != ESR_CaseNotFound || !IS->getElse())
4136         return ESR;
4137       return EvaluateStmt(Result, Info, IS->getElse(), Case);
4138     }
4139 
4140     case Stmt::WhileStmtClass: {
4141       EvalStmtResult ESR =
4142           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4143       if (ESR != ESR_Continue)
4144         return ESR;
4145       break;
4146     }
4147 
4148     case Stmt::ForStmtClass: {
4149       const ForStmt *FS = cast<ForStmt>(S);
4150       EvalStmtResult ESR =
4151           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4152       if (ESR != ESR_Continue)
4153         return ESR;
4154       if (FS->getInc()) {
4155         FullExpressionRAII IncScope(Info);
4156         if (!EvaluateIgnoredValue(Info, FS->getInc()))
4157           return ESR_Failed;
4158       }
4159       break;
4160     }
4161 
4162     case Stmt::DeclStmtClass: {
4163       // Start the lifetime of any uninitialized variables we encounter. They
4164       // might be used by the selected branch of the switch.
4165       const DeclStmt *DS = cast<DeclStmt>(S);
4166       for (const auto *D : DS->decls()) {
4167         if (const auto *VD = dyn_cast<VarDecl>(D)) {
4168           if (VD->hasLocalStorage() && !VD->getInit())
4169             if (!EvaluateVarDecl(Info, VD))
4170               return ESR_Failed;
4171           // FIXME: If the variable has initialization that can't be jumped
4172           // over, bail out of any immediately-surrounding compound-statement
4173           // too. There can't be any case labels here.
4174         }
4175       }
4176       return ESR_CaseNotFound;
4177     }
4178 
4179     default:
4180       return ESR_CaseNotFound;
4181     }
4182   }
4183 
4184   switch (S->getStmtClass()) {
4185   default:
4186     if (const Expr *E = dyn_cast<Expr>(S)) {
4187       // Don't bother evaluating beyond an expression-statement which couldn't
4188       // be evaluated.
4189       FullExpressionRAII Scope(Info);
4190       if (!EvaluateIgnoredValue(Info, E))
4191         return ESR_Failed;
4192       return ESR_Succeeded;
4193     }
4194 
4195     Info.FFDiag(S->getBeginLoc());
4196     return ESR_Failed;
4197 
4198   case Stmt::NullStmtClass:
4199     return ESR_Succeeded;
4200 
4201   case Stmt::DeclStmtClass: {
4202     const DeclStmt *DS = cast<DeclStmt>(S);
4203     for (const auto *D : DS->decls()) {
4204       // Each declaration initialization is its own full-expression.
4205       FullExpressionRAII Scope(Info);
4206       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
4207         return ESR_Failed;
4208     }
4209     return ESR_Succeeded;
4210   }
4211 
4212   case Stmt::ReturnStmtClass: {
4213     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
4214     FullExpressionRAII Scope(Info);
4215     if (RetExpr &&
4216         !(Result.Slot
4217               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4218               : Evaluate(Result.Value, Info, RetExpr)))
4219       return ESR_Failed;
4220     return ESR_Returned;
4221   }
4222 
4223   case Stmt::CompoundStmtClass: {
4224     BlockScopeRAII Scope(Info);
4225 
4226     const CompoundStmt *CS = cast<CompoundStmt>(S);
4227     for (const auto *BI : CS->body()) {
4228       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
4229       if (ESR == ESR_Succeeded)
4230         Case = nullptr;
4231       else if (ESR != ESR_CaseNotFound)
4232         return ESR;
4233     }
4234     return Case ? ESR_CaseNotFound : ESR_Succeeded;
4235   }
4236 
4237   case Stmt::IfStmtClass: {
4238     const IfStmt *IS = cast<IfStmt>(S);
4239 
4240     // Evaluate the condition, as either a var decl or as an expression.
4241     BlockScopeRAII Scope(Info);
4242     if (const Stmt *Init = IS->getInit()) {
4243       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4244       if (ESR != ESR_Succeeded)
4245         return ESR;
4246     }
4247     bool Cond;
4248     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4249       return ESR_Failed;
4250 
4251     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4252       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4253       if (ESR != ESR_Succeeded)
4254         return ESR;
4255     }
4256     return ESR_Succeeded;
4257   }
4258 
4259   case Stmt::WhileStmtClass: {
4260     const WhileStmt *WS = cast<WhileStmt>(S);
4261     while (true) {
4262       BlockScopeRAII Scope(Info);
4263       bool Continue;
4264       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4265                         Continue))
4266         return ESR_Failed;
4267       if (!Continue)
4268         break;
4269 
4270       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4271       if (ESR != ESR_Continue)
4272         return ESR;
4273     }
4274     return ESR_Succeeded;
4275   }
4276 
4277   case Stmt::DoStmtClass: {
4278     const DoStmt *DS = cast<DoStmt>(S);
4279     bool Continue;
4280     do {
4281       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4282       if (ESR != ESR_Continue)
4283         return ESR;
4284       Case = nullptr;
4285 
4286       FullExpressionRAII CondScope(Info);
4287       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4288         return ESR_Failed;
4289     } while (Continue);
4290     return ESR_Succeeded;
4291   }
4292 
4293   case Stmt::ForStmtClass: {
4294     const ForStmt *FS = cast<ForStmt>(S);
4295     BlockScopeRAII Scope(Info);
4296     if (FS->getInit()) {
4297       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4298       if (ESR != ESR_Succeeded)
4299         return ESR;
4300     }
4301     while (true) {
4302       BlockScopeRAII Scope(Info);
4303       bool Continue = true;
4304       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4305                                          FS->getCond(), Continue))
4306         return ESR_Failed;
4307       if (!Continue)
4308         break;
4309 
4310       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4311       if (ESR != ESR_Continue)
4312         return ESR;
4313 
4314       if (FS->getInc()) {
4315         FullExpressionRAII IncScope(Info);
4316         if (!EvaluateIgnoredValue(Info, FS->getInc()))
4317           return ESR_Failed;
4318       }
4319     }
4320     return ESR_Succeeded;
4321   }
4322 
4323   case Stmt::CXXForRangeStmtClass: {
4324     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4325     BlockScopeRAII Scope(Info);
4326 
4327     // Evaluate the init-statement if present.
4328     if (FS->getInit()) {
4329       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4330       if (ESR != ESR_Succeeded)
4331         return ESR;
4332     }
4333 
4334     // Initialize the __range variable.
4335     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4336     if (ESR != ESR_Succeeded)
4337       return ESR;
4338 
4339     // Create the __begin and __end iterators.
4340     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4341     if (ESR != ESR_Succeeded)
4342       return ESR;
4343     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4344     if (ESR != ESR_Succeeded)
4345       return ESR;
4346 
4347     while (true) {
4348       // Condition: __begin != __end.
4349       {
4350         bool Continue = true;
4351         FullExpressionRAII CondExpr(Info);
4352         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4353           return ESR_Failed;
4354         if (!Continue)
4355           break;
4356       }
4357 
4358       // User's variable declaration, initialized by *__begin.
4359       BlockScopeRAII InnerScope(Info);
4360       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4361       if (ESR != ESR_Succeeded)
4362         return ESR;
4363 
4364       // Loop body.
4365       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4366       if (ESR != ESR_Continue)
4367         return ESR;
4368 
4369       // Increment: ++__begin
4370       if (!EvaluateIgnoredValue(Info, FS->getInc()))
4371         return ESR_Failed;
4372     }
4373 
4374     return ESR_Succeeded;
4375   }
4376 
4377   case Stmt::SwitchStmtClass:
4378     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4379 
4380   case Stmt::ContinueStmtClass:
4381     return ESR_Continue;
4382 
4383   case Stmt::BreakStmtClass:
4384     return ESR_Break;
4385 
4386   case Stmt::LabelStmtClass:
4387     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4388 
4389   case Stmt::AttributedStmtClass:
4390     // As a general principle, C++11 attributes can be ignored without
4391     // any semantic impact.
4392     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4393                         Case);
4394 
4395   case Stmt::CaseStmtClass:
4396   case Stmt::DefaultStmtClass:
4397     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4398   case Stmt::CXXTryStmtClass:
4399     // Evaluate try blocks by evaluating all sub statements.
4400     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
4401   }
4402 }
4403 
4404 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4405 /// default constructor. If so, we'll fold it whether or not it's marked as
4406 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4407 /// so we need special handling.
4408 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4409                                            const CXXConstructorDecl *CD,
4410                                            bool IsValueInitialization) {
4411   if (!CD->isTrivial() || !CD->isDefaultConstructor())
4412     return false;
4413 
4414   // Value-initialization does not call a trivial default constructor, so such a
4415   // call is a core constant expression whether or not the constructor is
4416   // constexpr.
4417   if (!CD->isConstexpr() && !IsValueInitialization) {
4418     if (Info.getLangOpts().CPlusPlus11) {
4419       // FIXME: If DiagDecl is an implicitly-declared special member function,
4420       // we should be much more explicit about why it's not constexpr.
4421       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4422         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4423       Info.Note(CD->getLocation(), diag::note_declared_at);
4424     } else {
4425       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4426     }
4427   }
4428   return true;
4429 }
4430 
4431 /// CheckConstexprFunction - Check that a function can be called in a constant
4432 /// expression.
4433 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4434                                    const FunctionDecl *Declaration,
4435                                    const FunctionDecl *Definition,
4436                                    const Stmt *Body) {
4437   // Potential constant expressions can contain calls to declared, but not yet
4438   // defined, constexpr functions.
4439   if (Info.checkingPotentialConstantExpression() && !Definition &&
4440       Declaration->isConstexpr())
4441     return false;
4442 
4443   // Bail out if the function declaration itself is invalid.  We will
4444   // have produced a relevant diagnostic while parsing it, so just
4445   // note the problematic sub-expression.
4446   if (Declaration->isInvalidDecl()) {
4447     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4448     return false;
4449   }
4450 
4451   // DR1872: An instantiated virtual constexpr function can't be called in a
4452   // constant expression (prior to C++20). We can still constant-fold such a
4453   // call.
4454   if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
4455       cast<CXXMethodDecl>(Declaration)->isVirtual())
4456     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
4457 
4458   if (Definition && Definition->isInvalidDecl()) {
4459     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4460     return false;
4461   }
4462 
4463   // Can we evaluate this function call?
4464   if (Definition && Definition->isConstexpr() && Body)
4465     return true;
4466 
4467   if (Info.getLangOpts().CPlusPlus11) {
4468     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4469 
4470     // If this function is not constexpr because it is an inherited
4471     // non-constexpr constructor, diagnose that directly.
4472     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4473     if (CD && CD->isInheritingConstructor()) {
4474       auto *Inherited = CD->getInheritedConstructor().getConstructor();
4475       if (!Inherited->isConstexpr())
4476         DiagDecl = CD = Inherited;
4477     }
4478 
4479     // FIXME: If DiagDecl is an implicitly-declared special member function
4480     // or an inheriting constructor, we should be much more explicit about why
4481     // it's not constexpr.
4482     if (CD && CD->isInheritingConstructor())
4483       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4484         << CD->getInheritedConstructor().getConstructor()->getParent();
4485     else
4486       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4487         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4488     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4489   } else {
4490     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4491   }
4492   return false;
4493 }
4494 
4495 namespace {
4496 struct CheckDynamicTypeHandler {
4497   AccessKinds AccessKind;
4498   typedef bool result_type;
4499   bool failed() { return false; }
4500   bool found(APValue &Subobj, QualType SubobjType) { return true; }
4501   bool found(APSInt &Value, QualType SubobjType) { return true; }
4502   bool found(APFloat &Value, QualType SubobjType) { return true; }
4503 };
4504 } // end anonymous namespace
4505 
4506 /// Check that we can access the notional vptr of an object / determine its
4507 /// dynamic type.
4508 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
4509                              AccessKinds AK, bool Polymorphic) {
4510   if (This.Designator.Invalid)
4511     return false;
4512 
4513   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
4514 
4515   if (!Obj)
4516     return false;
4517 
4518   if (!Obj.Value) {
4519     // The object is not usable in constant expressions, so we can't inspect
4520     // its value to see if it's in-lifetime or what the active union members
4521     // are. We can still check for a one-past-the-end lvalue.
4522     if (This.Designator.isOnePastTheEnd() ||
4523         This.Designator.isMostDerivedAnUnsizedArray()) {
4524       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
4525                          ? diag::note_constexpr_access_past_end
4526                          : diag::note_constexpr_access_unsized_array)
4527           << AK;
4528       return false;
4529     } else if (Polymorphic) {
4530       // Conservatively refuse to perform a polymorphic operation if we would
4531       // not be able to read a notional 'vptr' value.
4532       APValue Val;
4533       This.moveInto(Val);
4534       QualType StarThisType =
4535           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
4536       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
4537           << AK << Val.getAsString(Info.Ctx, StarThisType);
4538       return false;
4539     }
4540     return true;
4541   }
4542 
4543   CheckDynamicTypeHandler Handler{AK};
4544   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
4545 }
4546 
4547 /// Check that the pointee of the 'this' pointer in a member function call is
4548 /// either within its lifetime or in its period of construction or destruction.
4549 static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
4550                                                  const LValue &This) {
4551   return checkDynamicType(Info, E, This, AK_MemberCall, false);
4552 }
4553 
4554 struct DynamicType {
4555   /// The dynamic class type of the object.
4556   const CXXRecordDecl *Type;
4557   /// The corresponding path length in the lvalue.
4558   unsigned PathLength;
4559 };
4560 
4561 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
4562                                              unsigned PathLength) {
4563   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
4564       Designator.Entries.size() && "invalid path length");
4565   return (PathLength == Designator.MostDerivedPathLength)
4566              ? Designator.MostDerivedType->getAsCXXRecordDecl()
4567              : getAsBaseClass(Designator.Entries[PathLength - 1]);
4568 }
4569 
4570 /// Determine the dynamic type of an object.
4571 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
4572                                                 LValue &This, AccessKinds AK) {
4573   // If we don't have an lvalue denoting an object of class type, there is no
4574   // meaningful dynamic type. (We consider objects of non-class type to have no
4575   // dynamic type.)
4576   if (!checkDynamicType(Info, E, This, AK, true))
4577     return None;
4578 
4579   // Refuse to compute a dynamic type in the presence of virtual bases. This
4580   // shouldn't happen other than in constant-folding situations, since literal
4581   // types can't have virtual bases.
4582   //
4583   // Note that consumers of DynamicType assume that the type has no virtual
4584   // bases, and will need modifications if this restriction is relaxed.
4585   const CXXRecordDecl *Class =
4586       This.Designator.MostDerivedType->getAsCXXRecordDecl();
4587   if (!Class || Class->getNumVBases()) {
4588     Info.FFDiag(E);
4589     return None;
4590   }
4591 
4592   // FIXME: For very deep class hierarchies, it might be beneficial to use a
4593   // binary search here instead. But the overwhelmingly common case is that
4594   // we're not in the middle of a constructor, so it probably doesn't matter
4595   // in practice.
4596   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
4597   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
4598        PathLength <= Path.size(); ++PathLength) {
4599     switch (Info.isEvaluatingConstructor(This.getLValueBase(),
4600                                          Path.slice(0, PathLength))) {
4601     case ConstructionPhase::Bases:
4602       // We're constructing a base class. This is not the dynamic type.
4603       break;
4604 
4605     case ConstructionPhase::None:
4606     case ConstructionPhase::AfterBases:
4607       // We've finished constructing the base classes, so this is the dynamic
4608       // type.
4609       return DynamicType{getBaseClassType(This.Designator, PathLength),
4610                          PathLength};
4611     }
4612   }
4613 
4614   // CWG issue 1517: we're constructing a base class of the object described by
4615   // 'This', so that object has not yet begun its period of construction and
4616   // any polymorphic operation on it results in undefined behavior.
4617   Info.FFDiag(E);
4618   return None;
4619 }
4620 
4621 /// Perform virtual dispatch.
4622 static const CXXMethodDecl *HandleVirtualDispatch(
4623     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
4624     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
4625   Optional<DynamicType> DynType =
4626       ComputeDynamicType(Info, E, This, AK_MemberCall);
4627   if (!DynType)
4628     return nullptr;
4629 
4630   // Find the final overrider. It must be declared in one of the classes on the
4631   // path from the dynamic type to the static type.
4632   // FIXME: If we ever allow literal types to have virtual base classes, that
4633   // won't be true.
4634   const CXXMethodDecl *Callee = Found;
4635   unsigned PathLength = DynType->PathLength;
4636   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
4637     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
4638     const CXXMethodDecl *Overrider =
4639         Found->getCorrespondingMethodDeclaredInClass(Class, false);
4640     if (Overrider) {
4641       Callee = Overrider;
4642       break;
4643     }
4644   }
4645 
4646   // C++2a [class.abstract]p6:
4647   //   the effect of making a virtual call to a pure virtual function [...] is
4648   //   undefined
4649   if (Callee->isPure()) {
4650     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
4651     Info.Note(Callee->getLocation(), diag::note_declared_at);
4652     return nullptr;
4653   }
4654 
4655   // If necessary, walk the rest of the path to determine the sequence of
4656   // covariant adjustment steps to apply.
4657   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
4658                                        Found->getReturnType())) {
4659     CovariantAdjustmentPath.push_back(Callee->getReturnType());
4660     for (unsigned CovariantPathLength = PathLength + 1;
4661          CovariantPathLength != This.Designator.Entries.size();
4662          ++CovariantPathLength) {
4663       const CXXRecordDecl *NextClass =
4664           getBaseClassType(This.Designator, CovariantPathLength);
4665       const CXXMethodDecl *Next =
4666           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
4667       if (Next && !Info.Ctx.hasSameUnqualifiedType(
4668                       Next->getReturnType(), CovariantAdjustmentPath.back()))
4669         CovariantAdjustmentPath.push_back(Next->getReturnType());
4670     }
4671     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
4672                                          CovariantAdjustmentPath.back()))
4673       CovariantAdjustmentPath.push_back(Found->getReturnType());
4674   }
4675 
4676   // Perform 'this' adjustment.
4677   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
4678     return nullptr;
4679 
4680   return Callee;
4681 }
4682 
4683 /// Perform the adjustment from a value returned by a virtual function to
4684 /// a value of the statically expected type, which may be a pointer or
4685 /// reference to a base class of the returned type.
4686 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
4687                                             APValue &Result,
4688                                             ArrayRef<QualType> Path) {
4689   assert(Result.isLValue() &&
4690          "unexpected kind of APValue for covariant return");
4691   if (Result.isNullPointer())
4692     return true;
4693 
4694   LValue LVal;
4695   LVal.setFrom(Info.Ctx, Result);
4696 
4697   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
4698   for (unsigned I = 1; I != Path.size(); ++I) {
4699     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
4700     assert(OldClass && NewClass && "unexpected kind of covariant return");
4701     if (OldClass != NewClass &&
4702         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
4703       return false;
4704     OldClass = NewClass;
4705   }
4706 
4707   LVal.moveInto(Result);
4708   return true;
4709 }
4710 
4711 /// Determine whether \p Base, which is known to be a direct base class of
4712 /// \p Derived, is a public base class.
4713 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
4714                               const CXXRecordDecl *Base) {
4715   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
4716     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
4717     if (BaseClass && declaresSameEntity(BaseClass, Base))
4718       return BaseSpec.getAccessSpecifier() == AS_public;
4719   }
4720   llvm_unreachable("Base is not a direct base of Derived");
4721 }
4722 
4723 /// Apply the given dynamic cast operation on the provided lvalue.
4724 ///
4725 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
4726 /// to find a suitable target subobject.
4727 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
4728                               LValue &Ptr) {
4729   // We can't do anything with a non-symbolic pointer value.
4730   SubobjectDesignator &D = Ptr.Designator;
4731   if (D.Invalid)
4732     return false;
4733 
4734   // C++ [expr.dynamic.cast]p6:
4735   //   If v is a null pointer value, the result is a null pointer value.
4736   if (Ptr.isNullPointer() && !E->isGLValue())
4737     return true;
4738 
4739   // For all the other cases, we need the pointer to point to an object within
4740   // its lifetime / period of construction / destruction, and we need to know
4741   // its dynamic type.
4742   Optional<DynamicType> DynType =
4743       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
4744   if (!DynType)
4745     return false;
4746 
4747   // C++ [expr.dynamic.cast]p7:
4748   //   If T is "pointer to cv void", then the result is a pointer to the most
4749   //   derived object
4750   if (E->getType()->isVoidPointerType())
4751     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
4752 
4753   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
4754   assert(C && "dynamic_cast target is not void pointer nor class");
4755   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
4756 
4757   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
4758     // C++ [expr.dynamic.cast]p9:
4759     if (!E->isGLValue()) {
4760       //   The value of a failed cast to pointer type is the null pointer value
4761       //   of the required result type.
4762       auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
4763       Ptr.setNull(E->getType(), TargetVal);
4764       return true;
4765     }
4766 
4767     //   A failed cast to reference type throws [...] std::bad_cast.
4768     unsigned DiagKind;
4769     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
4770                    DynType->Type->isDerivedFrom(C)))
4771       DiagKind = 0;
4772     else if (!Paths || Paths->begin() == Paths->end())
4773       DiagKind = 1;
4774     else if (Paths->isAmbiguous(CQT))
4775       DiagKind = 2;
4776     else {
4777       assert(Paths->front().Access != AS_public && "why did the cast fail?");
4778       DiagKind = 3;
4779     }
4780     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
4781         << DiagKind << Ptr.Designator.getType(Info.Ctx)
4782         << Info.Ctx.getRecordType(DynType->Type)
4783         << E->getType().getUnqualifiedType();
4784     return false;
4785   };
4786 
4787   // Runtime check, phase 1:
4788   //   Walk from the base subobject towards the derived object looking for the
4789   //   target type.
4790   for (int PathLength = Ptr.Designator.Entries.size();
4791        PathLength >= (int)DynType->PathLength; --PathLength) {
4792     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
4793     if (declaresSameEntity(Class, C))
4794       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
4795     // We can only walk across public inheritance edges.
4796     if (PathLength > (int)DynType->PathLength &&
4797         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
4798                            Class))
4799       return RuntimeCheckFailed(nullptr);
4800   }
4801 
4802   // Runtime check, phase 2:
4803   //   Search the dynamic type for an unambiguous public base of type C.
4804   CXXBasePaths Paths(/*FindAmbiguities=*/true,
4805                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
4806   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
4807       Paths.front().Access == AS_public) {
4808     // Downcast to the dynamic type...
4809     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
4810       return false;
4811     // ... then upcast to the chosen base class subobject.
4812     for (CXXBasePathElement &Elem : Paths.front())
4813       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
4814         return false;
4815     return true;
4816   }
4817 
4818   // Otherwise, the runtime check fails.
4819   return RuntimeCheckFailed(&Paths);
4820 }
4821 
4822 namespace {
4823 struct StartLifetimeOfUnionMemberHandler {
4824   const FieldDecl *Field;
4825 
4826   static const AccessKinds AccessKind = AK_Assign;
4827 
4828   typedef bool result_type;
4829   bool failed() { return false; }
4830   bool found(APValue &Subobj, QualType SubobjType) {
4831     // We are supposed to perform no initialization but begin the lifetime of
4832     // the object. We interpret that as meaning to do what default
4833     // initialization of the object would do if all constructors involved were
4834     // trivial:
4835     //  * All base, non-variant member, and array element subobjects' lifetimes
4836     //    begin
4837     //  * No variant members' lifetimes begin
4838     //  * All scalar subobjects whose lifetimes begin have indeterminate values
4839     assert(SubobjType->isUnionType());
4840     if (!declaresSameEntity(Subobj.getUnionField(), Field))
4841       Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
4842     return true;
4843   }
4844   bool found(APSInt &Value, QualType SubobjType) {
4845     llvm_unreachable("wrong value kind for union object");
4846   }
4847   bool found(APFloat &Value, QualType SubobjType) {
4848     llvm_unreachable("wrong value kind for union object");
4849   }
4850 };
4851 } // end anonymous namespace
4852 
4853 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
4854 
4855 /// Handle a builtin simple-assignment or a call to a trivial assignment
4856 /// operator whose left-hand side might involve a union member access. If it
4857 /// does, implicitly start the lifetime of any accessed union elements per
4858 /// C++20 [class.union]5.
4859 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
4860                                           const LValue &LHS) {
4861   if (LHS.InvalidBase || LHS.Designator.Invalid)
4862     return false;
4863 
4864   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
4865   // C++ [class.union]p5:
4866   //   define the set S(E) of subexpressions of E as follows:
4867   unsigned PathLength = LHS.Designator.Entries.size();
4868   for (const Expr *E = LHSExpr; E != nullptr;) {
4869     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
4870     if (auto *ME = dyn_cast<MemberExpr>(E)) {
4871       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
4872       if (!FD)
4873         break;
4874 
4875       //    ... and also contains A.B if B names a union member
4876       if (FD->getParent()->isUnion())
4877         UnionPathLengths.push_back({PathLength - 1, FD});
4878 
4879       E = ME->getBase();
4880       --PathLength;
4881       assert(declaresSameEntity(FD,
4882                                 LHS.Designator.Entries[PathLength]
4883                                     .getAsBaseOrMember().getPointer()));
4884 
4885       //   -- If E is of the form A[B] and is interpreted as a built-in array
4886       //      subscripting operator, S(E) is [S(the array operand, if any)].
4887     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
4888       // Step over an ArrayToPointerDecay implicit cast.
4889       auto *Base = ASE->getBase()->IgnoreImplicit();
4890       if (!Base->getType()->isArrayType())
4891         break;
4892 
4893       E = Base;
4894       --PathLength;
4895 
4896     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4897       // Step over a derived-to-base conversion.
4898       E = ICE->getSubExpr();
4899       if (ICE->getCastKind() == CK_NoOp)
4900         continue;
4901       if (ICE->getCastKind() != CK_DerivedToBase &&
4902           ICE->getCastKind() != CK_UncheckedDerivedToBase)
4903         break;
4904       // Walk path backwards as we walk up from the base to the derived class.
4905       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
4906         --PathLength;
4907         (void)Elt;
4908         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
4909                                   LHS.Designator.Entries[PathLength]
4910                                       .getAsBaseOrMember().getPointer()));
4911       }
4912 
4913     //   -- Otherwise, S(E) is empty.
4914     } else {
4915       break;
4916     }
4917   }
4918 
4919   // Common case: no unions' lifetimes are started.
4920   if (UnionPathLengths.empty())
4921     return true;
4922 
4923   //   if modification of X [would access an inactive union member], an object
4924   //   of the type of X is implicitly created
4925   CompleteObject Obj =
4926       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
4927   if (!Obj)
4928     return false;
4929   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
4930            llvm::reverse(UnionPathLengths)) {
4931     // Form a designator for the union object.
4932     SubobjectDesignator D = LHS.Designator;
4933     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
4934 
4935     StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
4936     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
4937       return false;
4938   }
4939 
4940   return true;
4941 }
4942 
4943 /// Determine if a class has any fields that might need to be copied by a
4944 /// trivial copy or move operation.
4945 static bool hasFields(const CXXRecordDecl *RD) {
4946   if (!RD || RD->isEmpty())
4947     return false;
4948   for (auto *FD : RD->fields()) {
4949     if (FD->isUnnamedBitfield())
4950       continue;
4951     return true;
4952   }
4953   for (auto &Base : RD->bases())
4954     if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4955       return true;
4956   return false;
4957 }
4958 
4959 namespace {
4960 typedef SmallVector<APValue, 8> ArgVector;
4961 }
4962 
4963 /// EvaluateArgs - Evaluate the arguments to a function call.
4964 static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
4965                          EvalInfo &Info, const FunctionDecl *Callee) {
4966   bool Success = true;
4967   llvm::SmallBitVector ForbiddenNullArgs;
4968   if (Callee->hasAttr<NonNullAttr>()) {
4969     ForbiddenNullArgs.resize(Args.size());
4970     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
4971       if (!Attr->args_size()) {
4972         ForbiddenNullArgs.set();
4973         break;
4974       } else
4975         for (auto Idx : Attr->args()) {
4976           unsigned ASTIdx = Idx.getASTIndex();
4977           if (ASTIdx >= Args.size())
4978             continue;
4979           ForbiddenNullArgs[ASTIdx] = 1;
4980         }
4981     }
4982   }
4983   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
4984        I != E; ++I) {
4985     if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4986       // If we're checking for a potential constant expression, evaluate all
4987       // initializers even if some of them fail.
4988       if (!Info.noteFailure())
4989         return false;
4990       Success = false;
4991     } else if (!ForbiddenNullArgs.empty() &&
4992                ForbiddenNullArgs[I - Args.begin()] &&
4993                ArgValues[I - Args.begin()].isNullPointer()) {
4994       Info.CCEDiag(*I, diag::note_non_null_attribute_failed);
4995       if (!Info.noteFailure())
4996         return false;
4997       Success = false;
4998     }
4999   }
5000   return Success;
5001 }
5002 
5003 /// Evaluate a function call.
5004 static bool HandleFunctionCall(SourceLocation CallLoc,
5005                                const FunctionDecl *Callee, const LValue *This,
5006                                ArrayRef<const Expr*> Args, const Stmt *Body,
5007                                EvalInfo &Info, APValue &Result,
5008                                const LValue *ResultSlot) {
5009   ArgVector ArgValues(Args.size());
5010   if (!EvaluateArgs(Args, ArgValues, Info, Callee))
5011     return false;
5012 
5013   if (!Info.CheckCallLimit(CallLoc))
5014     return false;
5015 
5016   CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
5017 
5018   // For a trivial copy or move assignment, perform an APValue copy. This is
5019   // essential for unions, where the operations performed by the assignment
5020   // operator cannot be represented as statements.
5021   //
5022   // Skip this for non-union classes with no fields; in that case, the defaulted
5023   // copy/move does not actually read the object.
5024   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
5025   if (MD && MD->isDefaulted() &&
5026       (MD->getParent()->isUnion() ||
5027        (MD->isTrivial() && hasFields(MD->getParent())))) {
5028     assert(This &&
5029            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
5030     LValue RHS;
5031     RHS.setFrom(Info.Ctx, ArgValues[0]);
5032     APValue RHSValue;
5033     if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(), RHS,
5034                                         RHSValue, MD->getParent()->isUnion()))
5035       return false;
5036     if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
5037         !HandleUnionActiveMemberChange(Info, Args[0], *This))
5038       return false;
5039     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
5040                           RHSValue))
5041       return false;
5042     This->moveInto(Result);
5043     return true;
5044   } else if (MD && isLambdaCallOperator(MD)) {
5045     // We're in a lambda; determine the lambda capture field maps unless we're
5046     // just constexpr checking a lambda's call operator. constexpr checking is
5047     // done before the captures have been added to the closure object (unless
5048     // we're inferring constexpr-ness), so we don't have access to them in this
5049     // case. But since we don't need the captures to constexpr check, we can
5050     // just ignore them.
5051     if (!Info.checkingPotentialConstantExpression())
5052       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5053                                         Frame.LambdaThisCaptureField);
5054   }
5055 
5056   StmtResult Ret = {Result, ResultSlot};
5057   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
5058   if (ESR == ESR_Succeeded) {
5059     if (Callee->getReturnType()->isVoidType())
5060       return true;
5061     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
5062   }
5063   return ESR == ESR_Returned;
5064 }
5065 
5066 /// Evaluate a constructor call.
5067 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5068                                   APValue *ArgValues,
5069                                   const CXXConstructorDecl *Definition,
5070                                   EvalInfo &Info, APValue &Result) {
5071   SourceLocation CallLoc = E->getExprLoc();
5072   if (!Info.CheckCallLimit(CallLoc))
5073     return false;
5074 
5075   const CXXRecordDecl *RD = Definition->getParent();
5076   if (RD->getNumVBases()) {
5077     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5078     return false;
5079   }
5080 
5081   EvalInfo::EvaluatingConstructorRAII EvalObj(
5082       Info,
5083       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5084       RD->getNumBases());
5085   CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
5086 
5087   // FIXME: Creating an APValue just to hold a nonexistent return value is
5088   // wasteful.
5089   APValue RetVal;
5090   StmtResult Ret = {RetVal, nullptr};
5091 
5092   // If it's a delegating constructor, delegate.
5093   if (Definition->isDelegatingConstructor()) {
5094     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
5095     {
5096       FullExpressionRAII InitScope(Info);
5097       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
5098         return false;
5099     }
5100     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5101   }
5102 
5103   // For a trivial copy or move constructor, perform an APValue copy. This is
5104   // essential for unions (or classes with anonymous union members), where the
5105   // operations performed by the constructor cannot be represented by
5106   // ctor-initializers.
5107   //
5108   // Skip this for empty non-union classes; we should not perform an
5109   // lvalue-to-rvalue conversion on them because their copy constructor does not
5110   // actually read them.
5111   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
5112       (Definition->getParent()->isUnion() ||
5113        (Definition->isTrivial() && hasFields(Definition->getParent())))) {
5114     LValue RHS;
5115     RHS.setFrom(Info.Ctx, ArgValues[0]);
5116     return handleLValueToRValueConversion(
5117         Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
5118         RHS, Result, Definition->getParent()->isUnion());
5119   }
5120 
5121   // Reserve space for the struct members.
5122   if (!RD->isUnion() && !Result.hasValue())
5123     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5124                      std::distance(RD->field_begin(), RD->field_end()));
5125 
5126   if (RD->isInvalidDecl()) return false;
5127   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5128 
5129   // A scope for temporaries lifetime-extended by reference members.
5130   BlockScopeRAII LifetimeExtendedScope(Info);
5131 
5132   bool Success = true;
5133   unsigned BasesSeen = 0;
5134 #ifndef NDEBUG
5135   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5136 #endif
5137   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
5138   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
5139     // We might be initializing the same field again if this is an indirect
5140     // field initialization.
5141     if (FieldIt == RD->field_end() ||
5142         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
5143       assert(Indirect && "fields out of order?");
5144       return;
5145     }
5146 
5147     // Default-initialize any fields with no explicit initializer.
5148     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
5149       assert(FieldIt != RD->field_end() && "missing field?");
5150       if (!FieldIt->isUnnamedBitfield())
5151         Result.getStructField(FieldIt->getFieldIndex()) =
5152             getDefaultInitValue(FieldIt->getType());
5153     }
5154     ++FieldIt;
5155   };
5156   for (const auto *I : Definition->inits()) {
5157     LValue Subobject = This;
5158     LValue SubobjectParent = This;
5159     APValue *Value = &Result;
5160 
5161     // Determine the subobject to initialize.
5162     FieldDecl *FD = nullptr;
5163     if (I->isBaseInitializer()) {
5164       QualType BaseType(I->getBaseClass(), 0);
5165 #ifndef NDEBUG
5166       // Non-virtual base classes are initialized in the order in the class
5167       // definition. We have already checked for virtual base classes.
5168       assert(!BaseIt->isVirtual() && "virtual base for literal type");
5169       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5170              "base class initializers not in expected order");
5171       ++BaseIt;
5172 #endif
5173       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
5174                                   BaseType->getAsCXXRecordDecl(), &Layout))
5175         return false;
5176       Value = &Result.getStructBase(BasesSeen++);
5177     } else if ((FD = I->getMember())) {
5178       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
5179         return false;
5180       if (RD->isUnion()) {
5181         Result = APValue(FD);
5182         Value = &Result.getUnionValue();
5183       } else {
5184         SkipToField(FD, false);
5185         Value = &Result.getStructField(FD->getFieldIndex());
5186       }
5187     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
5188       // Walk the indirect field decl's chain to find the object to initialize,
5189       // and make sure we've initialized every step along it.
5190       auto IndirectFieldChain = IFD->chain();
5191       for (auto *C : IndirectFieldChain) {
5192         FD = cast<FieldDecl>(C);
5193         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5194         // Switch the union field if it differs. This happens if we had
5195         // preceding zero-initialization, and we're now initializing a union
5196         // subobject other than the first.
5197         // FIXME: In this case, the values of the other subobjects are
5198         // specified, since zero-initialization sets all padding bits to zero.
5199         if (!Value->hasValue() ||
5200             (Value->isUnion() && Value->getUnionField() != FD)) {
5201           if (CD->isUnion())
5202             *Value = APValue(FD);
5203           else
5204             // FIXME: This immediately starts the lifetime of all members of an
5205             // anonymous struct. It would be preferable to strictly start member
5206             // lifetime in initialization order.
5207             *Value = getDefaultInitValue(Info.Ctx.getRecordType(CD));
5208         }
5209         // Store Subobject as its parent before updating it for the last element
5210         // in the chain.
5211         if (C == IndirectFieldChain.back())
5212           SubobjectParent = Subobject;
5213         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
5214           return false;
5215         if (CD->isUnion())
5216           Value = &Value->getUnionValue();
5217         else {
5218           if (C == IndirectFieldChain.front() && !RD->isUnion())
5219             SkipToField(FD, true);
5220           Value = &Value->getStructField(FD->getFieldIndex());
5221         }
5222       }
5223     } else {
5224       llvm_unreachable("unknown base initializer kind");
5225     }
5226 
5227     // Need to override This for implicit field initializers as in this case
5228     // This refers to innermost anonymous struct/union containing initializer,
5229     // not to currently constructed class.
5230     const Expr *Init = I->getInit();
5231     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
5232                                   isa<CXXDefaultInitExpr>(Init));
5233     FullExpressionRAII InitScope(Info);
5234     if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
5235         (FD && FD->isBitField() &&
5236          !truncateBitfieldValue(Info, Init, *Value, FD))) {
5237       // If we're checking for a potential constant expression, evaluate all
5238       // initializers even if some of them fail.
5239       if (!Info.noteFailure())
5240         return false;
5241       Success = false;
5242     }
5243 
5244     // This is the point at which the dynamic type of the object becomes this
5245     // class type.
5246     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
5247       EvalObj.finishedConstructingBases();
5248   }
5249 
5250   // Default-initialize any remaining fields.
5251   if (!RD->isUnion()) {
5252     for (; FieldIt != RD->field_end(); ++FieldIt) {
5253       if (!FieldIt->isUnnamedBitfield())
5254         Result.getStructField(FieldIt->getFieldIndex()) =
5255             getDefaultInitValue(FieldIt->getType());
5256     }
5257   }
5258 
5259   return Success &&
5260          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5261 }
5262 
5263 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5264                                   ArrayRef<const Expr*> Args,
5265                                   const CXXConstructorDecl *Definition,
5266                                   EvalInfo &Info, APValue &Result) {
5267   ArgVector ArgValues(Args.size());
5268   if (!EvaluateArgs(Args, ArgValues, Info, Definition))
5269     return false;
5270 
5271   return HandleConstructorCall(E, This, ArgValues.data(), Definition,
5272                                Info, Result);
5273 }
5274 
5275 //===----------------------------------------------------------------------===//
5276 // Generic Evaluation
5277 //===----------------------------------------------------------------------===//
5278 namespace {
5279 
5280 class BitCastBuffer {
5281   // FIXME: We're going to need bit-level granularity when we support
5282   // bit-fields.
5283   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
5284   // we don't support a host or target where that is the case. Still, we should
5285   // use a more generic type in case we ever do.
5286   SmallVector<Optional<unsigned char>, 32> Bytes;
5287 
5288   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
5289                 "Need at least 8 bit unsigned char");
5290 
5291   bool TargetIsLittleEndian;
5292 
5293 public:
5294   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
5295       : Bytes(Width.getQuantity()),
5296         TargetIsLittleEndian(TargetIsLittleEndian) {}
5297 
5298   LLVM_NODISCARD
5299   bool readObject(CharUnits Offset, CharUnits Width,
5300                   SmallVectorImpl<unsigned char> &Output) const {
5301     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
5302       // If a byte of an integer is uninitialized, then the whole integer is
5303       // uninitalized.
5304       if (!Bytes[I.getQuantity()])
5305         return false;
5306       Output.push_back(*Bytes[I.getQuantity()]);
5307     }
5308     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
5309       std::reverse(Output.begin(), Output.end());
5310     return true;
5311   }
5312 
5313   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
5314     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
5315       std::reverse(Input.begin(), Input.end());
5316 
5317     size_t Index = 0;
5318     for (unsigned char Byte : Input) {
5319       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
5320       Bytes[Offset.getQuantity() + Index] = Byte;
5321       ++Index;
5322     }
5323   }
5324 
5325   size_t size() { return Bytes.size(); }
5326 };
5327 
5328 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
5329 /// target would represent the value at runtime.
5330 class APValueToBufferConverter {
5331   EvalInfo &Info;
5332   BitCastBuffer Buffer;
5333   const CastExpr *BCE;
5334 
5335   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
5336                            const CastExpr *BCE)
5337       : Info(Info),
5338         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
5339         BCE(BCE) {}
5340 
5341   bool visit(const APValue &Val, QualType Ty) {
5342     return visit(Val, Ty, CharUnits::fromQuantity(0));
5343   }
5344 
5345   // Write out Val with type Ty into Buffer starting at Offset.
5346   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
5347     assert((size_t)Offset.getQuantity() <= Buffer.size());
5348 
5349     // As a special case, nullptr_t has an indeterminate value.
5350     if (Ty->isNullPtrType())
5351       return true;
5352 
5353     // Dig through Src to find the byte at SrcOffset.
5354     switch (Val.getKind()) {
5355     case APValue::Indeterminate:
5356     case APValue::None:
5357       return true;
5358 
5359     case APValue::Int:
5360       return visitInt(Val.getInt(), Ty, Offset);
5361     case APValue::Float:
5362       return visitFloat(Val.getFloat(), Ty, Offset);
5363     case APValue::Array:
5364       return visitArray(Val, Ty, Offset);
5365     case APValue::Struct:
5366       return visitRecord(Val, Ty, Offset);
5367 
5368     case APValue::ComplexInt:
5369     case APValue::ComplexFloat:
5370     case APValue::Vector:
5371     case APValue::FixedPoint:
5372       // FIXME: We should support these.
5373 
5374     case APValue::Union:
5375     case APValue::MemberPointer:
5376     case APValue::AddrLabelDiff: {
5377       Info.FFDiag(BCE->getBeginLoc(),
5378                   diag::note_constexpr_bit_cast_unsupported_type)
5379           << Ty;
5380       return false;
5381     }
5382 
5383     case APValue::LValue:
5384       llvm_unreachable("LValue subobject in bit_cast?");
5385     }
5386     llvm_unreachable("Unhandled APValue::ValueKind");
5387   }
5388 
5389   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
5390     const RecordDecl *RD = Ty->getAsRecordDecl();
5391     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5392 
5393     // Visit the base classes.
5394     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5395       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
5396         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
5397         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
5398 
5399         if (!visitRecord(Val.getStructBase(I), BS.getType(),
5400                          Layout.getBaseClassOffset(BaseDecl) + Offset))
5401           return false;
5402       }
5403     }
5404 
5405     // Visit the fields.
5406     unsigned FieldIdx = 0;
5407     for (FieldDecl *FD : RD->fields()) {
5408       if (FD->isBitField()) {
5409         Info.FFDiag(BCE->getBeginLoc(),
5410                     diag::note_constexpr_bit_cast_unsupported_bitfield);
5411         return false;
5412       }
5413 
5414       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
5415 
5416       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
5417              "only bit-fields can have sub-char alignment");
5418       CharUnits FieldOffset =
5419           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
5420       QualType FieldTy = FD->getType();
5421       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
5422         return false;
5423       ++FieldIdx;
5424     }
5425 
5426     return true;
5427   }
5428 
5429   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
5430     const auto *CAT =
5431         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
5432     if (!CAT)
5433       return false;
5434 
5435     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
5436     unsigned NumInitializedElts = Val.getArrayInitializedElts();
5437     unsigned ArraySize = Val.getArraySize();
5438     // First, initialize the initialized elements.
5439     for (unsigned I = 0; I != NumInitializedElts; ++I) {
5440       const APValue &SubObj = Val.getArrayInitializedElt(I);
5441       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
5442         return false;
5443     }
5444 
5445     // Next, initialize the rest of the array using the filler.
5446     if (Val.hasArrayFiller()) {
5447       const APValue &Filler = Val.getArrayFiller();
5448       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
5449         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
5450           return false;
5451       }
5452     }
5453 
5454     return true;
5455   }
5456 
5457   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
5458     CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
5459     SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
5460     llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
5461     Buffer.writeObject(Offset, Bytes);
5462     return true;
5463   }
5464 
5465   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
5466     APSInt AsInt(Val.bitcastToAPInt());
5467     return visitInt(AsInt, Ty, Offset);
5468   }
5469 
5470 public:
5471   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
5472                                          const CastExpr *BCE) {
5473     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
5474     APValueToBufferConverter Converter(Info, DstSize, BCE);
5475     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
5476       return None;
5477     return Converter.Buffer;
5478   }
5479 };
5480 
5481 /// Write an BitCastBuffer into an APValue.
5482 class BufferToAPValueConverter {
5483   EvalInfo &Info;
5484   const BitCastBuffer &Buffer;
5485   const CastExpr *BCE;
5486 
5487   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
5488                            const CastExpr *BCE)
5489       : Info(Info), Buffer(Buffer), BCE(BCE) {}
5490 
5491   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
5492   // with an invalid type, so anything left is a deficiency on our part (FIXME).
5493   // Ideally this will be unreachable.
5494   llvm::NoneType unsupportedType(QualType Ty) {
5495     Info.FFDiag(BCE->getBeginLoc(),
5496                 diag::note_constexpr_bit_cast_unsupported_type)
5497         << Ty;
5498     return None;
5499   }
5500 
5501   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
5502                           const EnumType *EnumSugar = nullptr) {
5503     if (T->isNullPtrType()) {
5504       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
5505       return APValue((Expr *)nullptr,
5506                      /*Offset=*/CharUnits::fromQuantity(NullValue),
5507                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
5508     }
5509 
5510     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
5511     SmallVector<uint8_t, 8> Bytes;
5512     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
5513       // If this is std::byte or unsigned char, then its okay to store an
5514       // indeterminate value.
5515       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
5516       bool IsUChar =
5517           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
5518                          T->isSpecificBuiltinType(BuiltinType::Char_U));
5519       if (!IsStdByte && !IsUChar) {
5520         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
5521         Info.FFDiag(BCE->getExprLoc(),
5522                     diag::note_constexpr_bit_cast_indet_dest)
5523             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
5524         return None;
5525       }
5526 
5527       return APValue::IndeterminateValue();
5528     }
5529 
5530     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
5531     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
5532 
5533     if (T->isIntegralOrEnumerationType()) {
5534       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
5535       return APValue(Val);
5536     }
5537 
5538     if (T->isRealFloatingType()) {
5539       const llvm::fltSemantics &Semantics =
5540           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
5541       return APValue(APFloat(Semantics, Val));
5542     }
5543 
5544     return unsupportedType(QualType(T, 0));
5545   }
5546 
5547   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
5548     const RecordDecl *RD = RTy->getAsRecordDecl();
5549     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5550 
5551     unsigned NumBases = 0;
5552     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
5553       NumBases = CXXRD->getNumBases();
5554 
5555     APValue ResultVal(APValue::UninitStruct(), NumBases,
5556                       std::distance(RD->field_begin(), RD->field_end()));
5557 
5558     // Visit the base classes.
5559     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5560       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
5561         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
5562         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
5563         if (BaseDecl->isEmpty() ||
5564             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
5565           continue;
5566 
5567         Optional<APValue> SubObj = visitType(
5568             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
5569         if (!SubObj)
5570           return None;
5571         ResultVal.getStructBase(I) = *SubObj;
5572       }
5573     }
5574 
5575     // Visit the fields.
5576     unsigned FieldIdx = 0;
5577     for (FieldDecl *FD : RD->fields()) {
5578       // FIXME: We don't currently support bit-fields. A lot of the logic for
5579       // this is in CodeGen, so we need to factor it around.
5580       if (FD->isBitField()) {
5581         Info.FFDiag(BCE->getBeginLoc(),
5582                     diag::note_constexpr_bit_cast_unsupported_bitfield);
5583         return None;
5584       }
5585 
5586       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
5587       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
5588 
5589       CharUnits FieldOffset =
5590           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
5591           Offset;
5592       QualType FieldTy = FD->getType();
5593       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
5594       if (!SubObj)
5595         return None;
5596       ResultVal.getStructField(FieldIdx) = *SubObj;
5597       ++FieldIdx;
5598     }
5599 
5600     return ResultVal;
5601   }
5602 
5603   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
5604     QualType RepresentationType = Ty->getDecl()->getIntegerType();
5605     assert(!RepresentationType.isNull() &&
5606            "enum forward decl should be caught by Sema");
5607     const BuiltinType *AsBuiltin =
5608         RepresentationType.getCanonicalType()->getAs<BuiltinType>();
5609     assert(AsBuiltin && "non-integral enum underlying type?");
5610     // Recurse into the underlying type. Treat std::byte transparently as
5611     // unsigned char.
5612     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
5613   }
5614 
5615   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
5616     size_t Size = Ty->getSize().getLimitedValue();
5617     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
5618 
5619     APValue ArrayValue(APValue::UninitArray(), Size, Size);
5620     for (size_t I = 0; I != Size; ++I) {
5621       Optional<APValue> ElementValue =
5622           visitType(Ty->getElementType(), Offset + I * ElementWidth);
5623       if (!ElementValue)
5624         return None;
5625       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
5626     }
5627 
5628     return ArrayValue;
5629   }
5630 
5631   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
5632     return unsupportedType(QualType(Ty, 0));
5633   }
5634 
5635   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
5636     QualType Can = Ty.getCanonicalType();
5637 
5638     switch (Can->getTypeClass()) {
5639 #define TYPE(Class, Base)                                                      \
5640   case Type::Class:                                                            \
5641     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
5642 #define ABSTRACT_TYPE(Class, Base)
5643 #define NON_CANONICAL_TYPE(Class, Base)                                        \
5644   case Type::Class:                                                            \
5645     llvm_unreachable("non-canonical type should be impossible!");
5646 #define DEPENDENT_TYPE(Class, Base)                                            \
5647   case Type::Class:                                                            \
5648     llvm_unreachable(                                                          \
5649         "dependent types aren't supported in the constant evaluator!");
5650 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
5651   case Type::Class:                                                            \
5652     llvm_unreachable("either dependent or not canonical!");
5653 #include "clang/AST/TypeNodes.def"
5654     }
5655     llvm_unreachable("Unhandled Type::TypeClass");
5656   }
5657 
5658 public:
5659   // Pull out a full value of type DstType.
5660   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
5661                                    const CastExpr *BCE) {
5662     BufferToAPValueConverter Converter(Info, Buffer, BCE);
5663     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
5664   }
5665 };
5666 
5667 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
5668                                                  QualType Ty, EvalInfo *Info,
5669                                                  const ASTContext &Ctx,
5670                                                  bool CheckingDest) {
5671   Ty = Ty.getCanonicalType();
5672 
5673   auto diag = [&](int Reason) {
5674     if (Info)
5675       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
5676           << CheckingDest << (Reason == 4) << Reason;
5677     return false;
5678   };
5679   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
5680     if (Info)
5681       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
5682           << NoteTy << Construct << Ty;
5683     return false;
5684   };
5685 
5686   if (Ty->isUnionType())
5687     return diag(0);
5688   if (Ty->isPointerType())
5689     return diag(1);
5690   if (Ty->isMemberPointerType())
5691     return diag(2);
5692   if (Ty.isVolatileQualified())
5693     return diag(3);
5694 
5695   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
5696     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
5697       for (CXXBaseSpecifier &BS : CXXRD->bases())
5698         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
5699                                                   CheckingDest))
5700           return note(1, BS.getType(), BS.getBeginLoc());
5701     }
5702     for (FieldDecl *FD : Record->fields()) {
5703       if (FD->getType()->isReferenceType())
5704         return diag(4);
5705       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
5706                                                 CheckingDest))
5707         return note(0, FD->getType(), FD->getBeginLoc());
5708     }
5709   }
5710 
5711   if (Ty->isArrayType() &&
5712       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
5713                                             Info, Ctx, CheckingDest))
5714     return false;
5715 
5716   return true;
5717 }
5718 
5719 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
5720                                              const ASTContext &Ctx,
5721                                              const CastExpr *BCE) {
5722   bool DestOK = checkBitCastConstexprEligibilityType(
5723       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
5724   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
5725                                 BCE->getBeginLoc(),
5726                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
5727   return SourceOK;
5728 }
5729 
5730 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
5731                                         APValue &SourceValue,
5732                                         const CastExpr *BCE) {
5733   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
5734          "no host or target supports non 8-bit chars");
5735   assert(SourceValue.isLValue() &&
5736          "LValueToRValueBitcast requires an lvalue operand!");
5737 
5738   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
5739     return false;
5740 
5741   LValue SourceLValue;
5742   APValue SourceRValue;
5743   SourceLValue.setFrom(Info.Ctx, SourceValue);
5744   if (!handleLValueToRValueConversion(
5745           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
5746           SourceRValue, /*WantObjectRepresentation=*/true))
5747     return false;
5748 
5749   // Read out SourceValue into a char buffer.
5750   Optional<BitCastBuffer> Buffer =
5751       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
5752   if (!Buffer)
5753     return false;
5754 
5755   // Write out the buffer into a new APValue.
5756   Optional<APValue> MaybeDestValue =
5757       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
5758   if (!MaybeDestValue)
5759     return false;
5760 
5761   DestValue = std::move(*MaybeDestValue);
5762   return true;
5763 }
5764 
5765 template <class Derived>
5766 class ExprEvaluatorBase
5767   : public ConstStmtVisitor<Derived, bool> {
5768 private:
5769   Derived &getDerived() { return static_cast<Derived&>(*this); }
5770   bool DerivedSuccess(const APValue &V, const Expr *E) {
5771     return getDerived().Success(V, E);
5772   }
5773   bool DerivedZeroInitialization(const Expr *E) {
5774     return getDerived().ZeroInitialization(E);
5775   }
5776 
5777   // Check whether a conditional operator with a non-constant condition is a
5778   // potential constant expression. If neither arm is a potential constant
5779   // expression, then the conditional operator is not either.
5780   template<typename ConditionalOperator>
5781   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
5782     assert(Info.checkingPotentialConstantExpression());
5783 
5784     // Speculatively evaluate both arms.
5785     SmallVector<PartialDiagnosticAt, 8> Diag;
5786     {
5787       SpeculativeEvaluationRAII Speculate(Info, &Diag);
5788       StmtVisitorTy::Visit(E->getFalseExpr());
5789       if (Diag.empty())
5790         return;
5791     }
5792 
5793     {
5794       SpeculativeEvaluationRAII Speculate(Info, &Diag);
5795       Diag.clear();
5796       StmtVisitorTy::Visit(E->getTrueExpr());
5797       if (Diag.empty())
5798         return;
5799     }
5800 
5801     Error(E, diag::note_constexpr_conditional_never_const);
5802   }
5803 
5804 
5805   template<typename ConditionalOperator>
5806   bool HandleConditionalOperator(const ConditionalOperator *E) {
5807     bool BoolResult;
5808     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
5809       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
5810         CheckPotentialConstantConditional(E);
5811         return false;
5812       }
5813       if (Info.noteFailure()) {
5814         StmtVisitorTy::Visit(E->getTrueExpr());
5815         StmtVisitorTy::Visit(E->getFalseExpr());
5816       }
5817       return false;
5818     }
5819 
5820     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
5821     return StmtVisitorTy::Visit(EvalExpr);
5822   }
5823 
5824 protected:
5825   EvalInfo &Info;
5826   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
5827   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
5828 
5829   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
5830     return Info.CCEDiag(E, D);
5831   }
5832 
5833   bool ZeroInitialization(const Expr *E) { return Error(E); }
5834 
5835 public:
5836   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
5837 
5838   EvalInfo &getEvalInfo() { return Info; }
5839 
5840   /// Report an evaluation error. This should only be called when an error is
5841   /// first discovered. When propagating an error, just return false.
5842   bool Error(const Expr *E, diag::kind D) {
5843     Info.FFDiag(E, D);
5844     return false;
5845   }
5846   bool Error(const Expr *E) {
5847     return Error(E, diag::note_invalid_subexpr_in_const_expr);
5848   }
5849 
5850   bool VisitStmt(const Stmt *) {
5851     llvm_unreachable("Expression evaluator should not be called on stmts");
5852   }
5853   bool VisitExpr(const Expr *E) {
5854     return Error(E);
5855   }
5856 
5857   bool VisitConstantExpr(const ConstantExpr *E)
5858     { return StmtVisitorTy::Visit(E->getSubExpr()); }
5859   bool VisitParenExpr(const ParenExpr *E)
5860     { return StmtVisitorTy::Visit(E->getSubExpr()); }
5861   bool VisitUnaryExtension(const UnaryOperator *E)
5862     { return StmtVisitorTy::Visit(E->getSubExpr()); }
5863   bool VisitUnaryPlus(const UnaryOperator *E)
5864     { return StmtVisitorTy::Visit(E->getSubExpr()); }
5865   bool VisitChooseExpr(const ChooseExpr *E)
5866     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
5867   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
5868     { return StmtVisitorTy::Visit(E->getResultExpr()); }
5869   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
5870     { return StmtVisitorTy::Visit(E->getReplacement()); }
5871   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
5872     TempVersionRAII RAII(*Info.CurrentCall);
5873     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
5874     return StmtVisitorTy::Visit(E->getExpr());
5875   }
5876   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
5877     TempVersionRAII RAII(*Info.CurrentCall);
5878     // The initializer may not have been parsed yet, or might be erroneous.
5879     if (!E->getExpr())
5880       return Error(E);
5881     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
5882     return StmtVisitorTy::Visit(E->getExpr());
5883   }
5884 
5885   // We cannot create any objects for which cleanups are required, so there is
5886   // nothing to do here; all cleanups must come from unevaluated subexpressions.
5887   bool VisitExprWithCleanups(const ExprWithCleanups *E)
5888     { return StmtVisitorTy::Visit(E->getSubExpr()); }
5889 
5890   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
5891     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
5892     return static_cast<Derived*>(this)->VisitCastExpr(E);
5893   }
5894   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
5895     if (!Info.Ctx.getLangOpts().CPlusPlus2a)
5896       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
5897     return static_cast<Derived*>(this)->VisitCastExpr(E);
5898   }
5899   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
5900     return static_cast<Derived*>(this)->VisitCastExpr(E);
5901   }
5902 
5903   bool VisitBinaryOperator(const BinaryOperator *E) {
5904     switch (E->getOpcode()) {
5905     default:
5906       return Error(E);
5907 
5908     case BO_Comma:
5909       VisitIgnoredValue(E->getLHS());
5910       return StmtVisitorTy::Visit(E->getRHS());
5911 
5912     case BO_PtrMemD:
5913     case BO_PtrMemI: {
5914       LValue Obj;
5915       if (!HandleMemberPointerAccess(Info, E, Obj))
5916         return false;
5917       APValue Result;
5918       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
5919         return false;
5920       return DerivedSuccess(Result, E);
5921     }
5922     }
5923   }
5924 
5925   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
5926     // Evaluate and cache the common expression. We treat it as a temporary,
5927     // even though it's not quite the same thing.
5928     if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
5929                   Info, E->getCommon()))
5930       return false;
5931 
5932     return HandleConditionalOperator(E);
5933   }
5934 
5935   bool VisitConditionalOperator(const ConditionalOperator *E) {
5936     bool IsBcpCall = false;
5937     // If the condition (ignoring parens) is a __builtin_constant_p call,
5938     // the result is a constant expression if it can be folded without
5939     // side-effects. This is an important GNU extension. See GCC PR38377
5940     // for discussion.
5941     if (const CallExpr *CallCE =
5942           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
5943       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
5944         IsBcpCall = true;
5945 
5946     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
5947     // constant expression; we can't check whether it's potentially foldable.
5948     // FIXME: We should instead treat __builtin_constant_p as non-constant if
5949     // it would return 'false' in this mode.
5950     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
5951       return false;
5952 
5953     FoldConstant Fold(Info, IsBcpCall);
5954     if (!HandleConditionalOperator(E)) {
5955       Fold.keepDiagnostics();
5956       return false;
5957     }
5958 
5959     return true;
5960   }
5961 
5962   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
5963     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
5964       return DerivedSuccess(*Value, E);
5965 
5966     const Expr *Source = E->getSourceExpr();
5967     if (!Source)
5968       return Error(E);
5969     if (Source == E) { // sanity checking.
5970       assert(0 && "OpaqueValueExpr recursively refers to itself");
5971       return Error(E);
5972     }
5973     return StmtVisitorTy::Visit(Source);
5974   }
5975 
5976   bool VisitCallExpr(const CallExpr *E) {
5977     APValue Result;
5978     if (!handleCallExpr(E, Result, nullptr))
5979       return false;
5980     return DerivedSuccess(Result, E);
5981   }
5982 
5983   bool handleCallExpr(const CallExpr *E, APValue &Result,
5984                      const LValue *ResultSlot) {
5985     const Expr *Callee = E->getCallee()->IgnoreParens();
5986     QualType CalleeType = Callee->getType();
5987 
5988     const FunctionDecl *FD = nullptr;
5989     LValue *This = nullptr, ThisVal;
5990     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
5991     bool HasQualifier = false;
5992 
5993     // Extract function decl and 'this' pointer from the callee.
5994     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
5995       const CXXMethodDecl *Member = nullptr;
5996       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
5997         // Explicit bound member calls, such as x.f() or p->g();
5998         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
5999           return false;
6000         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
6001         if (!Member)
6002           return Error(Callee);
6003         This = &ThisVal;
6004         HasQualifier = ME->hasQualifier();
6005       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
6006         // Indirect bound member calls ('.*' or '->*').
6007         Member = dyn_cast_or_null<CXXMethodDecl>(
6008             HandleMemberPointerAccess(Info, BE, ThisVal, false));
6009         if (!Member)
6010           return Error(Callee);
6011         This = &ThisVal;
6012       } else
6013         return Error(Callee);
6014       FD = Member;
6015     } else if (CalleeType->isFunctionPointerType()) {
6016       LValue Call;
6017       if (!EvaluatePointer(Callee, Call, Info))
6018         return false;
6019 
6020       if (!Call.getLValueOffset().isZero())
6021         return Error(Callee);
6022       FD = dyn_cast_or_null<FunctionDecl>(
6023                              Call.getLValueBase().dyn_cast<const ValueDecl*>());
6024       if (!FD)
6025         return Error(Callee);
6026       // Don't call function pointers which have been cast to some other type.
6027       // Per DR (no number yet), the caller and callee can differ in noexcept.
6028       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
6029         CalleeType->getPointeeType(), FD->getType())) {
6030         return Error(E);
6031       }
6032 
6033       // Overloaded operator calls to member functions are represented as normal
6034       // calls with '*this' as the first argument.
6035       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6036       if (MD && !MD->isStatic()) {
6037         // FIXME: When selecting an implicit conversion for an overloaded
6038         // operator delete, we sometimes try to evaluate calls to conversion
6039         // operators without a 'this' parameter!
6040         if (Args.empty())
6041           return Error(E);
6042 
6043         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
6044           return false;
6045         This = &ThisVal;
6046         Args = Args.slice(1);
6047       } else if (MD && MD->isLambdaStaticInvoker()) {
6048         // Map the static invoker for the lambda back to the call operator.
6049         // Conveniently, we don't have to slice out the 'this' argument (as is
6050         // being done for the non-static case), since a static member function
6051         // doesn't have an implicit argument passed in.
6052         const CXXRecordDecl *ClosureClass = MD->getParent();
6053         assert(
6054             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
6055             "Number of captures must be zero for conversion to function-ptr");
6056 
6057         const CXXMethodDecl *LambdaCallOp =
6058             ClosureClass->getLambdaCallOperator();
6059 
6060         // Set 'FD', the function that will be called below, to the call
6061         // operator.  If the closure object represents a generic lambda, find
6062         // the corresponding specialization of the call operator.
6063 
6064         if (ClosureClass->isGenericLambda()) {
6065           assert(MD->isFunctionTemplateSpecialization() &&
6066                  "A generic lambda's static-invoker function must be a "
6067                  "template specialization");
6068           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
6069           FunctionTemplateDecl *CallOpTemplate =
6070               LambdaCallOp->getDescribedFunctionTemplate();
6071           void *InsertPos = nullptr;
6072           FunctionDecl *CorrespondingCallOpSpecialization =
6073               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
6074           assert(CorrespondingCallOpSpecialization &&
6075                  "We must always have a function call operator specialization "
6076                  "that corresponds to our static invoker specialization");
6077           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
6078         } else
6079           FD = LambdaCallOp;
6080       }
6081     } else
6082       return Error(E);
6083 
6084     SmallVector<QualType, 4> CovariantAdjustmentPath;
6085     if (This) {
6086       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
6087       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
6088         // Perform virtual dispatch, if necessary.
6089         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
6090                                    CovariantAdjustmentPath);
6091         if (!FD)
6092           return false;
6093       } else {
6094         // Check that the 'this' pointer points to an object of the right type.
6095         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This))
6096           return false;
6097       }
6098     }
6099 
6100     const FunctionDecl *Definition = nullptr;
6101     Stmt *Body = FD->getBody(Definition);
6102 
6103     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
6104         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
6105                             Result, ResultSlot))
6106       return false;
6107 
6108     if (!CovariantAdjustmentPath.empty() &&
6109         !HandleCovariantReturnAdjustment(Info, E, Result,
6110                                          CovariantAdjustmentPath))
6111       return false;
6112 
6113     return true;
6114   }
6115 
6116   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
6117     return StmtVisitorTy::Visit(E->getInitializer());
6118   }
6119   bool VisitInitListExpr(const InitListExpr *E) {
6120     if (E->getNumInits() == 0)
6121       return DerivedZeroInitialization(E);
6122     if (E->getNumInits() == 1)
6123       return StmtVisitorTy::Visit(E->getInit(0));
6124     return Error(E);
6125   }
6126   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
6127     return DerivedZeroInitialization(E);
6128   }
6129   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
6130     return DerivedZeroInitialization(E);
6131   }
6132   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
6133     return DerivedZeroInitialization(E);
6134   }
6135 
6136   /// A member expression where the object is a prvalue is itself a prvalue.
6137   bool VisitMemberExpr(const MemberExpr *E) {
6138     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
6139            "missing temporary materialization conversion");
6140     assert(!E->isArrow() && "missing call to bound member function?");
6141 
6142     APValue Val;
6143     if (!Evaluate(Val, Info, E->getBase()))
6144       return false;
6145 
6146     QualType BaseTy = E->getBase()->getType();
6147 
6148     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
6149     if (!FD) return Error(E);
6150     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
6151     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
6152            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
6153 
6154     // Note: there is no lvalue base here. But this case should only ever
6155     // happen in C or in C++98, where we cannot be evaluating a constexpr
6156     // constructor, which is the only case the base matters.
6157     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
6158     SubobjectDesignator Designator(BaseTy);
6159     Designator.addDeclUnchecked(FD);
6160 
6161     APValue Result;
6162     return extractSubobject(Info, E, Obj, Designator, Result) &&
6163            DerivedSuccess(Result, E);
6164   }
6165 
6166   bool VisitCastExpr(const CastExpr *E) {
6167     switch (E->getCastKind()) {
6168     default:
6169       break;
6170 
6171     case CK_AtomicToNonAtomic: {
6172       APValue AtomicVal;
6173       // This does not need to be done in place even for class/array types:
6174       // atomic-to-non-atomic conversion implies copying the object
6175       // representation.
6176       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
6177         return false;
6178       return DerivedSuccess(AtomicVal, E);
6179     }
6180 
6181     case CK_NoOp:
6182     case CK_UserDefinedConversion:
6183       return StmtVisitorTy::Visit(E->getSubExpr());
6184 
6185     case CK_LValueToRValue: {
6186       LValue LVal;
6187       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
6188         return false;
6189       APValue RVal;
6190       // Note, we use the subexpression's type in order to retain cv-qualifiers.
6191       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
6192                                           LVal, RVal))
6193         return false;
6194       return DerivedSuccess(RVal, E);
6195     }
6196     case CK_LValueToRValueBitCast: {
6197       APValue DestValue, SourceValue;
6198       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
6199         return false;
6200       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
6201         return false;
6202       return DerivedSuccess(DestValue, E);
6203     }
6204     }
6205 
6206     return Error(E);
6207   }
6208 
6209   bool VisitUnaryPostInc(const UnaryOperator *UO) {
6210     return VisitUnaryPostIncDec(UO);
6211   }
6212   bool VisitUnaryPostDec(const UnaryOperator *UO) {
6213     return VisitUnaryPostIncDec(UO);
6214   }
6215   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
6216     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6217       return Error(UO);
6218 
6219     LValue LVal;
6220     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
6221       return false;
6222     APValue RVal;
6223     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
6224                       UO->isIncrementOp(), &RVal))
6225       return false;
6226     return DerivedSuccess(RVal, UO);
6227   }
6228 
6229   bool VisitStmtExpr(const StmtExpr *E) {
6230     // We will have checked the full-expressions inside the statement expression
6231     // when they were completed, and don't need to check them again now.
6232     if (Info.checkingForUndefinedBehavior())
6233       return Error(E);
6234 
6235     BlockScopeRAII Scope(Info);
6236     const CompoundStmt *CS = E->getSubStmt();
6237     if (CS->body_empty())
6238       return true;
6239 
6240     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
6241                                            BE = CS->body_end();
6242          /**/; ++BI) {
6243       if (BI + 1 == BE) {
6244         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
6245         if (!FinalExpr) {
6246           Info.FFDiag((*BI)->getBeginLoc(),
6247                       diag::note_constexpr_stmt_expr_unsupported);
6248           return false;
6249         }
6250         return this->Visit(FinalExpr);
6251       }
6252 
6253       APValue ReturnValue;
6254       StmtResult Result = { ReturnValue, nullptr };
6255       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
6256       if (ESR != ESR_Succeeded) {
6257         // FIXME: If the statement-expression terminated due to 'return',
6258         // 'break', or 'continue', it would be nice to propagate that to
6259         // the outer statement evaluation rather than bailing out.
6260         if (ESR != ESR_Failed)
6261           Info.FFDiag((*BI)->getBeginLoc(),
6262                       diag::note_constexpr_stmt_expr_unsupported);
6263         return false;
6264       }
6265     }
6266 
6267     llvm_unreachable("Return from function from the loop above.");
6268   }
6269 
6270   /// Visit a value which is evaluated, but whose value is ignored.
6271   void VisitIgnoredValue(const Expr *E) {
6272     EvaluateIgnoredValue(Info, E);
6273   }
6274 
6275   /// Potentially visit a MemberExpr's base expression.
6276   void VisitIgnoredBaseExpression(const Expr *E) {
6277     // While MSVC doesn't evaluate the base expression, it does diagnose the
6278     // presence of side-effecting behavior.
6279     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
6280       return;
6281     VisitIgnoredValue(E);
6282   }
6283 };
6284 
6285 } // namespace
6286 
6287 //===----------------------------------------------------------------------===//
6288 // Common base class for lvalue and temporary evaluation.
6289 //===----------------------------------------------------------------------===//
6290 namespace {
6291 template<class Derived>
6292 class LValueExprEvaluatorBase
6293   : public ExprEvaluatorBase<Derived> {
6294 protected:
6295   LValue &Result;
6296   bool InvalidBaseOK;
6297   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
6298   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
6299 
6300   bool Success(APValue::LValueBase B) {
6301     Result.set(B);
6302     return true;
6303   }
6304 
6305   bool evaluatePointer(const Expr *E, LValue &Result) {
6306     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
6307   }
6308 
6309 public:
6310   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
6311       : ExprEvaluatorBaseTy(Info), Result(Result),
6312         InvalidBaseOK(InvalidBaseOK) {}
6313 
6314   bool Success(const APValue &V, const Expr *E) {
6315     Result.setFrom(this->Info.Ctx, V);
6316     return true;
6317   }
6318 
6319   bool VisitMemberExpr(const MemberExpr *E) {
6320     // Handle non-static data members.
6321     QualType BaseTy;
6322     bool EvalOK;
6323     if (E->isArrow()) {
6324       EvalOK = evaluatePointer(E->getBase(), Result);
6325       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
6326     } else if (E->getBase()->isRValue()) {
6327       assert(E->getBase()->getType()->isRecordType());
6328       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
6329       BaseTy = E->getBase()->getType();
6330     } else {
6331       EvalOK = this->Visit(E->getBase());
6332       BaseTy = E->getBase()->getType();
6333     }
6334     if (!EvalOK) {
6335       if (!InvalidBaseOK)
6336         return false;
6337       Result.setInvalid(E);
6338       return true;
6339     }
6340 
6341     const ValueDecl *MD = E->getMemberDecl();
6342     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
6343       assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
6344              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
6345       (void)BaseTy;
6346       if (!HandleLValueMember(this->Info, E, Result, FD))
6347         return false;
6348     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
6349       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
6350         return false;
6351     } else
6352       return this->Error(E);
6353 
6354     if (MD->getType()->isReferenceType()) {
6355       APValue RefValue;
6356       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
6357                                           RefValue))
6358         return false;
6359       return Success(RefValue, E);
6360     }
6361     return true;
6362   }
6363 
6364   bool VisitBinaryOperator(const BinaryOperator *E) {
6365     switch (E->getOpcode()) {
6366     default:
6367       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6368 
6369     case BO_PtrMemD:
6370     case BO_PtrMemI:
6371       return HandleMemberPointerAccess(this->Info, E, Result);
6372     }
6373   }
6374 
6375   bool VisitCastExpr(const CastExpr *E) {
6376     switch (E->getCastKind()) {
6377     default:
6378       return ExprEvaluatorBaseTy::VisitCastExpr(E);
6379 
6380     case CK_DerivedToBase:
6381     case CK_UncheckedDerivedToBase:
6382       if (!this->Visit(E->getSubExpr()))
6383         return false;
6384 
6385       // Now figure out the necessary offset to add to the base LV to get from
6386       // the derived class to the base class.
6387       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
6388                                   Result);
6389     }
6390   }
6391 };
6392 }
6393 
6394 //===----------------------------------------------------------------------===//
6395 // LValue Evaluation
6396 //
6397 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
6398 // function designators (in C), decl references to void objects (in C), and
6399 // temporaries (if building with -Wno-address-of-temporary).
6400 //
6401 // LValue evaluation produces values comprising a base expression of one of the
6402 // following types:
6403 // - Declarations
6404 //  * VarDecl
6405 //  * FunctionDecl
6406 // - Literals
6407 //  * CompoundLiteralExpr in C (and in global scope in C++)
6408 //  * StringLiteral
6409 //  * PredefinedExpr
6410 //  * ObjCStringLiteralExpr
6411 //  * ObjCEncodeExpr
6412 //  * AddrLabelExpr
6413 //  * BlockExpr
6414 //  * CallExpr for a MakeStringConstant builtin
6415 // - typeid(T) expressions, as TypeInfoLValues
6416 // - Locals and temporaries
6417 //  * MaterializeTemporaryExpr
6418 //  * Any Expr, with a CallIndex indicating the function in which the temporary
6419 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
6420 //    from the AST (FIXME).
6421 //  * A MaterializeTemporaryExpr that has static storage duration, with no
6422 //    CallIndex, for a lifetime-extended temporary.
6423 // plus an offset in bytes.
6424 //===----------------------------------------------------------------------===//
6425 namespace {
6426 class LValueExprEvaluator
6427   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
6428 public:
6429   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
6430     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
6431 
6432   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
6433   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
6434 
6435   bool VisitDeclRefExpr(const DeclRefExpr *E);
6436   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
6437   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
6438   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
6439   bool VisitMemberExpr(const MemberExpr *E);
6440   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
6441   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
6442   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
6443   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
6444   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
6445   bool VisitUnaryDeref(const UnaryOperator *E);
6446   bool VisitUnaryReal(const UnaryOperator *E);
6447   bool VisitUnaryImag(const UnaryOperator *E);
6448   bool VisitUnaryPreInc(const UnaryOperator *UO) {
6449     return VisitUnaryPreIncDec(UO);
6450   }
6451   bool VisitUnaryPreDec(const UnaryOperator *UO) {
6452     return VisitUnaryPreIncDec(UO);
6453   }
6454   bool VisitBinAssign(const BinaryOperator *BO);
6455   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
6456 
6457   bool VisitCastExpr(const CastExpr *E) {
6458     switch (E->getCastKind()) {
6459     default:
6460       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6461 
6462     case CK_LValueBitCast:
6463       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6464       if (!Visit(E->getSubExpr()))
6465         return false;
6466       Result.Designator.setInvalid();
6467       return true;
6468 
6469     case CK_BaseToDerived:
6470       if (!Visit(E->getSubExpr()))
6471         return false;
6472       return HandleBaseToDerivedCast(Info, E, Result);
6473 
6474     case CK_Dynamic:
6475       if (!Visit(E->getSubExpr()))
6476         return false;
6477       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
6478     }
6479   }
6480 };
6481 } // end anonymous namespace
6482 
6483 /// Evaluate an expression as an lvalue. This can be legitimately called on
6484 /// expressions which are not glvalues, in three cases:
6485 ///  * function designators in C, and
6486 ///  * "extern void" objects
6487 ///  * @selector() expressions in Objective-C
6488 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
6489                            bool InvalidBaseOK) {
6490   assert(E->isGLValue() || E->getType()->isFunctionType() ||
6491          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
6492   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
6493 }
6494 
6495 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
6496   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
6497     return Success(FD);
6498   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
6499     return VisitVarDecl(E, VD);
6500   if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
6501     return Visit(BD->getBinding());
6502   return Error(E);
6503 }
6504 
6505 
6506 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
6507 
6508   // If we are within a lambda's call operator, check whether the 'VD' referred
6509   // to within 'E' actually represents a lambda-capture that maps to a
6510   // data-member/field within the closure object, and if so, evaluate to the
6511   // field or what the field refers to.
6512   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
6513       isa<DeclRefExpr>(E) &&
6514       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
6515     // We don't always have a complete capture-map when checking or inferring if
6516     // the function call operator meets the requirements of a constexpr function
6517     // - but we don't need to evaluate the captures to determine constexprness
6518     // (dcl.constexpr C++17).
6519     if (Info.checkingPotentialConstantExpression())
6520       return false;
6521 
6522     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
6523       // Start with 'Result' referring to the complete closure object...
6524       Result = *Info.CurrentCall->This;
6525       // ... then update it to refer to the field of the closure object
6526       // that represents the capture.
6527       if (!HandleLValueMember(Info, E, Result, FD))
6528         return false;
6529       // And if the field is of reference type, update 'Result' to refer to what
6530       // the field refers to.
6531       if (FD->getType()->isReferenceType()) {
6532         APValue RVal;
6533         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
6534                                             RVal))
6535           return false;
6536         Result.setFrom(Info.Ctx, RVal);
6537       }
6538       return true;
6539     }
6540   }
6541   CallStackFrame *Frame = nullptr;
6542   if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
6543     // Only if a local variable was declared in the function currently being
6544     // evaluated, do we expect to be able to find its value in the current
6545     // frame. (Otherwise it was likely declared in an enclosing context and
6546     // could either have a valid evaluatable value (for e.g. a constexpr
6547     // variable) or be ill-formed (and trigger an appropriate evaluation
6548     // diagnostic)).
6549     if (Info.CurrentCall->Callee &&
6550         Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
6551       Frame = Info.CurrentCall;
6552     }
6553   }
6554 
6555   if (!VD->getType()->isReferenceType()) {
6556     if (Frame) {
6557       Result.set({VD, Frame->Index,
6558                   Info.CurrentCall->getCurrentTemporaryVersion(VD)});
6559       return true;
6560     }
6561     return Success(VD);
6562   }
6563 
6564   APValue *V;
6565   if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
6566     return false;
6567   if (!V->hasValue()) {
6568     // FIXME: Is it possible for V to be indeterminate here? If so, we should
6569     // adjust the diagnostic to say that.
6570     if (!Info.checkingPotentialConstantExpression())
6571       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
6572     return false;
6573   }
6574   return Success(*V, E);
6575 }
6576 
6577 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
6578     const MaterializeTemporaryExpr *E) {
6579   // Walk through the expression to find the materialized temporary itself.
6580   SmallVector<const Expr *, 2> CommaLHSs;
6581   SmallVector<SubobjectAdjustment, 2> Adjustments;
6582   const Expr *Inner = E->GetTemporaryExpr()->
6583       skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
6584 
6585   // If we passed any comma operators, evaluate their LHSs.
6586   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
6587     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
6588       return false;
6589 
6590   // A materialized temporary with static storage duration can appear within the
6591   // result of a constant expression evaluation, so we need to preserve its
6592   // value for use outside this evaluation.
6593   APValue *Value;
6594   if (E->getStorageDuration() == SD_Static) {
6595     Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
6596     *Value = APValue();
6597     Result.set(E);
6598   } else {
6599     Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
6600                              *Info.CurrentCall);
6601   }
6602 
6603   QualType Type = Inner->getType();
6604 
6605   // Materialize the temporary itself.
6606   if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
6607       (E->getStorageDuration() == SD_Static &&
6608        !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
6609     *Value = APValue();
6610     return false;
6611   }
6612 
6613   // Adjust our lvalue to refer to the desired subobject.
6614   for (unsigned I = Adjustments.size(); I != 0; /**/) {
6615     --I;
6616     switch (Adjustments[I].Kind) {
6617     case SubobjectAdjustment::DerivedToBaseAdjustment:
6618       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
6619                                 Type, Result))
6620         return false;
6621       Type = Adjustments[I].DerivedToBase.BasePath->getType();
6622       break;
6623 
6624     case SubobjectAdjustment::FieldAdjustment:
6625       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
6626         return false;
6627       Type = Adjustments[I].Field->getType();
6628       break;
6629 
6630     case SubobjectAdjustment::MemberPointerAdjustment:
6631       if (!HandleMemberPointerAccess(this->Info, Type, Result,
6632                                      Adjustments[I].Ptr.RHS))
6633         return false;
6634       Type = Adjustments[I].Ptr.MPT->getPointeeType();
6635       break;
6636     }
6637   }
6638 
6639   return true;
6640 }
6641 
6642 bool
6643 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
6644   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
6645          "lvalue compound literal in c++?");
6646   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
6647   // only see this when folding in C, so there's no standard to follow here.
6648   return Success(E);
6649 }
6650 
6651 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
6652   TypeInfoLValue TypeInfo;
6653 
6654   if (!E->isPotentiallyEvaluated()) {
6655     if (E->isTypeOperand())
6656       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
6657     else
6658       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
6659   } else {
6660     if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
6661       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
6662         << E->getExprOperand()->getType()
6663         << E->getExprOperand()->getSourceRange();
6664     }
6665 
6666     if (!Visit(E->getExprOperand()))
6667       return false;
6668 
6669     Optional<DynamicType> DynType =
6670         ComputeDynamicType(Info, E, Result, AK_TypeId);
6671     if (!DynType)
6672       return false;
6673 
6674     TypeInfo =
6675         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
6676   }
6677 
6678   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
6679 }
6680 
6681 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
6682   return Success(E);
6683 }
6684 
6685 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
6686   // Handle static data members.
6687   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
6688     VisitIgnoredBaseExpression(E->getBase());
6689     return VisitVarDecl(E, VD);
6690   }
6691 
6692   // Handle static member functions.
6693   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
6694     if (MD->isStatic()) {
6695       VisitIgnoredBaseExpression(E->getBase());
6696       return Success(MD);
6697     }
6698   }
6699 
6700   // Handle non-static data members.
6701   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
6702 }
6703 
6704 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
6705   // FIXME: Deal with vectors as array subscript bases.
6706   if (E->getBase()->getType()->isVectorType())
6707     return Error(E);
6708 
6709   bool Success = true;
6710   if (!evaluatePointer(E->getBase(), Result)) {
6711     if (!Info.noteFailure())
6712       return false;
6713     Success = false;
6714   }
6715 
6716   APSInt Index;
6717   if (!EvaluateInteger(E->getIdx(), Index, Info))
6718     return false;
6719 
6720   return Success &&
6721          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
6722 }
6723 
6724 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
6725   return evaluatePointer(E->getSubExpr(), Result);
6726 }
6727 
6728 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6729   if (!Visit(E->getSubExpr()))
6730     return false;
6731   // __real is a no-op on scalar lvalues.
6732   if (E->getSubExpr()->getType()->isAnyComplexType())
6733     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
6734   return true;
6735 }
6736 
6737 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6738   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
6739          "lvalue __imag__ on scalar?");
6740   if (!Visit(E->getSubExpr()))
6741     return false;
6742   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
6743   return true;
6744 }
6745 
6746 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
6747   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6748     return Error(UO);
6749 
6750   if (!this->Visit(UO->getSubExpr()))
6751     return false;
6752 
6753   return handleIncDec(
6754       this->Info, UO, Result, UO->getSubExpr()->getType(),
6755       UO->isIncrementOp(), nullptr);
6756 }
6757 
6758 bool LValueExprEvaluator::VisitCompoundAssignOperator(
6759     const CompoundAssignOperator *CAO) {
6760   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6761     return Error(CAO);
6762 
6763   APValue RHS;
6764 
6765   // The overall lvalue result is the result of evaluating the LHS.
6766   if (!this->Visit(CAO->getLHS())) {
6767     if (Info.noteFailure())
6768       Evaluate(RHS, this->Info, CAO->getRHS());
6769     return false;
6770   }
6771 
6772   if (!Evaluate(RHS, this->Info, CAO->getRHS()))
6773     return false;
6774 
6775   return handleCompoundAssignment(
6776       this->Info, CAO,
6777       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
6778       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
6779 }
6780 
6781 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
6782   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6783     return Error(E);
6784 
6785   APValue NewVal;
6786 
6787   if (!this->Visit(E->getLHS())) {
6788     if (Info.noteFailure())
6789       Evaluate(NewVal, this->Info, E->getRHS());
6790     return false;
6791   }
6792 
6793   if (!Evaluate(NewVal, this->Info, E->getRHS()))
6794     return false;
6795 
6796   if (Info.getLangOpts().CPlusPlus2a &&
6797       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
6798     return false;
6799 
6800   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
6801                           NewVal);
6802 }
6803 
6804 //===----------------------------------------------------------------------===//
6805 // Pointer Evaluation
6806 //===----------------------------------------------------------------------===//
6807 
6808 /// Attempts to compute the number of bytes available at the pointer
6809 /// returned by a function with the alloc_size attribute. Returns true if we
6810 /// were successful. Places an unsigned number into `Result`.
6811 ///
6812 /// This expects the given CallExpr to be a call to a function with an
6813 /// alloc_size attribute.
6814 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
6815                                             const CallExpr *Call,
6816                                             llvm::APInt &Result) {
6817   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
6818 
6819   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
6820   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
6821   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
6822   if (Call->getNumArgs() <= SizeArgNo)
6823     return false;
6824 
6825   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
6826     Expr::EvalResult ExprResult;
6827     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
6828       return false;
6829     Into = ExprResult.Val.getInt();
6830     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
6831       return false;
6832     Into = Into.zextOrSelf(BitsInSizeT);
6833     return true;
6834   };
6835 
6836   APSInt SizeOfElem;
6837   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
6838     return false;
6839 
6840   if (!AllocSize->getNumElemsParam().isValid()) {
6841     Result = std::move(SizeOfElem);
6842     return true;
6843   }
6844 
6845   APSInt NumberOfElems;
6846   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
6847   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
6848     return false;
6849 
6850   bool Overflow;
6851   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
6852   if (Overflow)
6853     return false;
6854 
6855   Result = std::move(BytesAvailable);
6856   return true;
6857 }
6858 
6859 /// Convenience function. LVal's base must be a call to an alloc_size
6860 /// function.
6861 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
6862                                             const LValue &LVal,
6863                                             llvm::APInt &Result) {
6864   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
6865          "Can't get the size of a non alloc_size function");
6866   const auto *Base = LVal.getLValueBase().get<const Expr *>();
6867   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
6868   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
6869 }
6870 
6871 /// Attempts to evaluate the given LValueBase as the result of a call to
6872 /// a function with the alloc_size attribute. If it was possible to do so, this
6873 /// function will return true, make Result's Base point to said function call,
6874 /// and mark Result's Base as invalid.
6875 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
6876                                       LValue &Result) {
6877   if (Base.isNull())
6878     return false;
6879 
6880   // Because we do no form of static analysis, we only support const variables.
6881   //
6882   // Additionally, we can't support parameters, nor can we support static
6883   // variables (in the latter case, use-before-assign isn't UB; in the former,
6884   // we have no clue what they'll be assigned to).
6885   const auto *VD =
6886       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
6887   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
6888     return false;
6889 
6890   const Expr *Init = VD->getAnyInitializer();
6891   if (!Init)
6892     return false;
6893 
6894   const Expr *E = Init->IgnoreParens();
6895   if (!tryUnwrapAllocSizeCall(E))
6896     return false;
6897 
6898   // Store E instead of E unwrapped so that the type of the LValue's base is
6899   // what the user wanted.
6900   Result.setInvalid(E);
6901 
6902   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
6903   Result.addUnsizedArray(Info, E, Pointee);
6904   return true;
6905 }
6906 
6907 namespace {
6908 class PointerExprEvaluator
6909   : public ExprEvaluatorBase<PointerExprEvaluator> {
6910   LValue &Result;
6911   bool InvalidBaseOK;
6912 
6913   bool Success(const Expr *E) {
6914     Result.set(E);
6915     return true;
6916   }
6917 
6918   bool evaluateLValue(const Expr *E, LValue &Result) {
6919     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
6920   }
6921 
6922   bool evaluatePointer(const Expr *E, LValue &Result) {
6923     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
6924   }
6925 
6926   bool visitNonBuiltinCallExpr(const CallExpr *E);
6927 public:
6928 
6929   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
6930       : ExprEvaluatorBaseTy(info), Result(Result),
6931         InvalidBaseOK(InvalidBaseOK) {}
6932 
6933   bool Success(const APValue &V, const Expr *E) {
6934     Result.setFrom(Info.Ctx, V);
6935     return true;
6936   }
6937   bool ZeroInitialization(const Expr *E) {
6938     auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
6939     Result.setNull(E->getType(), TargetVal);
6940     return true;
6941   }
6942 
6943   bool VisitBinaryOperator(const BinaryOperator *E);
6944   bool VisitCastExpr(const CastExpr* E);
6945   bool VisitUnaryAddrOf(const UnaryOperator *E);
6946   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
6947       { return Success(E); }
6948   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
6949     if (E->isExpressibleAsConstantInitializer())
6950       return Success(E);
6951     if (Info.noteFailure())
6952       EvaluateIgnoredValue(Info, E->getSubExpr());
6953     return Error(E);
6954   }
6955   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
6956       { return Success(E); }
6957   bool VisitCallExpr(const CallExpr *E);
6958   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
6959   bool VisitBlockExpr(const BlockExpr *E) {
6960     if (!E->getBlockDecl()->hasCaptures())
6961       return Success(E);
6962     return Error(E);
6963   }
6964   bool VisitCXXThisExpr(const CXXThisExpr *E) {
6965     // Can't look at 'this' when checking a potential constant expression.
6966     if (Info.checkingPotentialConstantExpression())
6967       return false;
6968     if (!Info.CurrentCall->This) {
6969       if (Info.getLangOpts().CPlusPlus11)
6970         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
6971       else
6972         Info.FFDiag(E);
6973       return false;
6974     }
6975     Result = *Info.CurrentCall->This;
6976     // If we are inside a lambda's call operator, the 'this' expression refers
6977     // to the enclosing '*this' object (either by value or reference) which is
6978     // either copied into the closure object's field that represents the '*this'
6979     // or refers to '*this'.
6980     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
6981       // Update 'Result' to refer to the data member/field of the closure object
6982       // that represents the '*this' capture.
6983       if (!HandleLValueMember(Info, E, Result,
6984                              Info.CurrentCall->LambdaThisCaptureField))
6985         return false;
6986       // If we captured '*this' by reference, replace the field with its referent.
6987       if (Info.CurrentCall->LambdaThisCaptureField->getType()
6988               ->isPointerType()) {
6989         APValue RVal;
6990         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
6991                                             RVal))
6992           return false;
6993 
6994         Result.setFrom(Info.Ctx, RVal);
6995       }
6996     }
6997     return true;
6998   }
6999 
7000   bool VisitSourceLocExpr(const SourceLocExpr *E) {
7001     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
7002     APValue LValResult = E->EvaluateInContext(
7003         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
7004     Result.setFrom(Info.Ctx, LValResult);
7005     return true;
7006   }
7007 
7008   // FIXME: Missing: @protocol, @selector
7009 };
7010 } // end anonymous namespace
7011 
7012 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
7013                             bool InvalidBaseOK) {
7014   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7015   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
7016 }
7017 
7018 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
7019   if (E->getOpcode() != BO_Add &&
7020       E->getOpcode() != BO_Sub)
7021     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7022 
7023   const Expr *PExp = E->getLHS();
7024   const Expr *IExp = E->getRHS();
7025   if (IExp->getType()->isPointerType())
7026     std::swap(PExp, IExp);
7027 
7028   bool EvalPtrOK = evaluatePointer(PExp, Result);
7029   if (!EvalPtrOK && !Info.noteFailure())
7030     return false;
7031 
7032   llvm::APSInt Offset;
7033   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
7034     return false;
7035 
7036   if (E->getOpcode() == BO_Sub)
7037     negateAsSigned(Offset);
7038 
7039   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
7040   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
7041 }
7042 
7043 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
7044   return evaluateLValue(E->getSubExpr(), Result);
7045 }
7046 
7047 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7048   const Expr *SubExpr = E->getSubExpr();
7049 
7050   switch (E->getCastKind()) {
7051   default:
7052     break;
7053   case CK_BitCast:
7054   case CK_CPointerToObjCPointerCast:
7055   case CK_BlockPointerToObjCPointerCast:
7056   case CK_AnyPointerToBlockPointerCast:
7057   case CK_AddressSpaceConversion:
7058     if (!Visit(SubExpr))
7059       return false;
7060     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
7061     // permitted in constant expressions in C++11. Bitcasts from cv void* are
7062     // also static_casts, but we disallow them as a resolution to DR1312.
7063     if (!E->getType()->isVoidPointerType()) {
7064       Result.Designator.setInvalid();
7065       if (SubExpr->getType()->isVoidPointerType())
7066         CCEDiag(E, diag::note_constexpr_invalid_cast)
7067           << 3 << SubExpr->getType();
7068       else
7069         CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7070     }
7071     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
7072       ZeroInitialization(E);
7073     return true;
7074 
7075   case CK_DerivedToBase:
7076   case CK_UncheckedDerivedToBase:
7077     if (!evaluatePointer(E->getSubExpr(), Result))
7078       return false;
7079     if (!Result.Base && Result.Offset.isZero())
7080       return true;
7081 
7082     // Now figure out the necessary offset to add to the base LV to get from
7083     // the derived class to the base class.
7084     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
7085                                   castAs<PointerType>()->getPointeeType(),
7086                                 Result);
7087 
7088   case CK_BaseToDerived:
7089     if (!Visit(E->getSubExpr()))
7090       return false;
7091     if (!Result.Base && Result.Offset.isZero())
7092       return true;
7093     return HandleBaseToDerivedCast(Info, E, Result);
7094 
7095   case CK_Dynamic:
7096     if (!Visit(E->getSubExpr()))
7097       return false;
7098     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
7099 
7100   case CK_NullToPointer:
7101     VisitIgnoredValue(E->getSubExpr());
7102     return ZeroInitialization(E);
7103 
7104   case CK_IntegralToPointer: {
7105     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7106 
7107     APValue Value;
7108     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
7109       break;
7110 
7111     if (Value.isInt()) {
7112       unsigned Size = Info.Ctx.getTypeSize(E->getType());
7113       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
7114       Result.Base = (Expr*)nullptr;
7115       Result.InvalidBase = false;
7116       Result.Offset = CharUnits::fromQuantity(N);
7117       Result.Designator.setInvalid();
7118       Result.IsNullPtr = false;
7119       return true;
7120     } else {
7121       // Cast is of an lvalue, no need to change value.
7122       Result.setFrom(Info.Ctx, Value);
7123       return true;
7124     }
7125   }
7126 
7127   case CK_ArrayToPointerDecay: {
7128     if (SubExpr->isGLValue()) {
7129       if (!evaluateLValue(SubExpr, Result))
7130         return false;
7131     } else {
7132       APValue &Value = createTemporary(SubExpr, false, Result,
7133                                        *Info.CurrentCall);
7134       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
7135         return false;
7136     }
7137     // The result is a pointer to the first element of the array.
7138     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
7139     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
7140       Result.addArray(Info, E, CAT);
7141     else
7142       Result.addUnsizedArray(Info, E, AT->getElementType());
7143     return true;
7144   }
7145 
7146   case CK_FunctionToPointerDecay:
7147     return evaluateLValue(SubExpr, Result);
7148 
7149   case CK_LValueToRValue: {
7150     LValue LVal;
7151     if (!evaluateLValue(E->getSubExpr(), LVal))
7152       return false;
7153 
7154     APValue RVal;
7155     // Note, we use the subexpression's type in order to retain cv-qualifiers.
7156     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7157                                         LVal, RVal))
7158       return InvalidBaseOK &&
7159              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
7160     return Success(RVal, E);
7161   }
7162   }
7163 
7164   return ExprEvaluatorBaseTy::VisitCastExpr(E);
7165 }
7166 
7167 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
7168                                 UnaryExprOrTypeTrait ExprKind) {
7169   // C++ [expr.alignof]p3:
7170   //     When alignof is applied to a reference type, the result is the
7171   //     alignment of the referenced type.
7172   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
7173     T = Ref->getPointeeType();
7174 
7175   if (T.getQualifiers().hasUnaligned())
7176     return CharUnits::One();
7177 
7178   const bool AlignOfReturnsPreferred =
7179       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
7180 
7181   // __alignof is defined to return the preferred alignment.
7182   // Before 8, clang returned the preferred alignment for alignof and _Alignof
7183   // as well.
7184   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
7185     return Info.Ctx.toCharUnitsFromBits(
7186       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
7187   // alignof and _Alignof are defined to return the ABI alignment.
7188   else if (ExprKind == UETT_AlignOf)
7189     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
7190   else
7191     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
7192 }
7193 
7194 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
7195                                 UnaryExprOrTypeTrait ExprKind) {
7196   E = E->IgnoreParens();
7197 
7198   // The kinds of expressions that we have special-case logic here for
7199   // should be kept up to date with the special checks for those
7200   // expressions in Sema.
7201 
7202   // alignof decl is always accepted, even if it doesn't make sense: we default
7203   // to 1 in those cases.
7204   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7205     return Info.Ctx.getDeclAlign(DRE->getDecl(),
7206                                  /*RefAsPointee*/true);
7207 
7208   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
7209     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
7210                                  /*RefAsPointee*/true);
7211 
7212   return GetAlignOfType(Info, E->getType(), ExprKind);
7213 }
7214 
7215 // To be clear: this happily visits unsupported builtins. Better name welcomed.
7216 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
7217   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
7218     return true;
7219 
7220   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
7221     return false;
7222 
7223   Result.setInvalid(E);
7224   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
7225   Result.addUnsizedArray(Info, E, PointeeTy);
7226   return true;
7227 }
7228 
7229 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
7230   if (IsStringLiteralCall(E))
7231     return Success(E);
7232 
7233   if (unsigned BuiltinOp = E->getBuiltinCallee())
7234     return VisitBuiltinCallExpr(E, BuiltinOp);
7235 
7236   return visitNonBuiltinCallExpr(E);
7237 }
7238 
7239 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7240                                                 unsigned BuiltinOp) {
7241   switch (BuiltinOp) {
7242   case Builtin::BI__builtin_addressof:
7243     return evaluateLValue(E->getArg(0), Result);
7244   case Builtin::BI__builtin_assume_aligned: {
7245     // We need to be very careful here because: if the pointer does not have the
7246     // asserted alignment, then the behavior is undefined, and undefined
7247     // behavior is non-constant.
7248     if (!evaluatePointer(E->getArg(0), Result))
7249       return false;
7250 
7251     LValue OffsetResult(Result);
7252     APSInt Alignment;
7253     if (!EvaluateInteger(E->getArg(1), Alignment, Info))
7254       return false;
7255     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
7256 
7257     if (E->getNumArgs() > 2) {
7258       APSInt Offset;
7259       if (!EvaluateInteger(E->getArg(2), Offset, Info))
7260         return false;
7261 
7262       int64_t AdditionalOffset = -Offset.getZExtValue();
7263       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
7264     }
7265 
7266     // If there is a base object, then it must have the correct alignment.
7267     if (OffsetResult.Base) {
7268       CharUnits BaseAlignment;
7269       if (const ValueDecl *VD =
7270           OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
7271         BaseAlignment = Info.Ctx.getDeclAlign(VD);
7272       } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
7273         BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
7274       } else {
7275         BaseAlignment = GetAlignOfType(
7276             Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
7277       }
7278 
7279       if (BaseAlignment < Align) {
7280         Result.Designator.setInvalid();
7281         // FIXME: Add support to Diagnostic for long / long long.
7282         CCEDiag(E->getArg(0),
7283                 diag::note_constexpr_baa_insufficient_alignment) << 0
7284           << (unsigned)BaseAlignment.getQuantity()
7285           << (unsigned)Align.getQuantity();
7286         return false;
7287       }
7288     }
7289 
7290     // The offset must also have the correct alignment.
7291     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
7292       Result.Designator.setInvalid();
7293 
7294       (OffsetResult.Base
7295            ? CCEDiag(E->getArg(0),
7296                      diag::note_constexpr_baa_insufficient_alignment) << 1
7297            : CCEDiag(E->getArg(0),
7298                      diag::note_constexpr_baa_value_insufficient_alignment))
7299         << (int)OffsetResult.Offset.getQuantity()
7300         << (unsigned)Align.getQuantity();
7301       return false;
7302     }
7303 
7304     return true;
7305   }
7306   case Builtin::BI__builtin_launder:
7307     return evaluatePointer(E->getArg(0), Result);
7308   case Builtin::BIstrchr:
7309   case Builtin::BIwcschr:
7310   case Builtin::BImemchr:
7311   case Builtin::BIwmemchr:
7312     if (Info.getLangOpts().CPlusPlus11)
7313       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7314         << /*isConstexpr*/0 << /*isConstructor*/0
7315         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7316     else
7317       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7318     LLVM_FALLTHROUGH;
7319   case Builtin::BI__builtin_strchr:
7320   case Builtin::BI__builtin_wcschr:
7321   case Builtin::BI__builtin_memchr:
7322   case Builtin::BI__builtin_char_memchr:
7323   case Builtin::BI__builtin_wmemchr: {
7324     if (!Visit(E->getArg(0)))
7325       return false;
7326     APSInt Desired;
7327     if (!EvaluateInteger(E->getArg(1), Desired, Info))
7328       return false;
7329     uint64_t MaxLength = uint64_t(-1);
7330     if (BuiltinOp != Builtin::BIstrchr &&
7331         BuiltinOp != Builtin::BIwcschr &&
7332         BuiltinOp != Builtin::BI__builtin_strchr &&
7333         BuiltinOp != Builtin::BI__builtin_wcschr) {
7334       APSInt N;
7335       if (!EvaluateInteger(E->getArg(2), N, Info))
7336         return false;
7337       MaxLength = N.getExtValue();
7338     }
7339     // We cannot find the value if there are no candidates to match against.
7340     if (MaxLength == 0u)
7341       return ZeroInitialization(E);
7342     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
7343         Result.Designator.Invalid)
7344       return false;
7345     QualType CharTy = Result.Designator.getType(Info.Ctx);
7346     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
7347                      BuiltinOp == Builtin::BI__builtin_memchr;
7348     assert(IsRawByte ||
7349            Info.Ctx.hasSameUnqualifiedType(
7350                CharTy, E->getArg(0)->getType()->getPointeeType()));
7351     // Pointers to const void may point to objects of incomplete type.
7352     if (IsRawByte && CharTy->isIncompleteType()) {
7353       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
7354       return false;
7355     }
7356     // Give up on byte-oriented matching against multibyte elements.
7357     // FIXME: We can compare the bytes in the correct order.
7358     if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
7359       return false;
7360     // Figure out what value we're actually looking for (after converting to
7361     // the corresponding unsigned type if necessary).
7362     uint64_t DesiredVal;
7363     bool StopAtNull = false;
7364     switch (BuiltinOp) {
7365     case Builtin::BIstrchr:
7366     case Builtin::BI__builtin_strchr:
7367       // strchr compares directly to the passed integer, and therefore
7368       // always fails if given an int that is not a char.
7369       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
7370                                                   E->getArg(1)->getType(),
7371                                                   Desired),
7372                                Desired))
7373         return ZeroInitialization(E);
7374       StopAtNull = true;
7375       LLVM_FALLTHROUGH;
7376     case Builtin::BImemchr:
7377     case Builtin::BI__builtin_memchr:
7378     case Builtin::BI__builtin_char_memchr:
7379       // memchr compares by converting both sides to unsigned char. That's also
7380       // correct for strchr if we get this far (to cope with plain char being
7381       // unsigned in the strchr case).
7382       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
7383       break;
7384 
7385     case Builtin::BIwcschr:
7386     case Builtin::BI__builtin_wcschr:
7387       StopAtNull = true;
7388       LLVM_FALLTHROUGH;
7389     case Builtin::BIwmemchr:
7390     case Builtin::BI__builtin_wmemchr:
7391       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
7392       DesiredVal = Desired.getZExtValue();
7393       break;
7394     }
7395 
7396     for (; MaxLength; --MaxLength) {
7397       APValue Char;
7398       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
7399           !Char.isInt())
7400         return false;
7401       if (Char.getInt().getZExtValue() == DesiredVal)
7402         return true;
7403       if (StopAtNull && !Char.getInt())
7404         break;
7405       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
7406         return false;
7407     }
7408     // Not found: return nullptr.
7409     return ZeroInitialization(E);
7410   }
7411 
7412   case Builtin::BImemcpy:
7413   case Builtin::BImemmove:
7414   case Builtin::BIwmemcpy:
7415   case Builtin::BIwmemmove:
7416     if (Info.getLangOpts().CPlusPlus11)
7417       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7418         << /*isConstexpr*/0 << /*isConstructor*/0
7419         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7420     else
7421       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7422     LLVM_FALLTHROUGH;
7423   case Builtin::BI__builtin_memcpy:
7424   case Builtin::BI__builtin_memmove:
7425   case Builtin::BI__builtin_wmemcpy:
7426   case Builtin::BI__builtin_wmemmove: {
7427     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
7428                  BuiltinOp == Builtin::BIwmemmove ||
7429                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
7430                  BuiltinOp == Builtin::BI__builtin_wmemmove;
7431     bool Move = BuiltinOp == Builtin::BImemmove ||
7432                 BuiltinOp == Builtin::BIwmemmove ||
7433                 BuiltinOp == Builtin::BI__builtin_memmove ||
7434                 BuiltinOp == Builtin::BI__builtin_wmemmove;
7435 
7436     // The result of mem* is the first argument.
7437     if (!Visit(E->getArg(0)))
7438       return false;
7439     LValue Dest = Result;
7440 
7441     LValue Src;
7442     if (!EvaluatePointer(E->getArg(1), Src, Info))
7443       return false;
7444 
7445     APSInt N;
7446     if (!EvaluateInteger(E->getArg(2), N, Info))
7447       return false;
7448     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
7449 
7450     // If the size is zero, we treat this as always being a valid no-op.
7451     // (Even if one of the src and dest pointers is null.)
7452     if (!N)
7453       return true;
7454 
7455     // Otherwise, if either of the operands is null, we can't proceed. Don't
7456     // try to determine the type of the copied objects, because there aren't
7457     // any.
7458     if (!Src.Base || !Dest.Base) {
7459       APValue Val;
7460       (!Src.Base ? Src : Dest).moveInto(Val);
7461       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
7462           << Move << WChar << !!Src.Base
7463           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
7464       return false;
7465     }
7466     if (Src.Designator.Invalid || Dest.Designator.Invalid)
7467       return false;
7468 
7469     // We require that Src and Dest are both pointers to arrays of
7470     // trivially-copyable type. (For the wide version, the designator will be
7471     // invalid if the designated object is not a wchar_t.)
7472     QualType T = Dest.Designator.getType(Info.Ctx);
7473     QualType SrcT = Src.Designator.getType(Info.Ctx);
7474     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
7475       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
7476       return false;
7477     }
7478     if (T->isIncompleteType()) {
7479       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
7480       return false;
7481     }
7482     if (!T.isTriviallyCopyableType(Info.Ctx)) {
7483       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
7484       return false;
7485     }
7486 
7487     // Figure out how many T's we're copying.
7488     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
7489     if (!WChar) {
7490       uint64_t Remainder;
7491       llvm::APInt OrigN = N;
7492       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
7493       if (Remainder) {
7494         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
7495             << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
7496             << (unsigned)TSize;
7497         return false;
7498       }
7499     }
7500 
7501     // Check that the copying will remain within the arrays, just so that we
7502     // can give a more meaningful diagnostic. This implicitly also checks that
7503     // N fits into 64 bits.
7504     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
7505     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
7506     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
7507       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
7508           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
7509           << N.toString(10, /*Signed*/false);
7510       return false;
7511     }
7512     uint64_t NElems = N.getZExtValue();
7513     uint64_t NBytes = NElems * TSize;
7514 
7515     // Check for overlap.
7516     int Direction = 1;
7517     if (HasSameBase(Src, Dest)) {
7518       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
7519       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
7520       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
7521         // Dest is inside the source region.
7522         if (!Move) {
7523           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
7524           return false;
7525         }
7526         // For memmove and friends, copy backwards.
7527         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
7528             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
7529           return false;
7530         Direction = -1;
7531       } else if (!Move && SrcOffset >= DestOffset &&
7532                  SrcOffset - DestOffset < NBytes) {
7533         // Src is inside the destination region for memcpy: invalid.
7534         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
7535         return false;
7536       }
7537     }
7538 
7539     while (true) {
7540       APValue Val;
7541       // FIXME: Set WantObjectRepresentation to true if we're copying a
7542       // char-like type?
7543       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
7544           !handleAssignment(Info, E, Dest, T, Val))
7545         return false;
7546       // Do not iterate past the last element; if we're copying backwards, that
7547       // might take us off the start of the array.
7548       if (--NElems == 0)
7549         return true;
7550       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
7551           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
7552         return false;
7553     }
7554   }
7555 
7556   default:
7557     return visitNonBuiltinCallExpr(E);
7558   }
7559 }
7560 
7561 //===----------------------------------------------------------------------===//
7562 // Member Pointer Evaluation
7563 //===----------------------------------------------------------------------===//
7564 
7565 namespace {
7566 class MemberPointerExprEvaluator
7567   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
7568   MemberPtr &Result;
7569 
7570   bool Success(const ValueDecl *D) {
7571     Result = MemberPtr(D);
7572     return true;
7573   }
7574 public:
7575 
7576   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
7577     : ExprEvaluatorBaseTy(Info), Result(Result) {}
7578 
7579   bool Success(const APValue &V, const Expr *E) {
7580     Result.setFrom(V);
7581     return true;
7582   }
7583   bool ZeroInitialization(const Expr *E) {
7584     return Success((const ValueDecl*)nullptr);
7585   }
7586 
7587   bool VisitCastExpr(const CastExpr *E);
7588   bool VisitUnaryAddrOf(const UnaryOperator *E);
7589 };
7590 } // end anonymous namespace
7591 
7592 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
7593                                   EvalInfo &Info) {
7594   assert(E->isRValue() && E->getType()->isMemberPointerType());
7595   return MemberPointerExprEvaluator(Info, Result).Visit(E);
7596 }
7597 
7598 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7599   switch (E->getCastKind()) {
7600   default:
7601     return ExprEvaluatorBaseTy::VisitCastExpr(E);
7602 
7603   case CK_NullToMemberPointer:
7604     VisitIgnoredValue(E->getSubExpr());
7605     return ZeroInitialization(E);
7606 
7607   case CK_BaseToDerivedMemberPointer: {
7608     if (!Visit(E->getSubExpr()))
7609       return false;
7610     if (E->path_empty())
7611       return true;
7612     // Base-to-derived member pointer casts store the path in derived-to-base
7613     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
7614     // the wrong end of the derived->base arc, so stagger the path by one class.
7615     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
7616     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
7617          PathI != PathE; ++PathI) {
7618       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7619       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
7620       if (!Result.castToDerived(Derived))
7621         return Error(E);
7622     }
7623     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
7624     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
7625       return Error(E);
7626     return true;
7627   }
7628 
7629   case CK_DerivedToBaseMemberPointer:
7630     if (!Visit(E->getSubExpr()))
7631       return false;
7632     for (CastExpr::path_const_iterator PathI = E->path_begin(),
7633          PathE = E->path_end(); PathI != PathE; ++PathI) {
7634       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7635       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7636       if (!Result.castToBase(Base))
7637         return Error(E);
7638     }
7639     return true;
7640   }
7641 }
7642 
7643 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
7644   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
7645   // member can be formed.
7646   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
7647 }
7648 
7649 //===----------------------------------------------------------------------===//
7650 // Record Evaluation
7651 //===----------------------------------------------------------------------===//
7652 
7653 namespace {
7654   class RecordExprEvaluator
7655   : public ExprEvaluatorBase<RecordExprEvaluator> {
7656     const LValue &This;
7657     APValue &Result;
7658   public:
7659 
7660     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
7661       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
7662 
7663     bool Success(const APValue &V, const Expr *E) {
7664       Result = V;
7665       return true;
7666     }
7667     bool ZeroInitialization(const Expr *E) {
7668       return ZeroInitialization(E, E->getType());
7669     }
7670     bool ZeroInitialization(const Expr *E, QualType T);
7671 
7672     bool VisitCallExpr(const CallExpr *E) {
7673       return handleCallExpr(E, Result, &This);
7674     }
7675     bool VisitCastExpr(const CastExpr *E);
7676     bool VisitInitListExpr(const InitListExpr *E);
7677     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
7678       return VisitCXXConstructExpr(E, E->getType());
7679     }
7680     bool VisitLambdaExpr(const LambdaExpr *E);
7681     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
7682     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
7683     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
7684 
7685     bool VisitBinCmp(const BinaryOperator *E);
7686   };
7687 }
7688 
7689 /// Perform zero-initialization on an object of non-union class type.
7690 /// C++11 [dcl.init]p5:
7691 ///  To zero-initialize an object or reference of type T means:
7692 ///    [...]
7693 ///    -- if T is a (possibly cv-qualified) non-union class type,
7694 ///       each non-static data member and each base-class subobject is
7695 ///       zero-initialized
7696 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
7697                                           const RecordDecl *RD,
7698                                           const LValue &This, APValue &Result) {
7699   assert(!RD->isUnion() && "Expected non-union class type");
7700   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
7701   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
7702                    std::distance(RD->field_begin(), RD->field_end()));
7703 
7704   if (RD->isInvalidDecl()) return false;
7705   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7706 
7707   if (CD) {
7708     unsigned Index = 0;
7709     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
7710            End = CD->bases_end(); I != End; ++I, ++Index) {
7711       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
7712       LValue Subobject = This;
7713       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
7714         return false;
7715       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
7716                                          Result.getStructBase(Index)))
7717         return false;
7718     }
7719   }
7720 
7721   for (const auto *I : RD->fields()) {
7722     // -- if T is a reference type, no initialization is performed.
7723     if (I->getType()->isReferenceType())
7724       continue;
7725 
7726     LValue Subobject = This;
7727     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
7728       return false;
7729 
7730     ImplicitValueInitExpr VIE(I->getType());
7731     if (!EvaluateInPlace(
7732           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
7733       return false;
7734   }
7735 
7736   return true;
7737 }
7738 
7739 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
7740   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
7741   if (RD->isInvalidDecl()) return false;
7742   if (RD->isUnion()) {
7743     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
7744     // object's first non-static named data member is zero-initialized
7745     RecordDecl::field_iterator I = RD->field_begin();
7746     if (I == RD->field_end()) {
7747       Result = APValue((const FieldDecl*)nullptr);
7748       return true;
7749     }
7750 
7751     LValue Subobject = This;
7752     if (!HandleLValueMember(Info, E, Subobject, *I))
7753       return false;
7754     Result = APValue(*I);
7755     ImplicitValueInitExpr VIE(I->getType());
7756     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
7757   }
7758 
7759   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
7760     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
7761     return false;
7762   }
7763 
7764   return HandleClassZeroInitialization(Info, E, RD, This, Result);
7765 }
7766 
7767 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
7768   switch (E->getCastKind()) {
7769   default:
7770     return ExprEvaluatorBaseTy::VisitCastExpr(E);
7771 
7772   case CK_ConstructorConversion:
7773     return Visit(E->getSubExpr());
7774 
7775   case CK_DerivedToBase:
7776   case CK_UncheckedDerivedToBase: {
7777     APValue DerivedObject;
7778     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
7779       return false;
7780     if (!DerivedObject.isStruct())
7781       return Error(E->getSubExpr());
7782 
7783     // Derived-to-base rvalue conversion: just slice off the derived part.
7784     APValue *Value = &DerivedObject;
7785     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
7786     for (CastExpr::path_const_iterator PathI = E->path_begin(),
7787          PathE = E->path_end(); PathI != PathE; ++PathI) {
7788       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
7789       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7790       Value = &Value->getStructBase(getBaseIndex(RD, Base));
7791       RD = Base;
7792     }
7793     Result = *Value;
7794     return true;
7795   }
7796   }
7797 }
7798 
7799 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7800   if (E->isTransparent())
7801     return Visit(E->getInit(0));
7802 
7803   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
7804   if (RD->isInvalidDecl()) return false;
7805   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7806   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
7807 
7808   EvalInfo::EvaluatingConstructorRAII EvalObj(
7809       Info,
7810       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
7811       CXXRD && CXXRD->getNumBases());
7812 
7813   if (RD->isUnion()) {
7814     const FieldDecl *Field = E->getInitializedFieldInUnion();
7815     Result = APValue(Field);
7816     if (!Field)
7817       return true;
7818 
7819     // If the initializer list for a union does not contain any elements, the
7820     // first element of the union is value-initialized.
7821     // FIXME: The element should be initialized from an initializer list.
7822     //        Is this difference ever observable for initializer lists which
7823     //        we don't build?
7824     ImplicitValueInitExpr VIE(Field->getType());
7825     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
7826 
7827     LValue Subobject = This;
7828     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
7829       return false;
7830 
7831     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7832     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7833                                   isa<CXXDefaultInitExpr>(InitExpr));
7834 
7835     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
7836   }
7837 
7838   if (!Result.hasValue())
7839     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
7840                      std::distance(RD->field_begin(), RD->field_end()));
7841   unsigned ElementNo = 0;
7842   bool Success = true;
7843 
7844   // Initialize base classes.
7845   if (CXXRD && CXXRD->getNumBases()) {
7846     for (const auto &Base : CXXRD->bases()) {
7847       assert(ElementNo < E->getNumInits() && "missing init for base class");
7848       const Expr *Init = E->getInit(ElementNo);
7849 
7850       LValue Subobject = This;
7851       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
7852         return false;
7853 
7854       APValue &FieldVal = Result.getStructBase(ElementNo);
7855       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
7856         if (!Info.noteFailure())
7857           return false;
7858         Success = false;
7859       }
7860       ++ElementNo;
7861     }
7862 
7863     EvalObj.finishedConstructingBases();
7864   }
7865 
7866   // Initialize members.
7867   for (const auto *Field : RD->fields()) {
7868     // Anonymous bit-fields are not considered members of the class for
7869     // purposes of aggregate initialization.
7870     if (Field->isUnnamedBitfield())
7871       continue;
7872 
7873     LValue Subobject = This;
7874 
7875     bool HaveInit = ElementNo < E->getNumInits();
7876 
7877     // FIXME: Diagnostics here should point to the end of the initializer
7878     // list, not the start.
7879     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
7880                             Subobject, Field, &Layout))
7881       return false;
7882 
7883     // Perform an implicit value-initialization for members beyond the end of
7884     // the initializer list.
7885     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
7886     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
7887 
7888     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7889     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7890                                   isa<CXXDefaultInitExpr>(Init));
7891 
7892     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
7893     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
7894         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
7895                                                        FieldVal, Field))) {
7896       if (!Info.noteFailure())
7897         return false;
7898       Success = false;
7899     }
7900   }
7901 
7902   return Success;
7903 }
7904 
7905 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7906                                                 QualType T) {
7907   // Note that E's type is not necessarily the type of our class here; we might
7908   // be initializing an array element instead.
7909   const CXXConstructorDecl *FD = E->getConstructor();
7910   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
7911 
7912   bool ZeroInit = E->requiresZeroInitialization();
7913   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
7914     // If we've already performed zero-initialization, we're already done.
7915     if (Result.hasValue())
7916       return true;
7917 
7918     if (ZeroInit)
7919       return ZeroInitialization(E, T);
7920 
7921     Result = getDefaultInitValue(T);
7922     return true;
7923   }
7924 
7925   const FunctionDecl *Definition = nullptr;
7926   auto Body = FD->getBody(Definition);
7927 
7928   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
7929     return false;
7930 
7931   // Avoid materializing a temporary for an elidable copy/move constructor.
7932   if (E->isElidable() && !ZeroInit)
7933     if (const MaterializeTemporaryExpr *ME
7934           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
7935       return Visit(ME->GetTemporaryExpr());
7936 
7937   if (ZeroInit && !ZeroInitialization(E, T))
7938     return false;
7939 
7940   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7941   return HandleConstructorCall(E, This, Args,
7942                                cast<CXXConstructorDecl>(Definition), Info,
7943                                Result);
7944 }
7945 
7946 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
7947     const CXXInheritedCtorInitExpr *E) {
7948   if (!Info.CurrentCall) {
7949     assert(Info.checkingPotentialConstantExpression());
7950     return false;
7951   }
7952 
7953   const CXXConstructorDecl *FD = E->getConstructor();
7954   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
7955     return false;
7956 
7957   const FunctionDecl *Definition = nullptr;
7958   auto Body = FD->getBody(Definition);
7959 
7960   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
7961     return false;
7962 
7963   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
7964                                cast<CXXConstructorDecl>(Definition), Info,
7965                                Result);
7966 }
7967 
7968 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
7969     const CXXStdInitializerListExpr *E) {
7970   const ConstantArrayType *ArrayType =
7971       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
7972 
7973   LValue Array;
7974   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
7975     return false;
7976 
7977   // Get a pointer to the first element of the array.
7978   Array.addArray(Info, E, ArrayType);
7979 
7980   // FIXME: Perform the checks on the field types in SemaInit.
7981   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
7982   RecordDecl::field_iterator Field = Record->field_begin();
7983   if (Field == Record->field_end())
7984     return Error(E);
7985 
7986   // Start pointer.
7987   if (!Field->getType()->isPointerType() ||
7988       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
7989                             ArrayType->getElementType()))
7990     return Error(E);
7991 
7992   // FIXME: What if the initializer_list type has base classes, etc?
7993   Result = APValue(APValue::UninitStruct(), 0, 2);
7994   Array.moveInto(Result.getStructField(0));
7995 
7996   if (++Field == Record->field_end())
7997     return Error(E);
7998 
7999   if (Field->getType()->isPointerType() &&
8000       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
8001                            ArrayType->getElementType())) {
8002     // End pointer.
8003     if (!HandleLValueArrayAdjustment(Info, E, Array,
8004                                      ArrayType->getElementType(),
8005                                      ArrayType->getSize().getZExtValue()))
8006       return false;
8007     Array.moveInto(Result.getStructField(1));
8008   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
8009     // Length.
8010     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
8011   else
8012     return Error(E);
8013 
8014   if (++Field != Record->field_end())
8015     return Error(E);
8016 
8017   return true;
8018 }
8019 
8020 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
8021   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
8022   if (ClosureClass->isInvalidDecl()) return false;
8023 
8024   if (Info.checkingPotentialConstantExpression()) return true;
8025 
8026   const size_t NumFields =
8027       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
8028 
8029   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
8030                                             E->capture_init_end()) &&
8031          "The number of lambda capture initializers should equal the number of "
8032          "fields within the closure type");
8033 
8034   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
8035   // Iterate through all the lambda's closure object's fields and initialize
8036   // them.
8037   auto *CaptureInitIt = E->capture_init_begin();
8038   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
8039   bool Success = true;
8040   for (const auto *Field : ClosureClass->fields()) {
8041     assert(CaptureInitIt != E->capture_init_end());
8042     // Get the initializer for this field
8043     Expr *const CurFieldInit = *CaptureInitIt++;
8044 
8045     // If there is no initializer, either this is a VLA or an error has
8046     // occurred.
8047     if (!CurFieldInit)
8048       return Error(E);
8049 
8050     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
8051     if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
8052       if (!Info.keepEvaluatingAfterFailure())
8053         return false;
8054       Success = false;
8055     }
8056     ++CaptureIt;
8057   }
8058   return Success;
8059 }
8060 
8061 static bool EvaluateRecord(const Expr *E, const LValue &This,
8062                            APValue &Result, EvalInfo &Info) {
8063   assert(E->isRValue() && E->getType()->isRecordType() &&
8064          "can't evaluate expression as a record rvalue");
8065   return RecordExprEvaluator(Info, This, Result).Visit(E);
8066 }
8067 
8068 //===----------------------------------------------------------------------===//
8069 // Temporary Evaluation
8070 //
8071 // Temporaries are represented in the AST as rvalues, but generally behave like
8072 // lvalues. The full-object of which the temporary is a subobject is implicitly
8073 // materialized so that a reference can bind to it.
8074 //===----------------------------------------------------------------------===//
8075 namespace {
8076 class TemporaryExprEvaluator
8077   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
8078 public:
8079   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
8080     LValueExprEvaluatorBaseTy(Info, Result, false) {}
8081 
8082   /// Visit an expression which constructs the value of this temporary.
8083   bool VisitConstructExpr(const Expr *E) {
8084     APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
8085     return EvaluateInPlace(Value, Info, Result, E);
8086   }
8087 
8088   bool VisitCastExpr(const CastExpr *E) {
8089     switch (E->getCastKind()) {
8090     default:
8091       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8092 
8093     case CK_ConstructorConversion:
8094       return VisitConstructExpr(E->getSubExpr());
8095     }
8096   }
8097   bool VisitInitListExpr(const InitListExpr *E) {
8098     return VisitConstructExpr(E);
8099   }
8100   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
8101     return VisitConstructExpr(E);
8102   }
8103   bool VisitCallExpr(const CallExpr *E) {
8104     return VisitConstructExpr(E);
8105   }
8106   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
8107     return VisitConstructExpr(E);
8108   }
8109   bool VisitLambdaExpr(const LambdaExpr *E) {
8110     return VisitConstructExpr(E);
8111   }
8112 };
8113 } // end anonymous namespace
8114 
8115 /// Evaluate an expression of record type as a temporary.
8116 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
8117   assert(E->isRValue() && E->getType()->isRecordType());
8118   return TemporaryExprEvaluator(Info, Result).Visit(E);
8119 }
8120 
8121 //===----------------------------------------------------------------------===//
8122 // Vector Evaluation
8123 //===----------------------------------------------------------------------===//
8124 
8125 namespace {
8126   class VectorExprEvaluator
8127   : public ExprEvaluatorBase<VectorExprEvaluator> {
8128     APValue &Result;
8129   public:
8130 
8131     VectorExprEvaluator(EvalInfo &info, APValue &Result)
8132       : ExprEvaluatorBaseTy(info), Result(Result) {}
8133 
8134     bool Success(ArrayRef<APValue> V, const Expr *E) {
8135       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
8136       // FIXME: remove this APValue copy.
8137       Result = APValue(V.data(), V.size());
8138       return true;
8139     }
8140     bool Success(const APValue &V, const Expr *E) {
8141       assert(V.isVector());
8142       Result = V;
8143       return true;
8144     }
8145     bool ZeroInitialization(const Expr *E);
8146 
8147     bool VisitUnaryReal(const UnaryOperator *E)
8148       { return Visit(E->getSubExpr()); }
8149     bool VisitCastExpr(const CastExpr* E);
8150     bool VisitInitListExpr(const InitListExpr *E);
8151     bool VisitUnaryImag(const UnaryOperator *E);
8152     // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
8153     //                 binary comparisons, binary and/or/xor,
8154     //                 shufflevector, ExtVectorElementExpr
8155   };
8156 } // end anonymous namespace
8157 
8158 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
8159   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
8160   return VectorExprEvaluator(Info, Result).Visit(E);
8161 }
8162 
8163 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
8164   const VectorType *VTy = E->getType()->castAs<VectorType>();
8165   unsigned NElts = VTy->getNumElements();
8166 
8167   const Expr *SE = E->getSubExpr();
8168   QualType SETy = SE->getType();
8169 
8170   switch (E->getCastKind()) {
8171   case CK_VectorSplat: {
8172     APValue Val = APValue();
8173     if (SETy->isIntegerType()) {
8174       APSInt IntResult;
8175       if (!EvaluateInteger(SE, IntResult, Info))
8176         return false;
8177       Val = APValue(std::move(IntResult));
8178     } else if (SETy->isRealFloatingType()) {
8179       APFloat FloatResult(0.0);
8180       if (!EvaluateFloat(SE, FloatResult, Info))
8181         return false;
8182       Val = APValue(std::move(FloatResult));
8183     } else {
8184       return Error(E);
8185     }
8186 
8187     // Splat and create vector APValue.
8188     SmallVector<APValue, 4> Elts(NElts, Val);
8189     return Success(Elts, E);
8190   }
8191   case CK_BitCast: {
8192     // Evaluate the operand into an APInt we can extract from.
8193     llvm::APInt SValInt;
8194     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
8195       return false;
8196     // Extract the elements
8197     QualType EltTy = VTy->getElementType();
8198     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
8199     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8200     SmallVector<APValue, 4> Elts;
8201     if (EltTy->isRealFloatingType()) {
8202       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
8203       unsigned FloatEltSize = EltSize;
8204       if (&Sem == &APFloat::x87DoubleExtended())
8205         FloatEltSize = 80;
8206       for (unsigned i = 0; i < NElts; i++) {
8207         llvm::APInt Elt;
8208         if (BigEndian)
8209           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
8210         else
8211           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
8212         Elts.push_back(APValue(APFloat(Sem, Elt)));
8213       }
8214     } else if (EltTy->isIntegerType()) {
8215       for (unsigned i = 0; i < NElts; i++) {
8216         llvm::APInt Elt;
8217         if (BigEndian)
8218           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
8219         else
8220           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
8221         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
8222       }
8223     } else {
8224       return Error(E);
8225     }
8226     return Success(Elts, E);
8227   }
8228   default:
8229     return ExprEvaluatorBaseTy::VisitCastExpr(E);
8230   }
8231 }
8232 
8233 bool
8234 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8235   const VectorType *VT = E->getType()->castAs<VectorType>();
8236   unsigned NumInits = E->getNumInits();
8237   unsigned NumElements = VT->getNumElements();
8238 
8239   QualType EltTy = VT->getElementType();
8240   SmallVector<APValue, 4> Elements;
8241 
8242   // The number of initializers can be less than the number of
8243   // vector elements. For OpenCL, this can be due to nested vector
8244   // initialization. For GCC compatibility, missing trailing elements
8245   // should be initialized with zeroes.
8246   unsigned CountInits = 0, CountElts = 0;
8247   while (CountElts < NumElements) {
8248     // Handle nested vector initialization.
8249     if (CountInits < NumInits
8250         && E->getInit(CountInits)->getType()->isVectorType()) {
8251       APValue v;
8252       if (!EvaluateVector(E->getInit(CountInits), v, Info))
8253         return Error(E);
8254       unsigned vlen = v.getVectorLength();
8255       for (unsigned j = 0; j < vlen; j++)
8256         Elements.push_back(v.getVectorElt(j));
8257       CountElts += vlen;
8258     } else if (EltTy->isIntegerType()) {
8259       llvm::APSInt sInt(32);
8260       if (CountInits < NumInits) {
8261         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
8262           return false;
8263       } else // trailing integer zero.
8264         sInt = Info.Ctx.MakeIntValue(0, EltTy);
8265       Elements.push_back(APValue(sInt));
8266       CountElts++;
8267     } else {
8268       llvm::APFloat f(0.0);
8269       if (CountInits < NumInits) {
8270         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
8271           return false;
8272       } else // trailing float zero.
8273         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
8274       Elements.push_back(APValue(f));
8275       CountElts++;
8276     }
8277     CountInits++;
8278   }
8279   return Success(Elements, E);
8280 }
8281 
8282 bool
8283 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
8284   const VectorType *VT = E->getType()->getAs<VectorType>();
8285   QualType EltTy = VT->getElementType();
8286   APValue ZeroElement;
8287   if (EltTy->isIntegerType())
8288     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
8289   else
8290     ZeroElement =
8291         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
8292 
8293   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
8294   return Success(Elements, E);
8295 }
8296 
8297 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8298   VisitIgnoredValue(E->getSubExpr());
8299   return ZeroInitialization(E);
8300 }
8301 
8302 //===----------------------------------------------------------------------===//
8303 // Array Evaluation
8304 //===----------------------------------------------------------------------===//
8305 
8306 namespace {
8307   class ArrayExprEvaluator
8308   : public ExprEvaluatorBase<ArrayExprEvaluator> {
8309     const LValue &This;
8310     APValue &Result;
8311   public:
8312 
8313     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
8314       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
8315 
8316     bool Success(const APValue &V, const Expr *E) {
8317       assert(V.isArray() && "expected array");
8318       Result = V;
8319       return true;
8320     }
8321 
8322     bool ZeroInitialization(const Expr *E) {
8323       const ConstantArrayType *CAT =
8324           Info.Ctx.getAsConstantArrayType(E->getType());
8325       if (!CAT)
8326         return Error(E);
8327 
8328       Result = APValue(APValue::UninitArray(), 0,
8329                        CAT->getSize().getZExtValue());
8330       if (!Result.hasArrayFiller()) return true;
8331 
8332       // Zero-initialize all elements.
8333       LValue Subobject = This;
8334       Subobject.addArray(Info, E, CAT);
8335       ImplicitValueInitExpr VIE(CAT->getElementType());
8336       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
8337     }
8338 
8339     bool VisitCallExpr(const CallExpr *E) {
8340       return handleCallExpr(E, Result, &This);
8341     }
8342     bool VisitInitListExpr(const InitListExpr *E);
8343     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
8344     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
8345     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
8346                                const LValue &Subobject,
8347                                APValue *Value, QualType Type);
8348     bool VisitStringLiteral(const StringLiteral *E) {
8349       expandStringLiteral(Info, E, Result);
8350       return true;
8351     }
8352   };
8353 } // end anonymous namespace
8354 
8355 static bool EvaluateArray(const Expr *E, const LValue &This,
8356                           APValue &Result, EvalInfo &Info) {
8357   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
8358   return ArrayExprEvaluator(Info, This, Result).Visit(E);
8359 }
8360 
8361 // Return true iff the given array filler may depend on the element index.
8362 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
8363   // For now, just whitelist non-class value-initialization and initialization
8364   // lists comprised of them.
8365   if (isa<ImplicitValueInitExpr>(FillerExpr))
8366     return false;
8367   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
8368     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
8369       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
8370         return true;
8371     }
8372     return false;
8373   }
8374   return true;
8375 }
8376 
8377 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8378   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
8379   if (!CAT)
8380     return Error(E);
8381 
8382   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
8383   // an appropriately-typed string literal enclosed in braces.
8384   if (E->isStringLiteralInit())
8385     return Visit(E->getInit(0));
8386 
8387   bool Success = true;
8388 
8389   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
8390          "zero-initialized array shouldn't have any initialized elts");
8391   APValue Filler;
8392   if (Result.isArray() && Result.hasArrayFiller())
8393     Filler = Result.getArrayFiller();
8394 
8395   unsigned NumEltsToInit = E->getNumInits();
8396   unsigned NumElts = CAT->getSize().getZExtValue();
8397   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
8398 
8399   // If the initializer might depend on the array index, run it for each
8400   // array element.
8401   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
8402     NumEltsToInit = NumElts;
8403 
8404   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
8405                           << NumEltsToInit << ".\n");
8406 
8407   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
8408 
8409   // If the array was previously zero-initialized, preserve the
8410   // zero-initialized values.
8411   if (Filler.hasValue()) {
8412     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
8413       Result.getArrayInitializedElt(I) = Filler;
8414     if (Result.hasArrayFiller())
8415       Result.getArrayFiller() = Filler;
8416   }
8417 
8418   LValue Subobject = This;
8419   Subobject.addArray(Info, E, CAT);
8420   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
8421     const Expr *Init =
8422         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
8423     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
8424                          Info, Subobject, Init) ||
8425         !HandleLValueArrayAdjustment(Info, Init, Subobject,
8426                                      CAT->getElementType(), 1)) {
8427       if (!Info.noteFailure())
8428         return false;
8429       Success = false;
8430     }
8431   }
8432 
8433   if (!Result.hasArrayFiller())
8434     return Success;
8435 
8436   // If we get here, we have a trivial filler, which we can just evaluate
8437   // once and splat over the rest of the array elements.
8438   assert(FillerExpr && "no array filler for incomplete init list");
8439   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
8440                          FillerExpr) && Success;
8441 }
8442 
8443 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
8444   if (E->getCommonExpr() &&
8445       !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
8446                 Info, E->getCommonExpr()->getSourceExpr()))
8447     return false;
8448 
8449   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
8450 
8451   uint64_t Elements = CAT->getSize().getZExtValue();
8452   Result = APValue(APValue::UninitArray(), Elements, Elements);
8453 
8454   LValue Subobject = This;
8455   Subobject.addArray(Info, E, CAT);
8456 
8457   bool Success = true;
8458   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
8459     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
8460                          Info, Subobject, E->getSubExpr()) ||
8461         !HandleLValueArrayAdjustment(Info, E, Subobject,
8462                                      CAT->getElementType(), 1)) {
8463       if (!Info.noteFailure())
8464         return false;
8465       Success = false;
8466     }
8467   }
8468 
8469   return Success;
8470 }
8471 
8472 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
8473   return VisitCXXConstructExpr(E, This, &Result, E->getType());
8474 }
8475 
8476 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
8477                                                const LValue &Subobject,
8478                                                APValue *Value,
8479                                                QualType Type) {
8480   bool HadZeroInit = Value->hasValue();
8481 
8482   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
8483     unsigned N = CAT->getSize().getZExtValue();
8484 
8485     // Preserve the array filler if we had prior zero-initialization.
8486     APValue Filler =
8487       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
8488                                              : APValue();
8489 
8490     *Value = APValue(APValue::UninitArray(), N, N);
8491 
8492     if (HadZeroInit)
8493       for (unsigned I = 0; I != N; ++I)
8494         Value->getArrayInitializedElt(I) = Filler;
8495 
8496     // Initialize the elements.
8497     LValue ArrayElt = Subobject;
8498     ArrayElt.addArray(Info, E, CAT);
8499     for (unsigned I = 0; I != N; ++I)
8500       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
8501                                  CAT->getElementType()) ||
8502           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
8503                                        CAT->getElementType(), 1))
8504         return false;
8505 
8506     return true;
8507   }
8508 
8509   if (!Type->isRecordType())
8510     return Error(E);
8511 
8512   return RecordExprEvaluator(Info, Subobject, *Value)
8513              .VisitCXXConstructExpr(E, Type);
8514 }
8515 
8516 //===----------------------------------------------------------------------===//
8517 // Integer Evaluation
8518 //
8519 // As a GNU extension, we support casting pointers to sufficiently-wide integer
8520 // types and back in constant folding. Integer values are thus represented
8521 // either as an integer-valued APValue, or as an lvalue-valued APValue.
8522 //===----------------------------------------------------------------------===//
8523 
8524 namespace {
8525 class IntExprEvaluator
8526         : public ExprEvaluatorBase<IntExprEvaluator> {
8527   APValue &Result;
8528 public:
8529   IntExprEvaluator(EvalInfo &info, APValue &result)
8530       : ExprEvaluatorBaseTy(info), Result(result) {}
8531 
8532   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
8533     assert(E->getType()->isIntegralOrEnumerationType() &&
8534            "Invalid evaluation result.");
8535     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
8536            "Invalid evaluation result.");
8537     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
8538            "Invalid evaluation result.");
8539     Result = APValue(SI);
8540     return true;
8541   }
8542   bool Success(const llvm::APSInt &SI, const Expr *E) {
8543     return Success(SI, E, Result);
8544   }
8545 
8546   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
8547     assert(E->getType()->isIntegralOrEnumerationType() &&
8548            "Invalid evaluation result.");
8549     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
8550            "Invalid evaluation result.");
8551     Result = APValue(APSInt(I));
8552     Result.getInt().setIsUnsigned(
8553                             E->getType()->isUnsignedIntegerOrEnumerationType());
8554     return true;
8555   }
8556   bool Success(const llvm::APInt &I, const Expr *E) {
8557     return Success(I, E, Result);
8558   }
8559 
8560   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8561     assert(E->getType()->isIntegralOrEnumerationType() &&
8562            "Invalid evaluation result.");
8563     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
8564     return true;
8565   }
8566   bool Success(uint64_t Value, const Expr *E) {
8567     return Success(Value, E, Result);
8568   }
8569 
8570   bool Success(CharUnits Size, const Expr *E) {
8571     return Success(Size.getQuantity(), E);
8572   }
8573 
8574   bool Success(const APValue &V, const Expr *E) {
8575     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
8576       Result = V;
8577       return true;
8578     }
8579     return Success(V.getInt(), E);
8580   }
8581 
8582   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
8583 
8584   //===--------------------------------------------------------------------===//
8585   //                            Visitor Methods
8586   //===--------------------------------------------------------------------===//
8587 
8588   bool VisitConstantExpr(const ConstantExpr *E);
8589 
8590   bool VisitIntegerLiteral(const IntegerLiteral *E) {
8591     return Success(E->getValue(), E);
8592   }
8593   bool VisitCharacterLiteral(const CharacterLiteral *E) {
8594     return Success(E->getValue(), E);
8595   }
8596 
8597   bool CheckReferencedDecl(const Expr *E, const Decl *D);
8598   bool VisitDeclRefExpr(const DeclRefExpr *E) {
8599     if (CheckReferencedDecl(E, E->getDecl()))
8600       return true;
8601 
8602     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
8603   }
8604   bool VisitMemberExpr(const MemberExpr *E) {
8605     if (CheckReferencedDecl(E, E->getMemberDecl())) {
8606       VisitIgnoredBaseExpression(E->getBase());
8607       return true;
8608     }
8609 
8610     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
8611   }
8612 
8613   bool VisitCallExpr(const CallExpr *E);
8614   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8615   bool VisitBinaryOperator(const BinaryOperator *E);
8616   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
8617   bool VisitUnaryOperator(const UnaryOperator *E);
8618 
8619   bool VisitCastExpr(const CastExpr* E);
8620   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
8621 
8622   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
8623     return Success(E->getValue(), E);
8624   }
8625 
8626   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
8627     return Success(E->getValue(), E);
8628   }
8629 
8630   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
8631     if (Info.ArrayInitIndex == uint64_t(-1)) {
8632       // We were asked to evaluate this subexpression independent of the
8633       // enclosing ArrayInitLoopExpr. We can't do that.
8634       Info.FFDiag(E);
8635       return false;
8636     }
8637     return Success(Info.ArrayInitIndex, E);
8638   }
8639 
8640   // Note, GNU defines __null as an integer, not a pointer.
8641   bool VisitGNUNullExpr(const GNUNullExpr *E) {
8642     return ZeroInitialization(E);
8643   }
8644 
8645   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
8646     return Success(E->getValue(), E);
8647   }
8648 
8649   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
8650     return Success(E->getValue(), E);
8651   }
8652 
8653   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
8654     return Success(E->getValue(), E);
8655   }
8656 
8657   bool VisitUnaryReal(const UnaryOperator *E);
8658   bool VisitUnaryImag(const UnaryOperator *E);
8659 
8660   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
8661   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
8662   bool VisitSourceLocExpr(const SourceLocExpr *E);
8663   // FIXME: Missing: array subscript of vector, member of vector
8664 };
8665 
8666 class FixedPointExprEvaluator
8667     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
8668   APValue &Result;
8669 
8670  public:
8671   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
8672       : ExprEvaluatorBaseTy(info), Result(result) {}
8673 
8674   bool Success(const llvm::APInt &I, const Expr *E) {
8675     return Success(
8676         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
8677   }
8678 
8679   bool Success(uint64_t Value, const Expr *E) {
8680     return Success(
8681         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
8682   }
8683 
8684   bool Success(const APValue &V, const Expr *E) {
8685     return Success(V.getFixedPoint(), E);
8686   }
8687 
8688   bool Success(const APFixedPoint &V, const Expr *E) {
8689     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
8690     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
8691            "Invalid evaluation result.");
8692     Result = APValue(V);
8693     return true;
8694   }
8695 
8696   //===--------------------------------------------------------------------===//
8697   //                            Visitor Methods
8698   //===--------------------------------------------------------------------===//
8699 
8700   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
8701     return Success(E->getValue(), E);
8702   }
8703 
8704   bool VisitCastExpr(const CastExpr *E);
8705   bool VisitUnaryOperator(const UnaryOperator *E);
8706   bool VisitBinaryOperator(const BinaryOperator *E);
8707 };
8708 } // end anonymous namespace
8709 
8710 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
8711 /// produce either the integer value or a pointer.
8712 ///
8713 /// GCC has a heinous extension which folds casts between pointer types and
8714 /// pointer-sized integral types. We support this by allowing the evaluation of
8715 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
8716 /// Some simple arithmetic on such values is supported (they are treated much
8717 /// like char*).
8718 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
8719                                     EvalInfo &Info) {
8720   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
8721   return IntExprEvaluator(Info, Result).Visit(E);
8722 }
8723 
8724 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
8725   APValue Val;
8726   if (!EvaluateIntegerOrLValue(E, Val, Info))
8727     return false;
8728   if (!Val.isInt()) {
8729     // FIXME: It would be better to produce the diagnostic for casting
8730     //        a pointer to an integer.
8731     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
8732     return false;
8733   }
8734   Result = Val.getInt();
8735   return true;
8736 }
8737 
8738 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
8739   APValue Evaluated = E->EvaluateInContext(
8740       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8741   return Success(Evaluated, E);
8742 }
8743 
8744 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
8745                                EvalInfo &Info) {
8746   if (E->getType()->isFixedPointType()) {
8747     APValue Val;
8748     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
8749       return false;
8750     if (!Val.isFixedPoint())
8751       return false;
8752 
8753     Result = Val.getFixedPoint();
8754     return true;
8755   }
8756   return false;
8757 }
8758 
8759 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
8760                                         EvalInfo &Info) {
8761   if (E->getType()->isIntegerType()) {
8762     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
8763     APSInt Val;
8764     if (!EvaluateInteger(E, Val, Info))
8765       return false;
8766     Result = APFixedPoint(Val, FXSema);
8767     return true;
8768   } else if (E->getType()->isFixedPointType()) {
8769     return EvaluateFixedPoint(E, Result, Info);
8770   }
8771   return false;
8772 }
8773 
8774 /// Check whether the given declaration can be directly converted to an integral
8775 /// rvalue. If not, no diagnostic is produced; there are other things we can
8776 /// try.
8777 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
8778   // Enums are integer constant exprs.
8779   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
8780     // Check for signedness/width mismatches between E type and ECD value.
8781     bool SameSign = (ECD->getInitVal().isSigned()
8782                      == E->getType()->isSignedIntegerOrEnumerationType());
8783     bool SameWidth = (ECD->getInitVal().getBitWidth()
8784                       == Info.Ctx.getIntWidth(E->getType()));
8785     if (SameSign && SameWidth)
8786       return Success(ECD->getInitVal(), E);
8787     else {
8788       // Get rid of mismatch (otherwise Success assertions will fail)
8789       // by computing a new value matching the type of E.
8790       llvm::APSInt Val = ECD->getInitVal();
8791       if (!SameSign)
8792         Val.setIsSigned(!ECD->getInitVal().isSigned());
8793       if (!SameWidth)
8794         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
8795       return Success(Val, E);
8796     }
8797   }
8798   return false;
8799 }
8800 
8801 /// Values returned by __builtin_classify_type, chosen to match the values
8802 /// produced by GCC's builtin.
8803 enum class GCCTypeClass {
8804   None = -1,
8805   Void = 0,
8806   Integer = 1,
8807   // GCC reserves 2 for character types, but instead classifies them as
8808   // integers.
8809   Enum = 3,
8810   Bool = 4,
8811   Pointer = 5,
8812   // GCC reserves 6 for references, but appears to never use it (because
8813   // expressions never have reference type, presumably).
8814   PointerToDataMember = 7,
8815   RealFloat = 8,
8816   Complex = 9,
8817   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
8818   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
8819   // GCC claims to reserve 11 for pointers to member functions, but *actually*
8820   // uses 12 for that purpose, same as for a class or struct. Maybe it
8821   // internally implements a pointer to member as a struct?  Who knows.
8822   PointerToMemberFunction = 12, // Not a bug, see above.
8823   ClassOrStruct = 12,
8824   Union = 13,
8825   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
8826   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
8827   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
8828   // literals.
8829 };
8830 
8831 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
8832 /// as GCC.
8833 static GCCTypeClass
8834 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
8835   assert(!T->isDependentType() && "unexpected dependent type");
8836 
8837   QualType CanTy = T.getCanonicalType();
8838   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
8839 
8840   switch (CanTy->getTypeClass()) {
8841 #define TYPE(ID, BASE)
8842 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
8843 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
8844 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
8845 #include "clang/AST/TypeNodes.def"
8846   case Type::Auto:
8847   case Type::DeducedTemplateSpecialization:
8848       llvm_unreachable("unexpected non-canonical or dependent type");
8849 
8850   case Type::Builtin:
8851     switch (BT->getKind()) {
8852 #define BUILTIN_TYPE(ID, SINGLETON_ID)
8853 #define SIGNED_TYPE(ID, SINGLETON_ID) \
8854     case BuiltinType::ID: return GCCTypeClass::Integer;
8855 #define FLOATING_TYPE(ID, SINGLETON_ID) \
8856     case BuiltinType::ID: return GCCTypeClass::RealFloat;
8857 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
8858     case BuiltinType::ID: break;
8859 #include "clang/AST/BuiltinTypes.def"
8860     case BuiltinType::Void:
8861       return GCCTypeClass::Void;
8862 
8863     case BuiltinType::Bool:
8864       return GCCTypeClass::Bool;
8865 
8866     case BuiltinType::Char_U:
8867     case BuiltinType::UChar:
8868     case BuiltinType::WChar_U:
8869     case BuiltinType::Char8:
8870     case BuiltinType::Char16:
8871     case BuiltinType::Char32:
8872     case BuiltinType::UShort:
8873     case BuiltinType::UInt:
8874     case BuiltinType::ULong:
8875     case BuiltinType::ULongLong:
8876     case BuiltinType::UInt128:
8877       return GCCTypeClass::Integer;
8878 
8879     case BuiltinType::UShortAccum:
8880     case BuiltinType::UAccum:
8881     case BuiltinType::ULongAccum:
8882     case BuiltinType::UShortFract:
8883     case BuiltinType::UFract:
8884     case BuiltinType::ULongFract:
8885     case BuiltinType::SatUShortAccum:
8886     case BuiltinType::SatUAccum:
8887     case BuiltinType::SatULongAccum:
8888     case BuiltinType::SatUShortFract:
8889     case BuiltinType::SatUFract:
8890     case BuiltinType::SatULongFract:
8891       return GCCTypeClass::None;
8892 
8893     case BuiltinType::NullPtr:
8894 
8895     case BuiltinType::ObjCId:
8896     case BuiltinType::ObjCClass:
8897     case BuiltinType::ObjCSel:
8898 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8899     case BuiltinType::Id:
8900 #include "clang/Basic/OpenCLImageTypes.def"
8901 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
8902     case BuiltinType::Id:
8903 #include "clang/Basic/OpenCLExtensionTypes.def"
8904     case BuiltinType::OCLSampler:
8905     case BuiltinType::OCLEvent:
8906     case BuiltinType::OCLClkEvent:
8907     case BuiltinType::OCLQueue:
8908     case BuiltinType::OCLReserveID:
8909 #define SVE_TYPE(Name, Id, SingletonId) \
8910     case BuiltinType::Id:
8911 #include "clang/Basic/AArch64SVEACLETypes.def"
8912       return GCCTypeClass::None;
8913 
8914     case BuiltinType::Dependent:
8915       llvm_unreachable("unexpected dependent type");
8916     };
8917     llvm_unreachable("unexpected placeholder type");
8918 
8919   case Type::Enum:
8920     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
8921 
8922   case Type::Pointer:
8923   case Type::ConstantArray:
8924   case Type::VariableArray:
8925   case Type::IncompleteArray:
8926   case Type::FunctionNoProto:
8927   case Type::FunctionProto:
8928     return GCCTypeClass::Pointer;
8929 
8930   case Type::MemberPointer:
8931     return CanTy->isMemberDataPointerType()
8932                ? GCCTypeClass::PointerToDataMember
8933                : GCCTypeClass::PointerToMemberFunction;
8934 
8935   case Type::Complex:
8936     return GCCTypeClass::Complex;
8937 
8938   case Type::Record:
8939     return CanTy->isUnionType() ? GCCTypeClass::Union
8940                                 : GCCTypeClass::ClassOrStruct;
8941 
8942   case Type::Atomic:
8943     // GCC classifies _Atomic T the same as T.
8944     return EvaluateBuiltinClassifyType(
8945         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
8946 
8947   case Type::BlockPointer:
8948   case Type::Vector:
8949   case Type::ExtVector:
8950   case Type::ObjCObject:
8951   case Type::ObjCInterface:
8952   case Type::ObjCObjectPointer:
8953   case Type::Pipe:
8954     // GCC classifies vectors as None. We follow its lead and classify all
8955     // other types that don't fit into the regular classification the same way.
8956     return GCCTypeClass::None;
8957 
8958   case Type::LValueReference:
8959   case Type::RValueReference:
8960     llvm_unreachable("invalid type for expression");
8961   }
8962 
8963   llvm_unreachable("unexpected type class");
8964 }
8965 
8966 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
8967 /// as GCC.
8968 static GCCTypeClass
8969 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
8970   // If no argument was supplied, default to None. This isn't
8971   // ideal, however it is what gcc does.
8972   if (E->getNumArgs() == 0)
8973     return GCCTypeClass::None;
8974 
8975   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
8976   // being an ICE, but still folds it to a constant using the type of the first
8977   // argument.
8978   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
8979 }
8980 
8981 /// EvaluateBuiltinConstantPForLValue - Determine the result of
8982 /// __builtin_constant_p when applied to the given pointer.
8983 ///
8984 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
8985 /// or it points to the first character of a string literal.
8986 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
8987   APValue::LValueBase Base = LV.getLValueBase();
8988   if (Base.isNull()) {
8989     // A null base is acceptable.
8990     return true;
8991   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
8992     if (!isa<StringLiteral>(E))
8993       return false;
8994     return LV.getLValueOffset().isZero();
8995   } else if (Base.is<TypeInfoLValue>()) {
8996     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
8997     // evaluate to true.
8998     return true;
8999   } else {
9000     // Any other base is not constant enough for GCC.
9001     return false;
9002   }
9003 }
9004 
9005 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
9006 /// GCC as we can manage.
9007 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
9008   // This evaluation is not permitted to have side-effects, so evaluate it in
9009   // a speculative evaluation context.
9010   SpeculativeEvaluationRAII SpeculativeEval(Info);
9011 
9012   // Constant-folding is always enabled for the operand of __builtin_constant_p
9013   // (even when the enclosing evaluation context otherwise requires a strict
9014   // language-specific constant expression).
9015   FoldConstant Fold(Info, true);
9016 
9017   QualType ArgType = Arg->getType();
9018 
9019   // __builtin_constant_p always has one operand. The rules which gcc follows
9020   // are not precisely documented, but are as follows:
9021   //
9022   //  - If the operand is of integral, floating, complex or enumeration type,
9023   //    and can be folded to a known value of that type, it returns 1.
9024   //  - If the operand can be folded to a pointer to the first character
9025   //    of a string literal (or such a pointer cast to an integral type)
9026   //    or to a null pointer or an integer cast to a pointer, it returns 1.
9027   //
9028   // Otherwise, it returns 0.
9029   //
9030   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
9031   // its support for this did not work prior to GCC 9 and is not yet well
9032   // understood.
9033   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
9034       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
9035       ArgType->isNullPtrType()) {
9036     APValue V;
9037     if (!::EvaluateAsRValue(Info, Arg, V)) {
9038       Fold.keepDiagnostics();
9039       return false;
9040     }
9041 
9042     // For a pointer (possibly cast to integer), there are special rules.
9043     if (V.getKind() == APValue::LValue)
9044       return EvaluateBuiltinConstantPForLValue(V);
9045 
9046     // Otherwise, any constant value is good enough.
9047     return V.hasValue();
9048   }
9049 
9050   // Anything else isn't considered to be sufficiently constant.
9051   return false;
9052 }
9053 
9054 /// Retrieves the "underlying object type" of the given expression,
9055 /// as used by __builtin_object_size.
9056 static QualType getObjectType(APValue::LValueBase B) {
9057   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
9058     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
9059       return VD->getType();
9060   } else if (const Expr *E = B.get<const Expr*>()) {
9061     if (isa<CompoundLiteralExpr>(E))
9062       return E->getType();
9063   } else if (B.is<TypeInfoLValue>()) {
9064     return B.getTypeInfoType();
9065   }
9066 
9067   return QualType();
9068 }
9069 
9070 /// A more selective version of E->IgnoreParenCasts for
9071 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
9072 /// to change the type of E.
9073 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
9074 ///
9075 /// Always returns an RValue with a pointer representation.
9076 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
9077   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
9078 
9079   auto *NoParens = E->IgnoreParens();
9080   auto *Cast = dyn_cast<CastExpr>(NoParens);
9081   if (Cast == nullptr)
9082     return NoParens;
9083 
9084   // We only conservatively allow a few kinds of casts, because this code is
9085   // inherently a simple solution that seeks to support the common case.
9086   auto CastKind = Cast->getCastKind();
9087   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
9088       CastKind != CK_AddressSpaceConversion)
9089     return NoParens;
9090 
9091   auto *SubExpr = Cast->getSubExpr();
9092   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
9093     return NoParens;
9094   return ignorePointerCastsAndParens(SubExpr);
9095 }
9096 
9097 /// Checks to see if the given LValue's Designator is at the end of the LValue's
9098 /// record layout. e.g.
9099 ///   struct { struct { int a, b; } fst, snd; } obj;
9100 ///   obj.fst   // no
9101 ///   obj.snd   // yes
9102 ///   obj.fst.a // no
9103 ///   obj.fst.b // no
9104 ///   obj.snd.a // no
9105 ///   obj.snd.b // yes
9106 ///
9107 /// Please note: this function is specialized for how __builtin_object_size
9108 /// views "objects".
9109 ///
9110 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
9111 /// correct result, it will always return true.
9112 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
9113   assert(!LVal.Designator.Invalid);
9114 
9115   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
9116     const RecordDecl *Parent = FD->getParent();
9117     Invalid = Parent->isInvalidDecl();
9118     if (Invalid || Parent->isUnion())
9119       return true;
9120     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
9121     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
9122   };
9123 
9124   auto &Base = LVal.getLValueBase();
9125   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
9126     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
9127       bool Invalid;
9128       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
9129         return Invalid;
9130     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
9131       for (auto *FD : IFD->chain()) {
9132         bool Invalid;
9133         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
9134           return Invalid;
9135       }
9136     }
9137   }
9138 
9139   unsigned I = 0;
9140   QualType BaseType = getType(Base);
9141   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
9142     // If we don't know the array bound, conservatively assume we're looking at
9143     // the final array element.
9144     ++I;
9145     if (BaseType->isIncompleteArrayType())
9146       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
9147     else
9148       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
9149   }
9150 
9151   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
9152     const auto &Entry = LVal.Designator.Entries[I];
9153     if (BaseType->isArrayType()) {
9154       // Because __builtin_object_size treats arrays as objects, we can ignore
9155       // the index iff this is the last array in the Designator.
9156       if (I + 1 == E)
9157         return true;
9158       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
9159       uint64_t Index = Entry.getAsArrayIndex();
9160       if (Index + 1 != CAT->getSize())
9161         return false;
9162       BaseType = CAT->getElementType();
9163     } else if (BaseType->isAnyComplexType()) {
9164       const auto *CT = BaseType->castAs<ComplexType>();
9165       uint64_t Index = Entry.getAsArrayIndex();
9166       if (Index != 1)
9167         return false;
9168       BaseType = CT->getElementType();
9169     } else if (auto *FD = getAsField(Entry)) {
9170       bool Invalid;
9171       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
9172         return Invalid;
9173       BaseType = FD->getType();
9174     } else {
9175       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
9176       return false;
9177     }
9178   }
9179   return true;
9180 }
9181 
9182 /// Tests to see if the LValue has a user-specified designator (that isn't
9183 /// necessarily valid). Note that this always returns 'true' if the LValue has
9184 /// an unsized array as its first designator entry, because there's currently no
9185 /// way to tell if the user typed *foo or foo[0].
9186 static bool refersToCompleteObject(const LValue &LVal) {
9187   if (LVal.Designator.Invalid)
9188     return false;
9189 
9190   if (!LVal.Designator.Entries.empty())
9191     return LVal.Designator.isMostDerivedAnUnsizedArray();
9192 
9193   if (!LVal.InvalidBase)
9194     return true;
9195 
9196   // If `E` is a MemberExpr, then the first part of the designator is hiding in
9197   // the LValueBase.
9198   const auto *E = LVal.Base.dyn_cast<const Expr *>();
9199   return !E || !isa<MemberExpr>(E);
9200 }
9201 
9202 /// Attempts to detect a user writing into a piece of memory that's impossible
9203 /// to figure out the size of by just using types.
9204 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
9205   const SubobjectDesignator &Designator = LVal.Designator;
9206   // Notes:
9207   // - Users can only write off of the end when we have an invalid base. Invalid
9208   //   bases imply we don't know where the memory came from.
9209   // - We used to be a bit more aggressive here; we'd only be conservative if
9210   //   the array at the end was flexible, or if it had 0 or 1 elements. This
9211   //   broke some common standard library extensions (PR30346), but was
9212   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
9213   //   with some sort of whitelist. OTOH, it seems that GCC is always
9214   //   conservative with the last element in structs (if it's an array), so our
9215   //   current behavior is more compatible than a whitelisting approach would
9216   //   be.
9217   return LVal.InvalidBase &&
9218          Designator.Entries.size() == Designator.MostDerivedPathLength &&
9219          Designator.MostDerivedIsArrayElement &&
9220          isDesignatorAtObjectEnd(Ctx, LVal);
9221 }
9222 
9223 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
9224 /// Fails if the conversion would cause loss of precision.
9225 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
9226                                             CharUnits &Result) {
9227   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
9228   if (Int.ugt(CharUnitsMax))
9229     return false;
9230   Result = CharUnits::fromQuantity(Int.getZExtValue());
9231   return true;
9232 }
9233 
9234 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
9235 /// determine how many bytes exist from the beginning of the object to either
9236 /// the end of the current subobject, or the end of the object itself, depending
9237 /// on what the LValue looks like + the value of Type.
9238 ///
9239 /// If this returns false, the value of Result is undefined.
9240 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
9241                                unsigned Type, const LValue &LVal,
9242                                CharUnits &EndOffset) {
9243   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
9244 
9245   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
9246     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
9247       return false;
9248     return HandleSizeof(Info, ExprLoc, Ty, Result);
9249   };
9250 
9251   // We want to evaluate the size of the entire object. This is a valid fallback
9252   // for when Type=1 and the designator is invalid, because we're asked for an
9253   // upper-bound.
9254   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
9255     // Type=3 wants a lower bound, so we can't fall back to this.
9256     if (Type == 3 && !DetermineForCompleteObject)
9257       return false;
9258 
9259     llvm::APInt APEndOffset;
9260     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9261         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
9262       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
9263 
9264     if (LVal.InvalidBase)
9265       return false;
9266 
9267     QualType BaseTy = getObjectType(LVal.getLValueBase());
9268     return CheckedHandleSizeof(BaseTy, EndOffset);
9269   }
9270 
9271   // We want to evaluate the size of a subobject.
9272   const SubobjectDesignator &Designator = LVal.Designator;
9273 
9274   // The following is a moderately common idiom in C:
9275   //
9276   // struct Foo { int a; char c[1]; };
9277   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
9278   // strcpy(&F->c[0], Bar);
9279   //
9280   // In order to not break too much legacy code, we need to support it.
9281   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
9282     // If we can resolve this to an alloc_size call, we can hand that back,
9283     // because we know for certain how many bytes there are to write to.
9284     llvm::APInt APEndOffset;
9285     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9286         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
9287       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
9288 
9289     // If we cannot determine the size of the initial allocation, then we can't
9290     // given an accurate upper-bound. However, we are still able to give
9291     // conservative lower-bounds for Type=3.
9292     if (Type == 1)
9293       return false;
9294   }
9295 
9296   CharUnits BytesPerElem;
9297   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
9298     return false;
9299 
9300   // According to the GCC documentation, we want the size of the subobject
9301   // denoted by the pointer. But that's not quite right -- what we actually
9302   // want is the size of the immediately-enclosing array, if there is one.
9303   int64_t ElemsRemaining;
9304   if (Designator.MostDerivedIsArrayElement &&
9305       Designator.Entries.size() == Designator.MostDerivedPathLength) {
9306     uint64_t ArraySize = Designator.getMostDerivedArraySize();
9307     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
9308     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
9309   } else {
9310     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
9311   }
9312 
9313   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
9314   return true;
9315 }
9316 
9317 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
9318 /// returns true and stores the result in @p Size.
9319 ///
9320 /// If @p WasError is non-null, this will report whether the failure to evaluate
9321 /// is to be treated as an Error in IntExprEvaluator.
9322 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
9323                                          EvalInfo &Info, uint64_t &Size) {
9324   // Determine the denoted object.
9325   LValue LVal;
9326   {
9327     // The operand of __builtin_object_size is never evaluated for side-effects.
9328     // If there are any, but we can determine the pointed-to object anyway, then
9329     // ignore the side-effects.
9330     SpeculativeEvaluationRAII SpeculativeEval(Info);
9331     IgnoreSideEffectsRAII Fold(Info);
9332 
9333     if (E->isGLValue()) {
9334       // It's possible for us to be given GLValues if we're called via
9335       // Expr::tryEvaluateObjectSize.
9336       APValue RVal;
9337       if (!EvaluateAsRValue(Info, E, RVal))
9338         return false;
9339       LVal.setFrom(Info.Ctx, RVal);
9340     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
9341                                 /*InvalidBaseOK=*/true))
9342       return false;
9343   }
9344 
9345   // If we point to before the start of the object, there are no accessible
9346   // bytes.
9347   if (LVal.getLValueOffset().isNegative()) {
9348     Size = 0;
9349     return true;
9350   }
9351 
9352   CharUnits EndOffset;
9353   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
9354     return false;
9355 
9356   // If we've fallen outside of the end offset, just pretend there's nothing to
9357   // write to/read from.
9358   if (EndOffset <= LVal.getLValueOffset())
9359     Size = 0;
9360   else
9361     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
9362   return true;
9363 }
9364 
9365 bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
9366   llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
9367   if (E->getResultAPValueKind() != APValue::None)
9368     return Success(E->getAPValueResult(), E);
9369   return ExprEvaluatorBaseTy::VisitConstantExpr(E);
9370 }
9371 
9372 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
9373   if (unsigned BuiltinOp = E->getBuiltinCallee())
9374     return VisitBuiltinCallExpr(E, BuiltinOp);
9375 
9376   return ExprEvaluatorBaseTy::VisitCallExpr(E);
9377 }
9378 
9379 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9380                                             unsigned BuiltinOp) {
9381   switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
9382   default:
9383     return ExprEvaluatorBaseTy::VisitCallExpr(E);
9384 
9385   case Builtin::BI__builtin_dynamic_object_size:
9386   case Builtin::BI__builtin_object_size: {
9387     // The type was checked when we built the expression.
9388     unsigned Type =
9389         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
9390     assert(Type <= 3 && "unexpected type");
9391 
9392     uint64_t Size;
9393     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
9394       return Success(Size, E);
9395 
9396     if (E->getArg(0)->HasSideEffects(Info.Ctx))
9397       return Success((Type & 2) ? 0 : -1, E);
9398 
9399     // Expression had no side effects, but we couldn't statically determine the
9400     // size of the referenced object.
9401     switch (Info.EvalMode) {
9402     case EvalInfo::EM_ConstantExpression:
9403     case EvalInfo::EM_ConstantFold:
9404     case EvalInfo::EM_IgnoreSideEffects:
9405       // Leave it to IR generation.
9406       return Error(E);
9407     case EvalInfo::EM_ConstantExpressionUnevaluated:
9408       // Reduce it to a constant now.
9409       return Success((Type & 2) ? 0 : -1, E);
9410     }
9411 
9412     llvm_unreachable("unexpected EvalMode");
9413   }
9414 
9415   case Builtin::BI__builtin_os_log_format_buffer_size: {
9416     analyze_os_log::OSLogBufferLayout Layout;
9417     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
9418     return Success(Layout.size().getQuantity(), E);
9419   }
9420 
9421   case Builtin::BI__builtin_bswap16:
9422   case Builtin::BI__builtin_bswap32:
9423   case Builtin::BI__builtin_bswap64: {
9424     APSInt Val;
9425     if (!EvaluateInteger(E->getArg(0), Val, Info))
9426       return false;
9427 
9428     return Success(Val.byteSwap(), E);
9429   }
9430 
9431   case Builtin::BI__builtin_classify_type:
9432     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
9433 
9434   case Builtin::BI__builtin_clrsb:
9435   case Builtin::BI__builtin_clrsbl:
9436   case Builtin::BI__builtin_clrsbll: {
9437     APSInt Val;
9438     if (!EvaluateInteger(E->getArg(0), Val, Info))
9439       return false;
9440 
9441     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
9442   }
9443 
9444   case Builtin::BI__builtin_clz:
9445   case Builtin::BI__builtin_clzl:
9446   case Builtin::BI__builtin_clzll:
9447   case Builtin::BI__builtin_clzs: {
9448     APSInt Val;
9449     if (!EvaluateInteger(E->getArg(0), Val, Info))
9450       return false;
9451     if (!Val)
9452       return Error(E);
9453 
9454     return Success(Val.countLeadingZeros(), E);
9455   }
9456 
9457   case Builtin::BI__builtin_constant_p: {
9458     const Expr *Arg = E->getArg(0);
9459     if (EvaluateBuiltinConstantP(Info, Arg))
9460       return Success(true, E);
9461     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
9462       // Outside a constant context, eagerly evaluate to false in the presence
9463       // of side-effects in order to avoid -Wunsequenced false-positives in
9464       // a branch on __builtin_constant_p(expr).
9465       return Success(false, E);
9466     }
9467     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9468     return false;
9469   }
9470 
9471   case Builtin::BI__builtin_is_constant_evaluated:
9472     return Success(Info.InConstantContext, E);
9473 
9474   case Builtin::BI__builtin_ctz:
9475   case Builtin::BI__builtin_ctzl:
9476   case Builtin::BI__builtin_ctzll:
9477   case Builtin::BI__builtin_ctzs: {
9478     APSInt Val;
9479     if (!EvaluateInteger(E->getArg(0), Val, Info))
9480       return false;
9481     if (!Val)
9482       return Error(E);
9483 
9484     return Success(Val.countTrailingZeros(), E);
9485   }
9486 
9487   case Builtin::BI__builtin_eh_return_data_regno: {
9488     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
9489     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
9490     return Success(Operand, E);
9491   }
9492 
9493   case Builtin::BI__builtin_expect:
9494     return Visit(E->getArg(0));
9495 
9496   case Builtin::BI__builtin_ffs:
9497   case Builtin::BI__builtin_ffsl:
9498   case Builtin::BI__builtin_ffsll: {
9499     APSInt Val;
9500     if (!EvaluateInteger(E->getArg(0), Val, Info))
9501       return false;
9502 
9503     unsigned N = Val.countTrailingZeros();
9504     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
9505   }
9506 
9507   case Builtin::BI__builtin_fpclassify: {
9508     APFloat Val(0.0);
9509     if (!EvaluateFloat(E->getArg(5), Val, Info))
9510       return false;
9511     unsigned Arg;
9512     switch (Val.getCategory()) {
9513     case APFloat::fcNaN: Arg = 0; break;
9514     case APFloat::fcInfinity: Arg = 1; break;
9515     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
9516     case APFloat::fcZero: Arg = 4; break;
9517     }
9518     return Visit(E->getArg(Arg));
9519   }
9520 
9521   case Builtin::BI__builtin_isinf_sign: {
9522     APFloat Val(0.0);
9523     return EvaluateFloat(E->getArg(0), Val, Info) &&
9524            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
9525   }
9526 
9527   case Builtin::BI__builtin_isinf: {
9528     APFloat Val(0.0);
9529     return EvaluateFloat(E->getArg(0), Val, Info) &&
9530            Success(Val.isInfinity() ? 1 : 0, E);
9531   }
9532 
9533   case Builtin::BI__builtin_isfinite: {
9534     APFloat Val(0.0);
9535     return EvaluateFloat(E->getArg(0), Val, Info) &&
9536            Success(Val.isFinite() ? 1 : 0, E);
9537   }
9538 
9539   case Builtin::BI__builtin_isnan: {
9540     APFloat Val(0.0);
9541     return EvaluateFloat(E->getArg(0), Val, Info) &&
9542            Success(Val.isNaN() ? 1 : 0, E);
9543   }
9544 
9545   case Builtin::BI__builtin_isnormal: {
9546     APFloat Val(0.0);
9547     return EvaluateFloat(E->getArg(0), Val, Info) &&
9548            Success(Val.isNormal() ? 1 : 0, E);
9549   }
9550 
9551   case Builtin::BI__builtin_parity:
9552   case Builtin::BI__builtin_parityl:
9553   case Builtin::BI__builtin_parityll: {
9554     APSInt Val;
9555     if (!EvaluateInteger(E->getArg(0), Val, Info))
9556       return false;
9557 
9558     return Success(Val.countPopulation() % 2, E);
9559   }
9560 
9561   case Builtin::BI__builtin_popcount:
9562   case Builtin::BI__builtin_popcountl:
9563   case Builtin::BI__builtin_popcountll: {
9564     APSInt Val;
9565     if (!EvaluateInteger(E->getArg(0), Val, Info))
9566       return false;
9567 
9568     return Success(Val.countPopulation(), E);
9569   }
9570 
9571   case Builtin::BIstrlen:
9572   case Builtin::BIwcslen:
9573     // A call to strlen is not a constant expression.
9574     if (Info.getLangOpts().CPlusPlus11)
9575       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9576         << /*isConstexpr*/0 << /*isConstructor*/0
9577         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9578     else
9579       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9580     LLVM_FALLTHROUGH;
9581   case Builtin::BI__builtin_strlen:
9582   case Builtin::BI__builtin_wcslen: {
9583     // As an extension, we support __builtin_strlen() as a constant expression,
9584     // and support folding strlen() to a constant.
9585     LValue String;
9586     if (!EvaluatePointer(E->getArg(0), String, Info))
9587       return false;
9588 
9589     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
9590 
9591     // Fast path: if it's a string literal, search the string value.
9592     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
9593             String.getLValueBase().dyn_cast<const Expr *>())) {
9594       // The string literal may have embedded null characters. Find the first
9595       // one and truncate there.
9596       StringRef Str = S->getBytes();
9597       int64_t Off = String.Offset.getQuantity();
9598       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
9599           S->getCharByteWidth() == 1 &&
9600           // FIXME: Add fast-path for wchar_t too.
9601           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
9602         Str = Str.substr(Off);
9603 
9604         StringRef::size_type Pos = Str.find(0);
9605         if (Pos != StringRef::npos)
9606           Str = Str.substr(0, Pos);
9607 
9608         return Success(Str.size(), E);
9609       }
9610 
9611       // Fall through to slow path to issue appropriate diagnostic.
9612     }
9613 
9614     // Slow path: scan the bytes of the string looking for the terminating 0.
9615     for (uint64_t Strlen = 0; /**/; ++Strlen) {
9616       APValue Char;
9617       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
9618           !Char.isInt())
9619         return false;
9620       if (!Char.getInt())
9621         return Success(Strlen, E);
9622       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
9623         return false;
9624     }
9625   }
9626 
9627   case Builtin::BIstrcmp:
9628   case Builtin::BIwcscmp:
9629   case Builtin::BIstrncmp:
9630   case Builtin::BIwcsncmp:
9631   case Builtin::BImemcmp:
9632   case Builtin::BIbcmp:
9633   case Builtin::BIwmemcmp:
9634     // A call to strlen is not a constant expression.
9635     if (Info.getLangOpts().CPlusPlus11)
9636       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9637         << /*isConstexpr*/0 << /*isConstructor*/0
9638         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9639     else
9640       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9641     LLVM_FALLTHROUGH;
9642   case Builtin::BI__builtin_strcmp:
9643   case Builtin::BI__builtin_wcscmp:
9644   case Builtin::BI__builtin_strncmp:
9645   case Builtin::BI__builtin_wcsncmp:
9646   case Builtin::BI__builtin_memcmp:
9647   case Builtin::BI__builtin_bcmp:
9648   case Builtin::BI__builtin_wmemcmp: {
9649     LValue String1, String2;
9650     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
9651         !EvaluatePointer(E->getArg(1), String2, Info))
9652       return false;
9653 
9654     uint64_t MaxLength = uint64_t(-1);
9655     if (BuiltinOp != Builtin::BIstrcmp &&
9656         BuiltinOp != Builtin::BIwcscmp &&
9657         BuiltinOp != Builtin::BI__builtin_strcmp &&
9658         BuiltinOp != Builtin::BI__builtin_wcscmp) {
9659       APSInt N;
9660       if (!EvaluateInteger(E->getArg(2), N, Info))
9661         return false;
9662       MaxLength = N.getExtValue();
9663     }
9664 
9665     // Empty substrings compare equal by definition.
9666     if (MaxLength == 0u)
9667       return Success(0, E);
9668 
9669     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9670         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9671         String1.Designator.Invalid || String2.Designator.Invalid)
9672       return false;
9673 
9674     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
9675     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
9676 
9677     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
9678                      BuiltinOp == Builtin::BIbcmp ||
9679                      BuiltinOp == Builtin::BI__builtin_memcmp ||
9680                      BuiltinOp == Builtin::BI__builtin_bcmp;
9681 
9682     assert(IsRawByte ||
9683            (Info.Ctx.hasSameUnqualifiedType(
9684                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
9685             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
9686 
9687     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
9688       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
9689              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
9690              Char1.isInt() && Char2.isInt();
9691     };
9692     const auto &AdvanceElems = [&] {
9693       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
9694              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
9695     };
9696 
9697     if (IsRawByte) {
9698       uint64_t BytesRemaining = MaxLength;
9699       // Pointers to const void may point to objects of incomplete type.
9700       if (CharTy1->isIncompleteType()) {
9701         Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
9702         return false;
9703       }
9704       if (CharTy2->isIncompleteType()) {
9705         Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
9706         return false;
9707       }
9708       uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
9709       CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
9710       // Give up on comparing between elements with disparate widths.
9711       if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
9712         return false;
9713       uint64_t BytesPerElement = CharTy1Size.getQuantity();
9714       assert(BytesRemaining && "BytesRemaining should not be zero: the "
9715                                "following loop considers at least one element");
9716       while (true) {
9717         APValue Char1, Char2;
9718         if (!ReadCurElems(Char1, Char2))
9719           return false;
9720         // We have compatible in-memory widths, but a possible type and
9721         // (for `bool`) internal representation mismatch.
9722         // Assuming two's complement representation, including 0 for `false` and
9723         // 1 for `true`, we can check an appropriate number of elements for
9724         // equality even if they are not byte-sized.
9725         APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
9726         APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
9727         if (Char1InMem.ne(Char2InMem)) {
9728           // If the elements are byte-sized, then we can produce a three-way
9729           // comparison result in a straightforward manner.
9730           if (BytesPerElement == 1u) {
9731             // memcmp always compares unsigned chars.
9732             return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
9733           }
9734           // The result is byte-order sensitive, and we have multibyte elements.
9735           // FIXME: We can compare the remaining bytes in the correct order.
9736           return false;
9737         }
9738         if (!AdvanceElems())
9739           return false;
9740         if (BytesRemaining <= BytesPerElement)
9741           break;
9742         BytesRemaining -= BytesPerElement;
9743       }
9744       // Enough elements are equal to account for the memcmp limit.
9745       return Success(0, E);
9746     }
9747 
9748     bool StopAtNull =
9749         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
9750          BuiltinOp != Builtin::BIwmemcmp &&
9751          BuiltinOp != Builtin::BI__builtin_memcmp &&
9752          BuiltinOp != Builtin::BI__builtin_bcmp &&
9753          BuiltinOp != Builtin::BI__builtin_wmemcmp);
9754     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
9755                   BuiltinOp == Builtin::BIwcsncmp ||
9756                   BuiltinOp == Builtin::BIwmemcmp ||
9757                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
9758                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
9759                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
9760 
9761     for (; MaxLength; --MaxLength) {
9762       APValue Char1, Char2;
9763       if (!ReadCurElems(Char1, Char2))
9764         return false;
9765       if (Char1.getInt() != Char2.getInt()) {
9766         if (IsWide) // wmemcmp compares with wchar_t signedness.
9767           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
9768         // memcmp always compares unsigned chars.
9769         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
9770       }
9771       if (StopAtNull && !Char1.getInt())
9772         return Success(0, E);
9773       assert(!(StopAtNull && !Char2.getInt()));
9774       if (!AdvanceElems())
9775         return false;
9776     }
9777     // We hit the strncmp / memcmp limit.
9778     return Success(0, E);
9779   }
9780 
9781   case Builtin::BI__atomic_always_lock_free:
9782   case Builtin::BI__atomic_is_lock_free:
9783   case Builtin::BI__c11_atomic_is_lock_free: {
9784     APSInt SizeVal;
9785     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
9786       return false;
9787 
9788     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
9789     // of two less than the maximum inline atomic width, we know it is
9790     // lock-free.  If the size isn't a power of two, or greater than the
9791     // maximum alignment where we promote atomics, we know it is not lock-free
9792     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
9793     // the answer can only be determined at runtime; for example, 16-byte
9794     // atomics have lock-free implementations on some, but not all,
9795     // x86-64 processors.
9796 
9797     // Check power-of-two.
9798     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
9799     if (Size.isPowerOfTwo()) {
9800       // Check against inlining width.
9801       unsigned InlineWidthBits =
9802           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
9803       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
9804         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
9805             Size == CharUnits::One() ||
9806             E->getArg(1)->isNullPointerConstant(Info.Ctx,
9807                                                 Expr::NPC_NeverValueDependent))
9808           // OK, we will inline appropriately-aligned operations of this size,
9809           // and _Atomic(T) is appropriately-aligned.
9810           return Success(1, E);
9811 
9812         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
9813           castAs<PointerType>()->getPointeeType();
9814         if (!PointeeType->isIncompleteType() &&
9815             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
9816           // OK, we will inline operations on this object.
9817           return Success(1, E);
9818         }
9819       }
9820     }
9821 
9822     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
9823         Success(0, E) : Error(E);
9824   }
9825   case Builtin::BIomp_is_initial_device:
9826     // We can decide statically which value the runtime would return if called.
9827     return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
9828   case Builtin::BI__builtin_add_overflow:
9829   case Builtin::BI__builtin_sub_overflow:
9830   case Builtin::BI__builtin_mul_overflow:
9831   case Builtin::BI__builtin_sadd_overflow:
9832   case Builtin::BI__builtin_uadd_overflow:
9833   case Builtin::BI__builtin_uaddl_overflow:
9834   case Builtin::BI__builtin_uaddll_overflow:
9835   case Builtin::BI__builtin_usub_overflow:
9836   case Builtin::BI__builtin_usubl_overflow:
9837   case Builtin::BI__builtin_usubll_overflow:
9838   case Builtin::BI__builtin_umul_overflow:
9839   case Builtin::BI__builtin_umull_overflow:
9840   case Builtin::BI__builtin_umulll_overflow:
9841   case Builtin::BI__builtin_saddl_overflow:
9842   case Builtin::BI__builtin_saddll_overflow:
9843   case Builtin::BI__builtin_ssub_overflow:
9844   case Builtin::BI__builtin_ssubl_overflow:
9845   case Builtin::BI__builtin_ssubll_overflow:
9846   case Builtin::BI__builtin_smul_overflow:
9847   case Builtin::BI__builtin_smull_overflow:
9848   case Builtin::BI__builtin_smulll_overflow: {
9849     LValue ResultLValue;
9850     APSInt LHS, RHS;
9851 
9852     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
9853     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
9854         !EvaluateInteger(E->getArg(1), RHS, Info) ||
9855         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
9856       return false;
9857 
9858     APSInt Result;
9859     bool DidOverflow = false;
9860 
9861     // If the types don't have to match, enlarge all 3 to the largest of them.
9862     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
9863         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
9864         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
9865       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
9866                       ResultType->isSignedIntegerOrEnumerationType();
9867       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
9868                       ResultType->isSignedIntegerOrEnumerationType();
9869       uint64_t LHSSize = LHS.getBitWidth();
9870       uint64_t RHSSize = RHS.getBitWidth();
9871       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
9872       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
9873 
9874       // Add an additional bit if the signedness isn't uniformly agreed to. We
9875       // could do this ONLY if there is a signed and an unsigned that both have
9876       // MaxBits, but the code to check that is pretty nasty.  The issue will be
9877       // caught in the shrink-to-result later anyway.
9878       if (IsSigned && !AllSigned)
9879         ++MaxBits;
9880 
9881       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
9882       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
9883       Result = APSInt(MaxBits, !IsSigned);
9884     }
9885 
9886     // Find largest int.
9887     switch (BuiltinOp) {
9888     default:
9889       llvm_unreachable("Invalid value for BuiltinOp");
9890     case Builtin::BI__builtin_add_overflow:
9891     case Builtin::BI__builtin_sadd_overflow:
9892     case Builtin::BI__builtin_saddl_overflow:
9893     case Builtin::BI__builtin_saddll_overflow:
9894     case Builtin::BI__builtin_uadd_overflow:
9895     case Builtin::BI__builtin_uaddl_overflow:
9896     case Builtin::BI__builtin_uaddll_overflow:
9897       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
9898                               : LHS.uadd_ov(RHS, DidOverflow);
9899       break;
9900     case Builtin::BI__builtin_sub_overflow:
9901     case Builtin::BI__builtin_ssub_overflow:
9902     case Builtin::BI__builtin_ssubl_overflow:
9903     case Builtin::BI__builtin_ssubll_overflow:
9904     case Builtin::BI__builtin_usub_overflow:
9905     case Builtin::BI__builtin_usubl_overflow:
9906     case Builtin::BI__builtin_usubll_overflow:
9907       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
9908                               : LHS.usub_ov(RHS, DidOverflow);
9909       break;
9910     case Builtin::BI__builtin_mul_overflow:
9911     case Builtin::BI__builtin_smul_overflow:
9912     case Builtin::BI__builtin_smull_overflow:
9913     case Builtin::BI__builtin_smulll_overflow:
9914     case Builtin::BI__builtin_umul_overflow:
9915     case Builtin::BI__builtin_umull_overflow:
9916     case Builtin::BI__builtin_umulll_overflow:
9917       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
9918                               : LHS.umul_ov(RHS, DidOverflow);
9919       break;
9920     }
9921 
9922     // In the case where multiple sizes are allowed, truncate and see if
9923     // the values are the same.
9924     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
9925         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
9926         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
9927       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
9928       // since it will give us the behavior of a TruncOrSelf in the case where
9929       // its parameter <= its size.  We previously set Result to be at least the
9930       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
9931       // will work exactly like TruncOrSelf.
9932       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
9933       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
9934 
9935       if (!APSInt::isSameValue(Temp, Result))
9936         DidOverflow = true;
9937       Result = Temp;
9938     }
9939 
9940     APValue APV{Result};
9941     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
9942       return false;
9943     return Success(DidOverflow, E);
9944   }
9945   }
9946 }
9947 
9948 /// Determine whether this is a pointer past the end of the complete
9949 /// object referred to by the lvalue.
9950 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
9951                                             const LValue &LV) {
9952   // A null pointer can be viewed as being "past the end" but we don't
9953   // choose to look at it that way here.
9954   if (!LV.getLValueBase())
9955     return false;
9956 
9957   // If the designator is valid and refers to a subobject, we're not pointing
9958   // past the end.
9959   if (!LV.getLValueDesignator().Invalid &&
9960       !LV.getLValueDesignator().isOnePastTheEnd())
9961     return false;
9962 
9963   // A pointer to an incomplete type might be past-the-end if the type's size is
9964   // zero.  We cannot tell because the type is incomplete.
9965   QualType Ty = getType(LV.getLValueBase());
9966   if (Ty->isIncompleteType())
9967     return true;
9968 
9969   // We're a past-the-end pointer if we point to the byte after the object,
9970   // no matter what our type or path is.
9971   auto Size = Ctx.getTypeSizeInChars(Ty);
9972   return LV.getLValueOffset() == Size;
9973 }
9974 
9975 namespace {
9976 
9977 /// Data recursive integer evaluator of certain binary operators.
9978 ///
9979 /// We use a data recursive algorithm for binary operators so that we are able
9980 /// to handle extreme cases of chained binary operators without causing stack
9981 /// overflow.
9982 class DataRecursiveIntBinOpEvaluator {
9983   struct EvalResult {
9984     APValue Val;
9985     bool Failed;
9986 
9987     EvalResult() : Failed(false) { }
9988 
9989     void swap(EvalResult &RHS) {
9990       Val.swap(RHS.Val);
9991       Failed = RHS.Failed;
9992       RHS.Failed = false;
9993     }
9994   };
9995 
9996   struct Job {
9997     const Expr *E;
9998     EvalResult LHSResult; // meaningful only for binary operator expression.
9999     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
10000 
10001     Job() = default;
10002     Job(Job &&) = default;
10003 
10004     void startSpeculativeEval(EvalInfo &Info) {
10005       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
10006     }
10007 
10008   private:
10009     SpeculativeEvaluationRAII SpecEvalRAII;
10010   };
10011 
10012   SmallVector<Job, 16> Queue;
10013 
10014   IntExprEvaluator &IntEval;
10015   EvalInfo &Info;
10016   APValue &FinalResult;
10017 
10018 public:
10019   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
10020     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
10021 
10022   /// True if \param E is a binary operator that we are going to handle
10023   /// data recursively.
10024   /// We handle binary operators that are comma, logical, or that have operands
10025   /// with integral or enumeration type.
10026   static bool shouldEnqueue(const BinaryOperator *E) {
10027     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
10028            (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
10029             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10030             E->getRHS()->getType()->isIntegralOrEnumerationType());
10031   }
10032 
10033   bool Traverse(const BinaryOperator *E) {
10034     enqueue(E);
10035     EvalResult PrevResult;
10036     while (!Queue.empty())
10037       process(PrevResult);
10038 
10039     if (PrevResult.Failed) return false;
10040 
10041     FinalResult.swap(PrevResult.Val);
10042     return true;
10043   }
10044 
10045 private:
10046   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10047     return IntEval.Success(Value, E, Result);
10048   }
10049   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
10050     return IntEval.Success(Value, E, Result);
10051   }
10052   bool Error(const Expr *E) {
10053     return IntEval.Error(E);
10054   }
10055   bool Error(const Expr *E, diag::kind D) {
10056     return IntEval.Error(E, D);
10057   }
10058 
10059   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
10060     return Info.CCEDiag(E, D);
10061   }
10062 
10063   // Returns true if visiting the RHS is necessary, false otherwise.
10064   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
10065                          bool &SuppressRHSDiags);
10066 
10067   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
10068                   const BinaryOperator *E, APValue &Result);
10069 
10070   void EvaluateExpr(const Expr *E, EvalResult &Result) {
10071     Result.Failed = !Evaluate(Result.Val, Info, E);
10072     if (Result.Failed)
10073       Result.Val = APValue();
10074   }
10075 
10076   void process(EvalResult &Result);
10077 
10078   void enqueue(const Expr *E) {
10079     E = E->IgnoreParens();
10080     Queue.resize(Queue.size()+1);
10081     Queue.back().E = E;
10082     Queue.back().Kind = Job::AnyExprKind;
10083   }
10084 };
10085 
10086 }
10087 
10088 bool DataRecursiveIntBinOpEvaluator::
10089        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
10090                          bool &SuppressRHSDiags) {
10091   if (E->getOpcode() == BO_Comma) {
10092     // Ignore LHS but note if we could not evaluate it.
10093     if (LHSResult.Failed)
10094       return Info.noteSideEffect();
10095     return true;
10096   }
10097 
10098   if (E->isLogicalOp()) {
10099     bool LHSAsBool;
10100     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
10101       // We were able to evaluate the LHS, see if we can get away with not
10102       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
10103       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
10104         Success(LHSAsBool, E, LHSResult.Val);
10105         return false; // Ignore RHS
10106       }
10107     } else {
10108       LHSResult.Failed = true;
10109 
10110       // Since we weren't able to evaluate the left hand side, it
10111       // might have had side effects.
10112       if (!Info.noteSideEffect())
10113         return false;
10114 
10115       // We can't evaluate the LHS; however, sometimes the result
10116       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
10117       // Don't ignore RHS and suppress diagnostics from this arm.
10118       SuppressRHSDiags = true;
10119     }
10120 
10121     return true;
10122   }
10123 
10124   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10125          E->getRHS()->getType()->isIntegralOrEnumerationType());
10126 
10127   if (LHSResult.Failed && !Info.noteFailure())
10128     return false; // Ignore RHS;
10129 
10130   return true;
10131 }
10132 
10133 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
10134                                     bool IsSub) {
10135   // Compute the new offset in the appropriate width, wrapping at 64 bits.
10136   // FIXME: When compiling for a 32-bit target, we should use 32-bit
10137   // offsets.
10138   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
10139   CharUnits &Offset = LVal.getLValueOffset();
10140   uint64_t Offset64 = Offset.getQuantity();
10141   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
10142   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
10143                                          : Offset64 + Index64);
10144 }
10145 
10146 bool DataRecursiveIntBinOpEvaluator::
10147        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
10148                   const BinaryOperator *E, APValue &Result) {
10149   if (E->getOpcode() == BO_Comma) {
10150     if (RHSResult.Failed)
10151       return false;
10152     Result = RHSResult.Val;
10153     return true;
10154   }
10155 
10156   if (E->isLogicalOp()) {
10157     bool lhsResult, rhsResult;
10158     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
10159     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
10160 
10161     if (LHSIsOK) {
10162       if (RHSIsOK) {
10163         if (E->getOpcode() == BO_LOr)
10164           return Success(lhsResult || rhsResult, E, Result);
10165         else
10166           return Success(lhsResult && rhsResult, E, Result);
10167       }
10168     } else {
10169       if (RHSIsOK) {
10170         // We can't evaluate the LHS; however, sometimes the result
10171         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
10172         if (rhsResult == (E->getOpcode() == BO_LOr))
10173           return Success(rhsResult, E, Result);
10174       }
10175     }
10176 
10177     return false;
10178   }
10179 
10180   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10181          E->getRHS()->getType()->isIntegralOrEnumerationType());
10182 
10183   if (LHSResult.Failed || RHSResult.Failed)
10184     return false;
10185 
10186   const APValue &LHSVal = LHSResult.Val;
10187   const APValue &RHSVal = RHSResult.Val;
10188 
10189   // Handle cases like (unsigned long)&a + 4.
10190   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
10191     Result = LHSVal;
10192     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
10193     return true;
10194   }
10195 
10196   // Handle cases like 4 + (unsigned long)&a
10197   if (E->getOpcode() == BO_Add &&
10198       RHSVal.isLValue() && LHSVal.isInt()) {
10199     Result = RHSVal;
10200     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
10201     return true;
10202   }
10203 
10204   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
10205     // Handle (intptr_t)&&A - (intptr_t)&&B.
10206     if (!LHSVal.getLValueOffset().isZero() ||
10207         !RHSVal.getLValueOffset().isZero())
10208       return false;
10209     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
10210     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
10211     if (!LHSExpr || !RHSExpr)
10212       return false;
10213     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
10214     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
10215     if (!LHSAddrExpr || !RHSAddrExpr)
10216       return false;
10217     // Make sure both labels come from the same function.
10218     if (LHSAddrExpr->getLabel()->getDeclContext() !=
10219         RHSAddrExpr->getLabel()->getDeclContext())
10220       return false;
10221     Result = APValue(LHSAddrExpr, RHSAddrExpr);
10222     return true;
10223   }
10224 
10225   // All the remaining cases expect both operands to be an integer
10226   if (!LHSVal.isInt() || !RHSVal.isInt())
10227     return Error(E);
10228 
10229   // Set up the width and signedness manually, in case it can't be deduced
10230   // from the operation we're performing.
10231   // FIXME: Don't do this in the cases where we can deduce it.
10232   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
10233                E->getType()->isUnsignedIntegerOrEnumerationType());
10234   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
10235                          RHSVal.getInt(), Value))
10236     return false;
10237   return Success(Value, E, Result);
10238 }
10239 
10240 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
10241   Job &job = Queue.back();
10242 
10243   switch (job.Kind) {
10244     case Job::AnyExprKind: {
10245       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
10246         if (shouldEnqueue(Bop)) {
10247           job.Kind = Job::BinOpKind;
10248           enqueue(Bop->getLHS());
10249           return;
10250         }
10251       }
10252 
10253       EvaluateExpr(job.E, Result);
10254       Queue.pop_back();
10255       return;
10256     }
10257 
10258     case Job::BinOpKind: {
10259       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
10260       bool SuppressRHSDiags = false;
10261       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
10262         Queue.pop_back();
10263         return;
10264       }
10265       if (SuppressRHSDiags)
10266         job.startSpeculativeEval(Info);
10267       job.LHSResult.swap(Result);
10268       job.Kind = Job::BinOpVisitedLHSKind;
10269       enqueue(Bop->getRHS());
10270       return;
10271     }
10272 
10273     case Job::BinOpVisitedLHSKind: {
10274       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
10275       EvalResult RHS;
10276       RHS.swap(Result);
10277       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
10278       Queue.pop_back();
10279       return;
10280     }
10281   }
10282 
10283   llvm_unreachable("Invalid Job::Kind!");
10284 }
10285 
10286 namespace {
10287 /// Used when we determine that we should fail, but can keep evaluating prior to
10288 /// noting that we had a failure.
10289 class DelayedNoteFailureRAII {
10290   EvalInfo &Info;
10291   bool NoteFailure;
10292 
10293 public:
10294   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
10295       : Info(Info), NoteFailure(NoteFailure) {}
10296   ~DelayedNoteFailureRAII() {
10297     if (NoteFailure) {
10298       bool ContinueAfterFailure = Info.noteFailure();
10299       (void)ContinueAfterFailure;
10300       assert(ContinueAfterFailure &&
10301              "Shouldn't have kept evaluating on failure.");
10302     }
10303   }
10304 };
10305 }
10306 
10307 template <class SuccessCB, class AfterCB>
10308 static bool
10309 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
10310                                  SuccessCB &&Success, AfterCB &&DoAfter) {
10311   assert(E->isComparisonOp() && "expected comparison operator");
10312   assert((E->getOpcode() == BO_Cmp ||
10313           E->getType()->isIntegralOrEnumerationType()) &&
10314          "unsupported binary expression evaluation");
10315   auto Error = [&](const Expr *E) {
10316     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10317     return false;
10318   };
10319 
10320   using CCR = ComparisonCategoryResult;
10321   bool IsRelational = E->isRelationalOp();
10322   bool IsEquality = E->isEqualityOp();
10323   if (E->getOpcode() == BO_Cmp) {
10324     const ComparisonCategoryInfo &CmpInfo =
10325         Info.Ctx.CompCategories.getInfoForType(E->getType());
10326     IsRelational = CmpInfo.isOrdered();
10327     IsEquality = CmpInfo.isEquality();
10328   }
10329 
10330   QualType LHSTy = E->getLHS()->getType();
10331   QualType RHSTy = E->getRHS()->getType();
10332 
10333   if (LHSTy->isIntegralOrEnumerationType() &&
10334       RHSTy->isIntegralOrEnumerationType()) {
10335     APSInt LHS, RHS;
10336     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
10337     if (!LHSOK && !Info.noteFailure())
10338       return false;
10339     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
10340       return false;
10341     if (LHS < RHS)
10342       return Success(CCR::Less, E);
10343     if (LHS > RHS)
10344       return Success(CCR::Greater, E);
10345     return Success(CCR::Equal, E);
10346   }
10347 
10348   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
10349     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
10350     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
10351 
10352     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
10353     if (!LHSOK && !Info.noteFailure())
10354       return false;
10355     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
10356       return false;
10357     if (LHSFX < RHSFX)
10358       return Success(CCR::Less, E);
10359     if (LHSFX > RHSFX)
10360       return Success(CCR::Greater, E);
10361     return Success(CCR::Equal, E);
10362   }
10363 
10364   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
10365     ComplexValue LHS, RHS;
10366     bool LHSOK;
10367     if (E->isAssignmentOp()) {
10368       LValue LV;
10369       EvaluateLValue(E->getLHS(), LV, Info);
10370       LHSOK = false;
10371     } else if (LHSTy->isRealFloatingType()) {
10372       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
10373       if (LHSOK) {
10374         LHS.makeComplexFloat();
10375         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
10376       }
10377     } else {
10378       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
10379     }
10380     if (!LHSOK && !Info.noteFailure())
10381       return false;
10382 
10383     if (E->getRHS()->getType()->isRealFloatingType()) {
10384       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
10385         return false;
10386       RHS.makeComplexFloat();
10387       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
10388     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
10389       return false;
10390 
10391     if (LHS.isComplexFloat()) {
10392       APFloat::cmpResult CR_r =
10393         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
10394       APFloat::cmpResult CR_i =
10395         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
10396       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
10397       return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
10398     } else {
10399       assert(IsEquality && "invalid complex comparison");
10400       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
10401                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
10402       return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
10403     }
10404   }
10405 
10406   if (LHSTy->isRealFloatingType() &&
10407       RHSTy->isRealFloatingType()) {
10408     APFloat RHS(0.0), LHS(0.0);
10409 
10410     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
10411     if (!LHSOK && !Info.noteFailure())
10412       return false;
10413 
10414     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
10415       return false;
10416 
10417     assert(E->isComparisonOp() && "Invalid binary operator!");
10418     auto GetCmpRes = [&]() {
10419       switch (LHS.compare(RHS)) {
10420       case APFloat::cmpEqual:
10421         return CCR::Equal;
10422       case APFloat::cmpLessThan:
10423         return CCR::Less;
10424       case APFloat::cmpGreaterThan:
10425         return CCR::Greater;
10426       case APFloat::cmpUnordered:
10427         return CCR::Unordered;
10428       }
10429       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
10430     };
10431     return Success(GetCmpRes(), E);
10432   }
10433 
10434   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
10435     LValue LHSValue, RHSValue;
10436 
10437     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10438     if (!LHSOK && !Info.noteFailure())
10439       return false;
10440 
10441     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10442       return false;
10443 
10444     // Reject differing bases from the normal codepath; we special-case
10445     // comparisons to null.
10446     if (!HasSameBase(LHSValue, RHSValue)) {
10447       // Inequalities and subtractions between unrelated pointers have
10448       // unspecified or undefined behavior.
10449       if (!IsEquality)
10450         return Error(E);
10451       // A constant address may compare equal to the address of a symbol.
10452       // The one exception is that address of an object cannot compare equal
10453       // to a null pointer constant.
10454       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
10455           (!RHSValue.Base && !RHSValue.Offset.isZero()))
10456         return Error(E);
10457       // It's implementation-defined whether distinct literals will have
10458       // distinct addresses. In clang, the result of such a comparison is
10459       // unspecified, so it is not a constant expression. However, we do know
10460       // that the address of a literal will be non-null.
10461       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
10462           LHSValue.Base && RHSValue.Base)
10463         return Error(E);
10464       // We can't tell whether weak symbols will end up pointing to the same
10465       // object.
10466       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
10467         return Error(E);
10468       // We can't compare the address of the start of one object with the
10469       // past-the-end address of another object, per C++ DR1652.
10470       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
10471            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
10472           (RHSValue.Base && RHSValue.Offset.isZero() &&
10473            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
10474         return Error(E);
10475       // We can't tell whether an object is at the same address as another
10476       // zero sized object.
10477       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
10478           (LHSValue.Base && isZeroSized(RHSValue)))
10479         return Error(E);
10480       return Success(CCR::Nonequal, E);
10481     }
10482 
10483     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10484     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
10485 
10486     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10487     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
10488 
10489     // C++11 [expr.rel]p3:
10490     //   Pointers to void (after pointer conversions) can be compared, with a
10491     //   result defined as follows: If both pointers represent the same
10492     //   address or are both the null pointer value, the result is true if the
10493     //   operator is <= or >= and false otherwise; otherwise the result is
10494     //   unspecified.
10495     // We interpret this as applying to pointers to *cv* void.
10496     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
10497       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
10498 
10499     // C++11 [expr.rel]p2:
10500     // - If two pointers point to non-static data members of the same object,
10501     //   or to subobjects or array elements fo such members, recursively, the
10502     //   pointer to the later declared member compares greater provided the
10503     //   two members have the same access control and provided their class is
10504     //   not a union.
10505     //   [...]
10506     // - Otherwise pointer comparisons are unspecified.
10507     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
10508       bool WasArrayIndex;
10509       unsigned Mismatch = FindDesignatorMismatch(
10510           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
10511       // At the point where the designators diverge, the comparison has a
10512       // specified value if:
10513       //  - we are comparing array indices
10514       //  - we are comparing fields of a union, or fields with the same access
10515       // Otherwise, the result is unspecified and thus the comparison is not a
10516       // constant expression.
10517       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
10518           Mismatch < RHSDesignator.Entries.size()) {
10519         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
10520         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
10521         if (!LF && !RF)
10522           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
10523         else if (!LF)
10524           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
10525               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
10526               << RF->getParent() << RF;
10527         else if (!RF)
10528           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
10529               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
10530               << LF->getParent() << LF;
10531         else if (!LF->getParent()->isUnion() &&
10532                  LF->getAccess() != RF->getAccess())
10533           Info.CCEDiag(E,
10534                        diag::note_constexpr_pointer_comparison_differing_access)
10535               << LF << LF->getAccess() << RF << RF->getAccess()
10536               << LF->getParent();
10537       }
10538     }
10539 
10540     // The comparison here must be unsigned, and performed with the same
10541     // width as the pointer.
10542     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
10543     uint64_t CompareLHS = LHSOffset.getQuantity();
10544     uint64_t CompareRHS = RHSOffset.getQuantity();
10545     assert(PtrSize <= 64 && "Unexpected pointer width");
10546     uint64_t Mask = ~0ULL >> (64 - PtrSize);
10547     CompareLHS &= Mask;
10548     CompareRHS &= Mask;
10549 
10550     // If there is a base and this is a relational operator, we can only
10551     // compare pointers within the object in question; otherwise, the result
10552     // depends on where the object is located in memory.
10553     if (!LHSValue.Base.isNull() && IsRelational) {
10554       QualType BaseTy = getType(LHSValue.Base);
10555       if (BaseTy->isIncompleteType())
10556         return Error(E);
10557       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
10558       uint64_t OffsetLimit = Size.getQuantity();
10559       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
10560         return Error(E);
10561     }
10562 
10563     if (CompareLHS < CompareRHS)
10564       return Success(CCR::Less, E);
10565     if (CompareLHS > CompareRHS)
10566       return Success(CCR::Greater, E);
10567     return Success(CCR::Equal, E);
10568   }
10569 
10570   if (LHSTy->isMemberPointerType()) {
10571     assert(IsEquality && "unexpected member pointer operation");
10572     assert(RHSTy->isMemberPointerType() && "invalid comparison");
10573 
10574     MemberPtr LHSValue, RHSValue;
10575 
10576     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
10577     if (!LHSOK && !Info.noteFailure())
10578       return false;
10579 
10580     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10581       return false;
10582 
10583     // C++11 [expr.eq]p2:
10584     //   If both operands are null, they compare equal. Otherwise if only one is
10585     //   null, they compare unequal.
10586     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
10587       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
10588       return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
10589     }
10590 
10591     //   Otherwise if either is a pointer to a virtual member function, the
10592     //   result is unspecified.
10593     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
10594       if (MD->isVirtual())
10595         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
10596     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
10597       if (MD->isVirtual())
10598         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
10599 
10600     //   Otherwise they compare equal if and only if they would refer to the
10601     //   same member of the same most derived object or the same subobject if
10602     //   they were dereferenced with a hypothetical object of the associated
10603     //   class type.
10604     bool Equal = LHSValue == RHSValue;
10605     return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
10606   }
10607 
10608   if (LHSTy->isNullPtrType()) {
10609     assert(E->isComparisonOp() && "unexpected nullptr operation");
10610     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
10611     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
10612     // are compared, the result is true of the operator is <=, >= or ==, and
10613     // false otherwise.
10614     return Success(CCR::Equal, E);
10615   }
10616 
10617   return DoAfter();
10618 }
10619 
10620 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
10621   if (!CheckLiteralType(Info, E))
10622     return false;
10623 
10624   auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10625                        const BinaryOperator *E) {
10626     // Evaluation succeeded. Lookup the information for the comparison category
10627     // type and fetch the VarDecl for the result.
10628     const ComparisonCategoryInfo &CmpInfo =
10629         Info.Ctx.CompCategories.getInfoForType(E->getType());
10630     const VarDecl *VD =
10631         CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
10632     // Check and evaluate the result as a constant expression.
10633     LValue LV;
10634     LV.set(VD);
10635     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
10636       return false;
10637     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
10638   };
10639   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10640     return ExprEvaluatorBaseTy::VisitBinCmp(E);
10641   });
10642 }
10643 
10644 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10645   // We don't call noteFailure immediately because the assignment happens after
10646   // we evaluate LHS and RHS.
10647   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
10648     return Error(E);
10649 
10650   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
10651   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
10652     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
10653 
10654   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
10655           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
10656          "DataRecursiveIntBinOpEvaluator should have handled integral types");
10657 
10658   if (E->isComparisonOp()) {
10659     // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
10660     // comparisons and then translating the result.
10661     auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10662                          const BinaryOperator *E) {
10663       using CCR = ComparisonCategoryResult;
10664       bool IsEqual   = ResKind == CCR::Equal,
10665            IsLess    = ResKind == CCR::Less,
10666            IsGreater = ResKind == CCR::Greater;
10667       auto Op = E->getOpcode();
10668       switch (Op) {
10669       default:
10670         llvm_unreachable("unsupported binary operator");
10671       case BO_EQ:
10672       case BO_NE:
10673         return Success(IsEqual == (Op == BO_EQ), E);
10674       case BO_LT: return Success(IsLess, E);
10675       case BO_GT: return Success(IsGreater, E);
10676       case BO_LE: return Success(IsEqual || IsLess, E);
10677       case BO_GE: return Success(IsEqual || IsGreater, E);
10678       }
10679     };
10680     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10681       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10682     });
10683   }
10684 
10685   QualType LHSTy = E->getLHS()->getType();
10686   QualType RHSTy = E->getRHS()->getType();
10687 
10688   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
10689       E->getOpcode() == BO_Sub) {
10690     LValue LHSValue, RHSValue;
10691 
10692     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10693     if (!LHSOK && !Info.noteFailure())
10694       return false;
10695 
10696     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10697       return false;
10698 
10699     // Reject differing bases from the normal codepath; we special-case
10700     // comparisons to null.
10701     if (!HasSameBase(LHSValue, RHSValue)) {
10702       // Handle &&A - &&B.
10703       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
10704         return Error(E);
10705       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
10706       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
10707       if (!LHSExpr || !RHSExpr)
10708         return Error(E);
10709       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
10710       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
10711       if (!LHSAddrExpr || !RHSAddrExpr)
10712         return Error(E);
10713       // Make sure both labels come from the same function.
10714       if (LHSAddrExpr->getLabel()->getDeclContext() !=
10715           RHSAddrExpr->getLabel()->getDeclContext())
10716         return Error(E);
10717       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
10718     }
10719     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10720     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
10721 
10722     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10723     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
10724 
10725     // C++11 [expr.add]p6:
10726     //   Unless both pointers point to elements of the same array object, or
10727     //   one past the last element of the array object, the behavior is
10728     //   undefined.
10729     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
10730         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
10731                                 RHSDesignator))
10732       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
10733 
10734     QualType Type = E->getLHS()->getType();
10735     QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
10736 
10737     CharUnits ElementSize;
10738     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
10739       return false;
10740 
10741     // As an extension, a type may have zero size (empty struct or union in
10742     // C, array of zero length). Pointer subtraction in such cases has
10743     // undefined behavior, so is not constant.
10744     if (ElementSize.isZero()) {
10745       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
10746           << ElementType;
10747       return false;
10748     }
10749 
10750     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
10751     // and produce incorrect results when it overflows. Such behavior
10752     // appears to be non-conforming, but is common, so perhaps we should
10753     // assume the standard intended for such cases to be undefined behavior
10754     // and check for them.
10755 
10756     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
10757     // overflow in the final conversion to ptrdiff_t.
10758     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
10759     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
10760     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
10761                     false);
10762     APSInt TrueResult = (LHS - RHS) / ElemSize;
10763     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
10764 
10765     if (Result.extend(65) != TrueResult &&
10766         !HandleOverflow(Info, E, TrueResult, E->getType()))
10767       return false;
10768     return Success(Result, E);
10769   }
10770 
10771   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10772 }
10773 
10774 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
10775 /// a result as the expression's type.
10776 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
10777                                     const UnaryExprOrTypeTraitExpr *E) {
10778   switch(E->getKind()) {
10779   case UETT_PreferredAlignOf:
10780   case UETT_AlignOf: {
10781     if (E->isArgumentType())
10782       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
10783                      E);
10784     else
10785       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
10786                      E);
10787   }
10788 
10789   case UETT_VecStep: {
10790     QualType Ty = E->getTypeOfArgument();
10791 
10792     if (Ty->isVectorType()) {
10793       unsigned n = Ty->castAs<VectorType>()->getNumElements();
10794 
10795       // The vec_step built-in functions that take a 3-component
10796       // vector return 4. (OpenCL 1.1 spec 6.11.12)
10797       if (n == 3)
10798         n = 4;
10799 
10800       return Success(n, E);
10801     } else
10802       return Success(1, E);
10803   }
10804 
10805   case UETT_SizeOf: {
10806     QualType SrcTy = E->getTypeOfArgument();
10807     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
10808     //   the result is the size of the referenced type."
10809     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
10810       SrcTy = Ref->getPointeeType();
10811 
10812     CharUnits Sizeof;
10813     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
10814       return false;
10815     return Success(Sizeof, E);
10816   }
10817   case UETT_OpenMPRequiredSimdAlign:
10818     assert(E->isArgumentType());
10819     return Success(
10820         Info.Ctx.toCharUnitsFromBits(
10821                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
10822             .getQuantity(),
10823         E);
10824   }
10825 
10826   llvm_unreachable("unknown expr/type trait");
10827 }
10828 
10829 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
10830   CharUnits Result;
10831   unsigned n = OOE->getNumComponents();
10832   if (n == 0)
10833     return Error(OOE);
10834   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
10835   for (unsigned i = 0; i != n; ++i) {
10836     OffsetOfNode ON = OOE->getComponent(i);
10837     switch (ON.getKind()) {
10838     case OffsetOfNode::Array: {
10839       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
10840       APSInt IdxResult;
10841       if (!EvaluateInteger(Idx, IdxResult, Info))
10842         return false;
10843       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
10844       if (!AT)
10845         return Error(OOE);
10846       CurrentType = AT->getElementType();
10847       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
10848       Result += IdxResult.getSExtValue() * ElementSize;
10849       break;
10850     }
10851 
10852     case OffsetOfNode::Field: {
10853       FieldDecl *MemberDecl = ON.getField();
10854       const RecordType *RT = CurrentType->getAs<RecordType>();
10855       if (!RT)
10856         return Error(OOE);
10857       RecordDecl *RD = RT->getDecl();
10858       if (RD->isInvalidDecl()) return false;
10859       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
10860       unsigned i = MemberDecl->getFieldIndex();
10861       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
10862       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
10863       CurrentType = MemberDecl->getType().getNonReferenceType();
10864       break;
10865     }
10866 
10867     case OffsetOfNode::Identifier:
10868       llvm_unreachable("dependent __builtin_offsetof");
10869 
10870     case OffsetOfNode::Base: {
10871       CXXBaseSpecifier *BaseSpec = ON.getBase();
10872       if (BaseSpec->isVirtual())
10873         return Error(OOE);
10874 
10875       // Find the layout of the class whose base we are looking into.
10876       const RecordType *RT = CurrentType->getAs<RecordType>();
10877       if (!RT)
10878         return Error(OOE);
10879       RecordDecl *RD = RT->getDecl();
10880       if (RD->isInvalidDecl()) return false;
10881       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
10882 
10883       // Find the base class itself.
10884       CurrentType = BaseSpec->getType();
10885       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
10886       if (!BaseRT)
10887         return Error(OOE);
10888 
10889       // Add the offset to the base.
10890       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
10891       break;
10892     }
10893     }
10894   }
10895   return Success(Result, OOE);
10896 }
10897 
10898 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10899   switch (E->getOpcode()) {
10900   default:
10901     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
10902     // See C99 6.6p3.
10903     return Error(E);
10904   case UO_Extension:
10905     // FIXME: Should extension allow i-c-e extension expressions in its scope?
10906     // If so, we could clear the diagnostic ID.
10907     return Visit(E->getSubExpr());
10908   case UO_Plus:
10909     // The result is just the value.
10910     return Visit(E->getSubExpr());
10911   case UO_Minus: {
10912     if (!Visit(E->getSubExpr()))
10913       return false;
10914     if (!Result.isInt()) return Error(E);
10915     const APSInt &Value = Result.getInt();
10916     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
10917         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
10918                         E->getType()))
10919       return false;
10920     return Success(-Value, E);
10921   }
10922   case UO_Not: {
10923     if (!Visit(E->getSubExpr()))
10924       return false;
10925     if (!Result.isInt()) return Error(E);
10926     return Success(~Result.getInt(), E);
10927   }
10928   case UO_LNot: {
10929     bool bres;
10930     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
10931       return false;
10932     return Success(!bres, E);
10933   }
10934   }
10935 }
10936 
10937 /// HandleCast - This is used to evaluate implicit or explicit casts where the
10938 /// result type is integer.
10939 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
10940   const Expr *SubExpr = E->getSubExpr();
10941   QualType DestType = E->getType();
10942   QualType SrcType = SubExpr->getType();
10943 
10944   switch (E->getCastKind()) {
10945   case CK_BaseToDerived:
10946   case CK_DerivedToBase:
10947   case CK_UncheckedDerivedToBase:
10948   case CK_Dynamic:
10949   case CK_ToUnion:
10950   case CK_ArrayToPointerDecay:
10951   case CK_FunctionToPointerDecay:
10952   case CK_NullToPointer:
10953   case CK_NullToMemberPointer:
10954   case CK_BaseToDerivedMemberPointer:
10955   case CK_DerivedToBaseMemberPointer:
10956   case CK_ReinterpretMemberPointer:
10957   case CK_ConstructorConversion:
10958   case CK_IntegralToPointer:
10959   case CK_ToVoid:
10960   case CK_VectorSplat:
10961   case CK_IntegralToFloating:
10962   case CK_FloatingCast:
10963   case CK_CPointerToObjCPointerCast:
10964   case CK_BlockPointerToObjCPointerCast:
10965   case CK_AnyPointerToBlockPointerCast:
10966   case CK_ObjCObjectLValueCast:
10967   case CK_FloatingRealToComplex:
10968   case CK_FloatingComplexToReal:
10969   case CK_FloatingComplexCast:
10970   case CK_FloatingComplexToIntegralComplex:
10971   case CK_IntegralRealToComplex:
10972   case CK_IntegralComplexCast:
10973   case CK_IntegralComplexToFloatingComplex:
10974   case CK_BuiltinFnToFnPtr:
10975   case CK_ZeroToOCLOpaqueType:
10976   case CK_NonAtomicToAtomic:
10977   case CK_AddressSpaceConversion:
10978   case CK_IntToOCLSampler:
10979   case CK_FixedPointCast:
10980   case CK_IntegralToFixedPoint:
10981     llvm_unreachable("invalid cast kind for integral value");
10982 
10983   case CK_BitCast:
10984   case CK_Dependent:
10985   case CK_LValueBitCast:
10986   case CK_ARCProduceObject:
10987   case CK_ARCConsumeObject:
10988   case CK_ARCReclaimReturnedObject:
10989   case CK_ARCExtendBlockObject:
10990   case CK_CopyAndAutoreleaseBlockObject:
10991     return Error(E);
10992 
10993   case CK_UserDefinedConversion:
10994   case CK_LValueToRValue:
10995   case CK_AtomicToNonAtomic:
10996   case CK_NoOp:
10997   case CK_LValueToRValueBitCast:
10998     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10999 
11000   case CK_MemberPointerToBoolean:
11001   case CK_PointerToBoolean:
11002   case CK_IntegralToBoolean:
11003   case CK_FloatingToBoolean:
11004   case CK_BooleanToSignedIntegral:
11005   case CK_FloatingComplexToBoolean:
11006   case CK_IntegralComplexToBoolean: {
11007     bool BoolResult;
11008     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
11009       return false;
11010     uint64_t IntResult = BoolResult;
11011     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
11012       IntResult = (uint64_t)-1;
11013     return Success(IntResult, E);
11014   }
11015 
11016   case CK_FixedPointToIntegral: {
11017     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
11018     if (!EvaluateFixedPoint(SubExpr, Src, Info))
11019       return false;
11020     bool Overflowed;
11021     llvm::APSInt Result = Src.convertToInt(
11022         Info.Ctx.getIntWidth(DestType),
11023         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
11024     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
11025       return false;
11026     return Success(Result, E);
11027   }
11028 
11029   case CK_FixedPointToBoolean: {
11030     // Unsigned padding does not affect this.
11031     APValue Val;
11032     if (!Evaluate(Val, Info, SubExpr))
11033       return false;
11034     return Success(Val.getFixedPoint().getBoolValue(), E);
11035   }
11036 
11037   case CK_IntegralCast: {
11038     if (!Visit(SubExpr))
11039       return false;
11040 
11041     if (!Result.isInt()) {
11042       // Allow casts of address-of-label differences if they are no-ops
11043       // or narrowing.  (The narrowing case isn't actually guaranteed to
11044       // be constant-evaluatable except in some narrow cases which are hard
11045       // to detect here.  We let it through on the assumption the user knows
11046       // what they are doing.)
11047       if (Result.isAddrLabelDiff())
11048         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
11049       // Only allow casts of lvalues if they are lossless.
11050       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
11051     }
11052 
11053     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
11054                                       Result.getInt()), E);
11055   }
11056 
11057   case CK_PointerToIntegral: {
11058     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
11059 
11060     LValue LV;
11061     if (!EvaluatePointer(SubExpr, LV, Info))
11062       return false;
11063 
11064     if (LV.getLValueBase()) {
11065       // Only allow based lvalue casts if they are lossless.
11066       // FIXME: Allow a larger integer size than the pointer size, and allow
11067       // narrowing back down to pointer width in subsequent integral casts.
11068       // FIXME: Check integer type's active bits, not its type size.
11069       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
11070         return Error(E);
11071 
11072       LV.Designator.setInvalid();
11073       LV.moveInto(Result);
11074       return true;
11075     }
11076 
11077     APSInt AsInt;
11078     APValue V;
11079     LV.moveInto(V);
11080     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
11081       llvm_unreachable("Can't cast this!");
11082 
11083     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
11084   }
11085 
11086   case CK_IntegralComplexToReal: {
11087     ComplexValue C;
11088     if (!EvaluateComplex(SubExpr, C, Info))
11089       return false;
11090     return Success(C.getComplexIntReal(), E);
11091   }
11092 
11093   case CK_FloatingToIntegral: {
11094     APFloat F(0.0);
11095     if (!EvaluateFloat(SubExpr, F, Info))
11096       return false;
11097 
11098     APSInt Value;
11099     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
11100       return false;
11101     return Success(Value, E);
11102   }
11103   }
11104 
11105   llvm_unreachable("unknown cast resulting in integral value");
11106 }
11107 
11108 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
11109   if (E->getSubExpr()->getType()->isAnyComplexType()) {
11110     ComplexValue LV;
11111     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
11112       return false;
11113     if (!LV.isComplexInt())
11114       return Error(E);
11115     return Success(LV.getComplexIntReal(), E);
11116   }
11117 
11118   return Visit(E->getSubExpr());
11119 }
11120 
11121 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11122   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
11123     ComplexValue LV;
11124     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
11125       return false;
11126     if (!LV.isComplexInt())
11127       return Error(E);
11128     return Success(LV.getComplexIntImag(), E);
11129   }
11130 
11131   VisitIgnoredValue(E->getSubExpr());
11132   return Success(0, E);
11133 }
11134 
11135 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
11136   return Success(E->getPackLength(), E);
11137 }
11138 
11139 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
11140   return Success(E->getValue(), E);
11141 }
11142 
11143 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11144   switch (E->getOpcode()) {
11145     default:
11146       // Invalid unary operators
11147       return Error(E);
11148     case UO_Plus:
11149       // The result is just the value.
11150       return Visit(E->getSubExpr());
11151     case UO_Minus: {
11152       if (!Visit(E->getSubExpr())) return false;
11153       if (!Result.isFixedPoint())
11154         return Error(E);
11155       bool Overflowed;
11156       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
11157       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
11158         return false;
11159       return Success(Negated, E);
11160     }
11161     case UO_LNot: {
11162       bool bres;
11163       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
11164         return false;
11165       return Success(!bres, E);
11166     }
11167   }
11168 }
11169 
11170 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
11171   const Expr *SubExpr = E->getSubExpr();
11172   QualType DestType = E->getType();
11173   assert(DestType->isFixedPointType() &&
11174          "Expected destination type to be a fixed point type");
11175   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
11176 
11177   switch (E->getCastKind()) {
11178   case CK_FixedPointCast: {
11179     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
11180     if (!EvaluateFixedPoint(SubExpr, Src, Info))
11181       return false;
11182     bool Overflowed;
11183     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
11184     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
11185       return false;
11186     return Success(Result, E);
11187   }
11188   case CK_IntegralToFixedPoint: {
11189     APSInt Src;
11190     if (!EvaluateInteger(SubExpr, Src, Info))
11191       return false;
11192 
11193     bool Overflowed;
11194     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11195         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
11196 
11197     if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
11198       return false;
11199 
11200     return Success(IntResult, E);
11201   }
11202   case CK_NoOp:
11203   case CK_LValueToRValue:
11204     return ExprEvaluatorBaseTy::VisitCastExpr(E);
11205   default:
11206     return Error(E);
11207   }
11208 }
11209 
11210 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11211   const Expr *LHS = E->getLHS();
11212   const Expr *RHS = E->getRHS();
11213   FixedPointSemantics ResultFXSema =
11214       Info.Ctx.getFixedPointSemantics(E->getType());
11215 
11216   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
11217   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
11218     return false;
11219   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
11220   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
11221     return false;
11222 
11223   switch (E->getOpcode()) {
11224   case BO_Add: {
11225     bool AddOverflow, ConversionOverflow;
11226     APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
11227                               .convert(ResultFXSema, &ConversionOverflow);
11228     if ((AddOverflow || ConversionOverflow) &&
11229         !HandleOverflow(Info, E, Result, E->getType()))
11230       return false;
11231     return Success(Result, E);
11232   }
11233   default:
11234     return false;
11235   }
11236   llvm_unreachable("Should've exited before this");
11237 }
11238 
11239 //===----------------------------------------------------------------------===//
11240 // Float Evaluation
11241 //===----------------------------------------------------------------------===//
11242 
11243 namespace {
11244 class FloatExprEvaluator
11245   : public ExprEvaluatorBase<FloatExprEvaluator> {
11246   APFloat &Result;
11247 public:
11248   FloatExprEvaluator(EvalInfo &info, APFloat &result)
11249     : ExprEvaluatorBaseTy(info), Result(result) {}
11250 
11251   bool Success(const APValue &V, const Expr *e) {
11252     Result = V.getFloat();
11253     return true;
11254   }
11255 
11256   bool ZeroInitialization(const Expr *E) {
11257     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
11258     return true;
11259   }
11260 
11261   bool VisitCallExpr(const CallExpr *E);
11262 
11263   bool VisitUnaryOperator(const UnaryOperator *E);
11264   bool VisitBinaryOperator(const BinaryOperator *E);
11265   bool VisitFloatingLiteral(const FloatingLiteral *E);
11266   bool VisitCastExpr(const CastExpr *E);
11267 
11268   bool VisitUnaryReal(const UnaryOperator *E);
11269   bool VisitUnaryImag(const UnaryOperator *E);
11270 
11271   // FIXME: Missing: array subscript of vector, member of vector
11272 };
11273 } // end anonymous namespace
11274 
11275 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
11276   assert(E->isRValue() && E->getType()->isRealFloatingType());
11277   return FloatExprEvaluator(Info, Result).Visit(E);
11278 }
11279 
11280 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
11281                                   QualType ResultTy,
11282                                   const Expr *Arg,
11283                                   bool SNaN,
11284                                   llvm::APFloat &Result) {
11285   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
11286   if (!S) return false;
11287 
11288   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
11289 
11290   llvm::APInt fill;
11291 
11292   // Treat empty strings as if they were zero.
11293   if (S->getString().empty())
11294     fill = llvm::APInt(32, 0);
11295   else if (S->getString().getAsInteger(0, fill))
11296     return false;
11297 
11298   if (Context.getTargetInfo().isNan2008()) {
11299     if (SNaN)
11300       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
11301     else
11302       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
11303   } else {
11304     // Prior to IEEE 754-2008, architectures were allowed to choose whether
11305     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
11306     // a different encoding to what became a standard in 2008, and for pre-
11307     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
11308     // sNaN. This is now known as "legacy NaN" encoding.
11309     if (SNaN)
11310       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
11311     else
11312       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
11313   }
11314 
11315   return true;
11316 }
11317 
11318 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
11319   switch (E->getBuiltinCallee()) {
11320   default:
11321     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11322 
11323   case Builtin::BI__builtin_huge_val:
11324   case Builtin::BI__builtin_huge_valf:
11325   case Builtin::BI__builtin_huge_vall:
11326   case Builtin::BI__builtin_huge_valf128:
11327   case Builtin::BI__builtin_inf:
11328   case Builtin::BI__builtin_inff:
11329   case Builtin::BI__builtin_infl:
11330   case Builtin::BI__builtin_inff128: {
11331     const llvm::fltSemantics &Sem =
11332       Info.Ctx.getFloatTypeSemantics(E->getType());
11333     Result = llvm::APFloat::getInf(Sem);
11334     return true;
11335   }
11336 
11337   case Builtin::BI__builtin_nans:
11338   case Builtin::BI__builtin_nansf:
11339   case Builtin::BI__builtin_nansl:
11340   case Builtin::BI__builtin_nansf128:
11341     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
11342                                true, Result))
11343       return Error(E);
11344     return true;
11345 
11346   case Builtin::BI__builtin_nan:
11347   case Builtin::BI__builtin_nanf:
11348   case Builtin::BI__builtin_nanl:
11349   case Builtin::BI__builtin_nanf128:
11350     // If this is __builtin_nan() turn this into a nan, otherwise we
11351     // can't constant fold it.
11352     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
11353                                false, Result))
11354       return Error(E);
11355     return true;
11356 
11357   case Builtin::BI__builtin_fabs:
11358   case Builtin::BI__builtin_fabsf:
11359   case Builtin::BI__builtin_fabsl:
11360   case Builtin::BI__builtin_fabsf128:
11361     if (!EvaluateFloat(E->getArg(0), Result, Info))
11362       return false;
11363 
11364     if (Result.isNegative())
11365       Result.changeSign();
11366     return true;
11367 
11368   // FIXME: Builtin::BI__builtin_powi
11369   // FIXME: Builtin::BI__builtin_powif
11370   // FIXME: Builtin::BI__builtin_powil
11371 
11372   case Builtin::BI__builtin_copysign:
11373   case Builtin::BI__builtin_copysignf:
11374   case Builtin::BI__builtin_copysignl:
11375   case Builtin::BI__builtin_copysignf128: {
11376     APFloat RHS(0.);
11377     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
11378         !EvaluateFloat(E->getArg(1), RHS, Info))
11379       return false;
11380     Result.copySign(RHS);
11381     return true;
11382   }
11383   }
11384 }
11385 
11386 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
11387   if (E->getSubExpr()->getType()->isAnyComplexType()) {
11388     ComplexValue CV;
11389     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
11390       return false;
11391     Result = CV.FloatReal;
11392     return true;
11393   }
11394 
11395   return Visit(E->getSubExpr());
11396 }
11397 
11398 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11399   if (E->getSubExpr()->getType()->isAnyComplexType()) {
11400     ComplexValue CV;
11401     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
11402       return false;
11403     Result = CV.FloatImag;
11404     return true;
11405   }
11406 
11407   VisitIgnoredValue(E->getSubExpr());
11408   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
11409   Result = llvm::APFloat::getZero(Sem);
11410   return true;
11411 }
11412 
11413 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11414   switch (E->getOpcode()) {
11415   default: return Error(E);
11416   case UO_Plus:
11417     return EvaluateFloat(E->getSubExpr(), Result, Info);
11418   case UO_Minus:
11419     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
11420       return false;
11421     Result.changeSign();
11422     return true;
11423   }
11424 }
11425 
11426 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11427   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
11428     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11429 
11430   APFloat RHS(0.0);
11431   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
11432   if (!LHSOK && !Info.noteFailure())
11433     return false;
11434   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
11435          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
11436 }
11437 
11438 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
11439   Result = E->getValue();
11440   return true;
11441 }
11442 
11443 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
11444   const Expr* SubExpr = E->getSubExpr();
11445 
11446   switch (E->getCastKind()) {
11447   default:
11448     return ExprEvaluatorBaseTy::VisitCastExpr(E);
11449 
11450   case CK_IntegralToFloating: {
11451     APSInt IntResult;
11452     return EvaluateInteger(SubExpr, IntResult, Info) &&
11453            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
11454                                 E->getType(), Result);
11455   }
11456 
11457   case CK_FloatingCast: {
11458     if (!Visit(SubExpr))
11459       return false;
11460     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
11461                                   Result);
11462   }
11463 
11464   case CK_FloatingComplexToReal: {
11465     ComplexValue V;
11466     if (!EvaluateComplex(SubExpr, V, Info))
11467       return false;
11468     Result = V.getComplexFloatReal();
11469     return true;
11470   }
11471   }
11472 }
11473 
11474 //===----------------------------------------------------------------------===//
11475 // Complex Evaluation (for float and integer)
11476 //===----------------------------------------------------------------------===//
11477 
11478 namespace {
11479 class ComplexExprEvaluator
11480   : public ExprEvaluatorBase<ComplexExprEvaluator> {
11481   ComplexValue &Result;
11482 
11483 public:
11484   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
11485     : ExprEvaluatorBaseTy(info), Result(Result) {}
11486 
11487   bool Success(const APValue &V, const Expr *e) {
11488     Result.setFrom(V);
11489     return true;
11490   }
11491 
11492   bool ZeroInitialization(const Expr *E);
11493 
11494   //===--------------------------------------------------------------------===//
11495   //                            Visitor Methods
11496   //===--------------------------------------------------------------------===//
11497 
11498   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
11499   bool VisitCastExpr(const CastExpr *E);
11500   bool VisitBinaryOperator(const BinaryOperator *E);
11501   bool VisitUnaryOperator(const UnaryOperator *E);
11502   bool VisitInitListExpr(const InitListExpr *E);
11503 };
11504 } // end anonymous namespace
11505 
11506 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
11507                             EvalInfo &Info) {
11508   assert(E->isRValue() && E->getType()->isAnyComplexType());
11509   return ComplexExprEvaluator(Info, Result).Visit(E);
11510 }
11511 
11512 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
11513   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
11514   if (ElemTy->isRealFloatingType()) {
11515     Result.makeComplexFloat();
11516     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
11517     Result.FloatReal = Zero;
11518     Result.FloatImag = Zero;
11519   } else {
11520     Result.makeComplexInt();
11521     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
11522     Result.IntReal = Zero;
11523     Result.IntImag = Zero;
11524   }
11525   return true;
11526 }
11527 
11528 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
11529   const Expr* SubExpr = E->getSubExpr();
11530 
11531   if (SubExpr->getType()->isRealFloatingType()) {
11532     Result.makeComplexFloat();
11533     APFloat &Imag = Result.FloatImag;
11534     if (!EvaluateFloat(SubExpr, Imag, Info))
11535       return false;
11536 
11537     Result.FloatReal = APFloat(Imag.getSemantics());
11538     return true;
11539   } else {
11540     assert(SubExpr->getType()->isIntegerType() &&
11541            "Unexpected imaginary literal.");
11542 
11543     Result.makeComplexInt();
11544     APSInt &Imag = Result.IntImag;
11545     if (!EvaluateInteger(SubExpr, Imag, Info))
11546       return false;
11547 
11548     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
11549     return true;
11550   }
11551 }
11552 
11553 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
11554 
11555   switch (E->getCastKind()) {
11556   case CK_BitCast:
11557   case CK_BaseToDerived:
11558   case CK_DerivedToBase:
11559   case CK_UncheckedDerivedToBase:
11560   case CK_Dynamic:
11561   case CK_ToUnion:
11562   case CK_ArrayToPointerDecay:
11563   case CK_FunctionToPointerDecay:
11564   case CK_NullToPointer:
11565   case CK_NullToMemberPointer:
11566   case CK_BaseToDerivedMemberPointer:
11567   case CK_DerivedToBaseMemberPointer:
11568   case CK_MemberPointerToBoolean:
11569   case CK_ReinterpretMemberPointer:
11570   case CK_ConstructorConversion:
11571   case CK_IntegralToPointer:
11572   case CK_PointerToIntegral:
11573   case CK_PointerToBoolean:
11574   case CK_ToVoid:
11575   case CK_VectorSplat:
11576   case CK_IntegralCast:
11577   case CK_BooleanToSignedIntegral:
11578   case CK_IntegralToBoolean:
11579   case CK_IntegralToFloating:
11580   case CK_FloatingToIntegral:
11581   case CK_FloatingToBoolean:
11582   case CK_FloatingCast:
11583   case CK_CPointerToObjCPointerCast:
11584   case CK_BlockPointerToObjCPointerCast:
11585   case CK_AnyPointerToBlockPointerCast:
11586   case CK_ObjCObjectLValueCast:
11587   case CK_FloatingComplexToReal:
11588   case CK_FloatingComplexToBoolean:
11589   case CK_IntegralComplexToReal:
11590   case CK_IntegralComplexToBoolean:
11591   case CK_ARCProduceObject:
11592   case CK_ARCConsumeObject:
11593   case CK_ARCReclaimReturnedObject:
11594   case CK_ARCExtendBlockObject:
11595   case CK_CopyAndAutoreleaseBlockObject:
11596   case CK_BuiltinFnToFnPtr:
11597   case CK_ZeroToOCLOpaqueType:
11598   case CK_NonAtomicToAtomic:
11599   case CK_AddressSpaceConversion:
11600   case CK_IntToOCLSampler:
11601   case CK_FixedPointCast:
11602   case CK_FixedPointToBoolean:
11603   case CK_FixedPointToIntegral:
11604   case CK_IntegralToFixedPoint:
11605     llvm_unreachable("invalid cast kind for complex value");
11606 
11607   case CK_LValueToRValue:
11608   case CK_AtomicToNonAtomic:
11609   case CK_NoOp:
11610   case CK_LValueToRValueBitCast:
11611     return ExprEvaluatorBaseTy::VisitCastExpr(E);
11612 
11613   case CK_Dependent:
11614   case CK_LValueBitCast:
11615   case CK_UserDefinedConversion:
11616     return Error(E);
11617 
11618   case CK_FloatingRealToComplex: {
11619     APFloat &Real = Result.FloatReal;
11620     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
11621       return false;
11622 
11623     Result.makeComplexFloat();
11624     Result.FloatImag = APFloat(Real.getSemantics());
11625     return true;
11626   }
11627 
11628   case CK_FloatingComplexCast: {
11629     if (!Visit(E->getSubExpr()))
11630       return false;
11631 
11632     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11633     QualType From
11634       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11635 
11636     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
11637            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
11638   }
11639 
11640   case CK_FloatingComplexToIntegralComplex: {
11641     if (!Visit(E->getSubExpr()))
11642       return false;
11643 
11644     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11645     QualType From
11646       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11647     Result.makeComplexInt();
11648     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
11649                                 To, Result.IntReal) &&
11650            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
11651                                 To, Result.IntImag);
11652   }
11653 
11654   case CK_IntegralRealToComplex: {
11655     APSInt &Real = Result.IntReal;
11656     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
11657       return false;
11658 
11659     Result.makeComplexInt();
11660     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
11661     return true;
11662   }
11663 
11664   case CK_IntegralComplexCast: {
11665     if (!Visit(E->getSubExpr()))
11666       return false;
11667 
11668     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11669     QualType From
11670       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11671 
11672     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
11673     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
11674     return true;
11675   }
11676 
11677   case CK_IntegralComplexToFloatingComplex: {
11678     if (!Visit(E->getSubExpr()))
11679       return false;
11680 
11681     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
11682     QualType From
11683       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
11684     Result.makeComplexFloat();
11685     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
11686                                 To, Result.FloatReal) &&
11687            HandleIntToFloatCast(Info, E, From, Result.IntImag,
11688                                 To, Result.FloatImag);
11689   }
11690   }
11691 
11692   llvm_unreachable("unknown cast resulting in complex value");
11693 }
11694 
11695 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11696   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
11697     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11698 
11699   // Track whether the LHS or RHS is real at the type system level. When this is
11700   // the case we can simplify our evaluation strategy.
11701   bool LHSReal = false, RHSReal = false;
11702 
11703   bool LHSOK;
11704   if (E->getLHS()->getType()->isRealFloatingType()) {
11705     LHSReal = true;
11706     APFloat &Real = Result.FloatReal;
11707     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
11708     if (LHSOK) {
11709       Result.makeComplexFloat();
11710       Result.FloatImag = APFloat(Real.getSemantics());
11711     }
11712   } else {
11713     LHSOK = Visit(E->getLHS());
11714   }
11715   if (!LHSOK && !Info.noteFailure())
11716     return false;
11717 
11718   ComplexValue RHS;
11719   if (E->getRHS()->getType()->isRealFloatingType()) {
11720     RHSReal = true;
11721     APFloat &Real = RHS.FloatReal;
11722     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
11723       return false;
11724     RHS.makeComplexFloat();
11725     RHS.FloatImag = APFloat(Real.getSemantics());
11726   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
11727     return false;
11728 
11729   assert(!(LHSReal && RHSReal) &&
11730          "Cannot have both operands of a complex operation be real.");
11731   switch (E->getOpcode()) {
11732   default: return Error(E);
11733   case BO_Add:
11734     if (Result.isComplexFloat()) {
11735       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
11736                                        APFloat::rmNearestTiesToEven);
11737       if (LHSReal)
11738         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11739       else if (!RHSReal)
11740         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
11741                                          APFloat::rmNearestTiesToEven);
11742     } else {
11743       Result.getComplexIntReal() += RHS.getComplexIntReal();
11744       Result.getComplexIntImag() += RHS.getComplexIntImag();
11745     }
11746     break;
11747   case BO_Sub:
11748     if (Result.isComplexFloat()) {
11749       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
11750                                             APFloat::rmNearestTiesToEven);
11751       if (LHSReal) {
11752         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11753         Result.getComplexFloatImag().changeSign();
11754       } else if (!RHSReal) {
11755         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
11756                                               APFloat::rmNearestTiesToEven);
11757       }
11758     } else {
11759       Result.getComplexIntReal() -= RHS.getComplexIntReal();
11760       Result.getComplexIntImag() -= RHS.getComplexIntImag();
11761     }
11762     break;
11763   case BO_Mul:
11764     if (Result.isComplexFloat()) {
11765       // This is an implementation of complex multiplication according to the
11766       // constraints laid out in C11 Annex G. The implementation uses the
11767       // following naming scheme:
11768       //   (a + ib) * (c + id)
11769       ComplexValue LHS = Result;
11770       APFloat &A = LHS.getComplexFloatReal();
11771       APFloat &B = LHS.getComplexFloatImag();
11772       APFloat &C = RHS.getComplexFloatReal();
11773       APFloat &D = RHS.getComplexFloatImag();
11774       APFloat &ResR = Result.getComplexFloatReal();
11775       APFloat &ResI = Result.getComplexFloatImag();
11776       if (LHSReal) {
11777         assert(!RHSReal && "Cannot have two real operands for a complex op!");
11778         ResR = A * C;
11779         ResI = A * D;
11780       } else if (RHSReal) {
11781         ResR = C * A;
11782         ResI = C * B;
11783       } else {
11784         // In the fully general case, we need to handle NaNs and infinities
11785         // robustly.
11786         APFloat AC = A * C;
11787         APFloat BD = B * D;
11788         APFloat AD = A * D;
11789         APFloat BC = B * C;
11790         ResR = AC - BD;
11791         ResI = AD + BC;
11792         if (ResR.isNaN() && ResI.isNaN()) {
11793           bool Recalc = false;
11794           if (A.isInfinity() || B.isInfinity()) {
11795             A = APFloat::copySign(
11796                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11797             B = APFloat::copySign(
11798                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11799             if (C.isNaN())
11800               C = APFloat::copySign(APFloat(C.getSemantics()), C);
11801             if (D.isNaN())
11802               D = APFloat::copySign(APFloat(D.getSemantics()), D);
11803             Recalc = true;
11804           }
11805           if (C.isInfinity() || D.isInfinity()) {
11806             C = APFloat::copySign(
11807                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11808             D = APFloat::copySign(
11809                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11810             if (A.isNaN())
11811               A = APFloat::copySign(APFloat(A.getSemantics()), A);
11812             if (B.isNaN())
11813               B = APFloat::copySign(APFloat(B.getSemantics()), B);
11814             Recalc = true;
11815           }
11816           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
11817                           AD.isInfinity() || BC.isInfinity())) {
11818             if (A.isNaN())
11819               A = APFloat::copySign(APFloat(A.getSemantics()), A);
11820             if (B.isNaN())
11821               B = APFloat::copySign(APFloat(B.getSemantics()), B);
11822             if (C.isNaN())
11823               C = APFloat::copySign(APFloat(C.getSemantics()), C);
11824             if (D.isNaN())
11825               D = APFloat::copySign(APFloat(D.getSemantics()), D);
11826             Recalc = true;
11827           }
11828           if (Recalc) {
11829             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
11830             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
11831           }
11832         }
11833       }
11834     } else {
11835       ComplexValue LHS = Result;
11836       Result.getComplexIntReal() =
11837         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
11838          LHS.getComplexIntImag() * RHS.getComplexIntImag());
11839       Result.getComplexIntImag() =
11840         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
11841          LHS.getComplexIntImag() * RHS.getComplexIntReal());
11842     }
11843     break;
11844   case BO_Div:
11845     if (Result.isComplexFloat()) {
11846       // This is an implementation of complex division according to the
11847       // constraints laid out in C11 Annex G. The implementation uses the
11848       // following naming scheme:
11849       //   (a + ib) / (c + id)
11850       ComplexValue LHS = Result;
11851       APFloat &A = LHS.getComplexFloatReal();
11852       APFloat &B = LHS.getComplexFloatImag();
11853       APFloat &C = RHS.getComplexFloatReal();
11854       APFloat &D = RHS.getComplexFloatImag();
11855       APFloat &ResR = Result.getComplexFloatReal();
11856       APFloat &ResI = Result.getComplexFloatImag();
11857       if (RHSReal) {
11858         ResR = A / C;
11859         ResI = B / C;
11860       } else {
11861         if (LHSReal) {
11862           // No real optimizations we can do here, stub out with zero.
11863           B = APFloat::getZero(A.getSemantics());
11864         }
11865         int DenomLogB = 0;
11866         APFloat MaxCD = maxnum(abs(C), abs(D));
11867         if (MaxCD.isFinite()) {
11868           DenomLogB = ilogb(MaxCD);
11869           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
11870           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
11871         }
11872         APFloat Denom = C * C + D * D;
11873         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
11874                       APFloat::rmNearestTiesToEven);
11875         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
11876                       APFloat::rmNearestTiesToEven);
11877         if (ResR.isNaN() && ResI.isNaN()) {
11878           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
11879             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
11880             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
11881           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
11882                      D.isFinite()) {
11883             A = APFloat::copySign(
11884                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11885             B = APFloat::copySign(
11886                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11887             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
11888             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
11889           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
11890             C = APFloat::copySign(
11891                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11892             D = APFloat::copySign(
11893                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11894             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
11895             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
11896           }
11897         }
11898       }
11899     } else {
11900       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
11901         return Error(E, diag::note_expr_divide_by_zero);
11902 
11903       ComplexValue LHS = Result;
11904       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
11905         RHS.getComplexIntImag() * RHS.getComplexIntImag();
11906       Result.getComplexIntReal() =
11907         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
11908          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
11909       Result.getComplexIntImag() =
11910         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
11911          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
11912     }
11913     break;
11914   }
11915 
11916   return true;
11917 }
11918 
11919 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11920   // Get the operand value into 'Result'.
11921   if (!Visit(E->getSubExpr()))
11922     return false;
11923 
11924   switch (E->getOpcode()) {
11925   default:
11926     return Error(E);
11927   case UO_Extension:
11928     return true;
11929   case UO_Plus:
11930     // The result is always just the subexpr.
11931     return true;
11932   case UO_Minus:
11933     if (Result.isComplexFloat()) {
11934       Result.getComplexFloatReal().changeSign();
11935       Result.getComplexFloatImag().changeSign();
11936     }
11937     else {
11938       Result.getComplexIntReal() = -Result.getComplexIntReal();
11939       Result.getComplexIntImag() = -Result.getComplexIntImag();
11940     }
11941     return true;
11942   case UO_Not:
11943     if (Result.isComplexFloat())
11944       Result.getComplexFloatImag().changeSign();
11945     else
11946       Result.getComplexIntImag() = -Result.getComplexIntImag();
11947     return true;
11948   }
11949 }
11950 
11951 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
11952   if (E->getNumInits() == 2) {
11953     if (E->getType()->isComplexType()) {
11954       Result.makeComplexFloat();
11955       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
11956         return false;
11957       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
11958         return false;
11959     } else {
11960       Result.makeComplexInt();
11961       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
11962         return false;
11963       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
11964         return false;
11965     }
11966     return true;
11967   }
11968   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
11969 }
11970 
11971 //===----------------------------------------------------------------------===//
11972 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
11973 // implicit conversion.
11974 //===----------------------------------------------------------------------===//
11975 
11976 namespace {
11977 class AtomicExprEvaluator :
11978     public ExprEvaluatorBase<AtomicExprEvaluator> {
11979   const LValue *This;
11980   APValue &Result;
11981 public:
11982   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
11983       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
11984 
11985   bool Success(const APValue &V, const Expr *E) {
11986     Result = V;
11987     return true;
11988   }
11989 
11990   bool ZeroInitialization(const Expr *E) {
11991     ImplicitValueInitExpr VIE(
11992         E->getType()->castAs<AtomicType>()->getValueType());
11993     // For atomic-qualified class (and array) types in C++, initialize the
11994     // _Atomic-wrapped subobject directly, in-place.
11995     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
11996                 : Evaluate(Result, Info, &VIE);
11997   }
11998 
11999   bool VisitCastExpr(const CastExpr *E) {
12000     switch (E->getCastKind()) {
12001     default:
12002       return ExprEvaluatorBaseTy::VisitCastExpr(E);
12003     case CK_NonAtomicToAtomic:
12004       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
12005                   : Evaluate(Result, Info, E->getSubExpr());
12006     }
12007   }
12008 };
12009 } // end anonymous namespace
12010 
12011 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
12012                            EvalInfo &Info) {
12013   assert(E->isRValue() && E->getType()->isAtomicType());
12014   return AtomicExprEvaluator(Info, This, Result).Visit(E);
12015 }
12016 
12017 //===----------------------------------------------------------------------===//
12018 // Void expression evaluation, primarily for a cast to void on the LHS of a
12019 // comma operator
12020 //===----------------------------------------------------------------------===//
12021 
12022 namespace {
12023 class VoidExprEvaluator
12024   : public ExprEvaluatorBase<VoidExprEvaluator> {
12025 public:
12026   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
12027 
12028   bool Success(const APValue &V, const Expr *e) { return true; }
12029 
12030   bool ZeroInitialization(const Expr *E) { return true; }
12031 
12032   bool VisitCastExpr(const CastExpr *E) {
12033     switch (E->getCastKind()) {
12034     default:
12035       return ExprEvaluatorBaseTy::VisitCastExpr(E);
12036     case CK_ToVoid:
12037       VisitIgnoredValue(E->getSubExpr());
12038       return true;
12039     }
12040   }
12041 
12042   bool VisitCallExpr(const CallExpr *E) {
12043     switch (E->getBuiltinCallee()) {
12044     default:
12045       return ExprEvaluatorBaseTy::VisitCallExpr(E);
12046     case Builtin::BI__assume:
12047     case Builtin::BI__builtin_assume:
12048       // The argument is not evaluated!
12049       return true;
12050     }
12051   }
12052 };
12053 } // end anonymous namespace
12054 
12055 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
12056   assert(E->isRValue() && E->getType()->isVoidType());
12057   return VoidExprEvaluator(Info).Visit(E);
12058 }
12059 
12060 //===----------------------------------------------------------------------===//
12061 // Top level Expr::EvaluateAsRValue method.
12062 //===----------------------------------------------------------------------===//
12063 
12064 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
12065   // In C, function designators are not lvalues, but we evaluate them as if they
12066   // are.
12067   QualType T = E->getType();
12068   if (E->isGLValue() || T->isFunctionType()) {
12069     LValue LV;
12070     if (!EvaluateLValue(E, LV, Info))
12071       return false;
12072     LV.moveInto(Result);
12073   } else if (T->isVectorType()) {
12074     if (!EvaluateVector(E, Result, Info))
12075       return false;
12076   } else if (T->isIntegralOrEnumerationType()) {
12077     if (!IntExprEvaluator(Info, Result).Visit(E))
12078       return false;
12079   } else if (T->hasPointerRepresentation()) {
12080     LValue LV;
12081     if (!EvaluatePointer(E, LV, Info))
12082       return false;
12083     LV.moveInto(Result);
12084   } else if (T->isRealFloatingType()) {
12085     llvm::APFloat F(0.0);
12086     if (!EvaluateFloat(E, F, Info))
12087       return false;
12088     Result = APValue(F);
12089   } else if (T->isAnyComplexType()) {
12090     ComplexValue C;
12091     if (!EvaluateComplex(E, C, Info))
12092       return false;
12093     C.moveInto(Result);
12094   } else if (T->isFixedPointType()) {
12095     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
12096   } else if (T->isMemberPointerType()) {
12097     MemberPtr P;
12098     if (!EvaluateMemberPointer(E, P, Info))
12099       return false;
12100     P.moveInto(Result);
12101     return true;
12102   } else if (T->isArrayType()) {
12103     LValue LV;
12104     APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
12105     if (!EvaluateArray(E, LV, Value, Info))
12106       return false;
12107     Result = Value;
12108   } else if (T->isRecordType()) {
12109     LValue LV;
12110     APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
12111     if (!EvaluateRecord(E, LV, Value, Info))
12112       return false;
12113     Result = Value;
12114   } else if (T->isVoidType()) {
12115     if (!Info.getLangOpts().CPlusPlus11)
12116       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
12117         << E->getType();
12118     if (!EvaluateVoid(E, Info))
12119       return false;
12120   } else if (T->isAtomicType()) {
12121     QualType Unqual = T.getAtomicUnqualifiedType();
12122     if (Unqual->isArrayType() || Unqual->isRecordType()) {
12123       LValue LV;
12124       APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
12125       if (!EvaluateAtomic(E, &LV, Value, Info))
12126         return false;
12127     } else {
12128       if (!EvaluateAtomic(E, nullptr, Result, Info))
12129         return false;
12130     }
12131   } else if (Info.getLangOpts().CPlusPlus11) {
12132     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
12133     return false;
12134   } else {
12135     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12136     return false;
12137   }
12138 
12139   return true;
12140 }
12141 
12142 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
12143 /// cases, the in-place evaluation is essential, since later initializers for
12144 /// an object can indirectly refer to subobjects which were initialized earlier.
12145 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
12146                             const Expr *E, bool AllowNonLiteralTypes) {
12147   assert(!E->isValueDependent());
12148 
12149   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
12150     return false;
12151 
12152   if (E->isRValue()) {
12153     // Evaluate arrays and record types in-place, so that later initializers can
12154     // refer to earlier-initialized members of the object.
12155     QualType T = E->getType();
12156     if (T->isArrayType())
12157       return EvaluateArray(E, This, Result, Info);
12158     else if (T->isRecordType())
12159       return EvaluateRecord(E, This, Result, Info);
12160     else if (T->isAtomicType()) {
12161       QualType Unqual = T.getAtomicUnqualifiedType();
12162       if (Unqual->isArrayType() || Unqual->isRecordType())
12163         return EvaluateAtomic(E, &This, Result, Info);
12164     }
12165   }
12166 
12167   // For any other type, in-place evaluation is unimportant.
12168   return Evaluate(Result, Info, E);
12169 }
12170 
12171 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
12172 /// lvalue-to-rvalue cast if it is an lvalue.
12173 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
12174    if (Info.EnableNewConstInterp) {
12175     auto &InterpCtx = Info.Ctx.getInterpContext();
12176     switch (InterpCtx.evaluateAsRValue(Info, E, Result)) {
12177     case interp::InterpResult::Success:
12178       return true;
12179     case interp::InterpResult::Fail:
12180       return false;
12181     case interp::InterpResult::Bail:
12182       break;
12183     }
12184   }
12185 
12186   if (E->getType().isNull())
12187     return false;
12188 
12189   if (!CheckLiteralType(Info, E))
12190     return false;
12191 
12192   if (!::Evaluate(Result, Info, E))
12193     return false;
12194 
12195   if (E->isGLValue()) {
12196     LValue LV;
12197     LV.setFrom(Info.Ctx, Result);
12198     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12199       return false;
12200   }
12201 
12202   // Check this core constant expression is a constant expression.
12203   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
12204 }
12205 
12206 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
12207                                  const ASTContext &Ctx, bool &IsConst) {
12208   // Fast-path evaluations of integer literals, since we sometimes see files
12209   // containing vast quantities of these.
12210   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
12211     Result.Val = APValue(APSInt(L->getValue(),
12212                                 L->getType()->isUnsignedIntegerType()));
12213     IsConst = true;
12214     return true;
12215   }
12216 
12217   // This case should be rare, but we need to check it before we check on
12218   // the type below.
12219   if (Exp->getType().isNull()) {
12220     IsConst = false;
12221     return true;
12222   }
12223 
12224   // FIXME: Evaluating values of large array and record types can cause
12225   // performance problems. Only do so in C++11 for now.
12226   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
12227                           Exp->getType()->isRecordType()) &&
12228       !Ctx.getLangOpts().CPlusPlus11) {
12229     IsConst = false;
12230     return true;
12231   }
12232   return false;
12233 }
12234 
12235 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
12236                                       Expr::SideEffectsKind SEK) {
12237   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
12238          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
12239 }
12240 
12241 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
12242                              const ASTContext &Ctx, EvalInfo &Info) {
12243   bool IsConst;
12244   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
12245     return IsConst;
12246 
12247   return EvaluateAsRValue(Info, E, Result.Val);
12248 }
12249 
12250 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
12251                           const ASTContext &Ctx,
12252                           Expr::SideEffectsKind AllowSideEffects,
12253                           EvalInfo &Info) {
12254   if (!E->getType()->isIntegralOrEnumerationType())
12255     return false;
12256 
12257   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
12258       !ExprResult.Val.isInt() ||
12259       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12260     return false;
12261 
12262   return true;
12263 }
12264 
12265 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
12266                                  const ASTContext &Ctx,
12267                                  Expr::SideEffectsKind AllowSideEffects,
12268                                  EvalInfo &Info) {
12269   if (!E->getType()->isFixedPointType())
12270     return false;
12271 
12272   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
12273     return false;
12274 
12275   if (!ExprResult.Val.isFixedPoint() ||
12276       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12277     return false;
12278 
12279   return true;
12280 }
12281 
12282 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
12283 /// any crazy technique (that has nothing to do with language standards) that
12284 /// we want to.  If this function returns true, it returns the folded constant
12285 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
12286 /// will be applied to the result.
12287 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
12288                             bool InConstantContext) const {
12289   assert(!isValueDependent() &&
12290          "Expression evaluator can't be called on a dependent expression.");
12291   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
12292   Info.InConstantContext = InConstantContext;
12293   return ::EvaluateAsRValue(this, Result, Ctx, Info);
12294 }
12295 
12296 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
12297                                       bool InConstantContext) const {
12298   assert(!isValueDependent() &&
12299          "Expression evaluator can't be called on a dependent expression.");
12300   EvalResult Scratch;
12301   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
12302          HandleConversionToBool(Scratch.Val, Result);
12303 }
12304 
12305 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
12306                          SideEffectsKind AllowSideEffects,
12307                          bool InConstantContext) const {
12308   assert(!isValueDependent() &&
12309          "Expression evaluator can't be called on a dependent expression.");
12310   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
12311   Info.InConstantContext = InConstantContext;
12312   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
12313 }
12314 
12315 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
12316                                 SideEffectsKind AllowSideEffects,
12317                                 bool InConstantContext) const {
12318   assert(!isValueDependent() &&
12319          "Expression evaluator can't be called on a dependent expression.");
12320   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
12321   Info.InConstantContext = InConstantContext;
12322   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
12323 }
12324 
12325 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
12326                            SideEffectsKind AllowSideEffects,
12327                            bool InConstantContext) const {
12328   assert(!isValueDependent() &&
12329          "Expression evaluator can't be called on a dependent expression.");
12330 
12331   if (!getType()->isRealFloatingType())
12332     return false;
12333 
12334   EvalResult ExprResult;
12335   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
12336       !ExprResult.Val.isFloat() ||
12337       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12338     return false;
12339 
12340   Result = ExprResult.Val.getFloat();
12341   return true;
12342 }
12343 
12344 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
12345                             bool InConstantContext) const {
12346   assert(!isValueDependent() &&
12347          "Expression evaluator can't be called on a dependent expression.");
12348 
12349   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
12350   Info.InConstantContext = InConstantContext;
12351   LValue LV;
12352   if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
12353       !CheckLValueConstantExpression(Info, getExprLoc(),
12354                                      Ctx.getLValueReferenceType(getType()), LV,
12355                                      Expr::EvaluateForCodeGen))
12356     return false;
12357 
12358   LV.moveInto(Result.Val);
12359   return true;
12360 }
12361 
12362 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
12363                                   const ASTContext &Ctx) const {
12364   assert(!isValueDependent() &&
12365          "Expression evaluator can't be called on a dependent expression.");
12366 
12367   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
12368   EvalInfo Info(Ctx, Result, EM);
12369   Info.InConstantContext = true;
12370 
12371   if (!::Evaluate(Result.Val, Info, this))
12372     return false;
12373 
12374   return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
12375                                  Usage);
12376 }
12377 
12378 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
12379                                  const VarDecl *VD,
12380                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
12381   assert(!isValueDependent() &&
12382          "Expression evaluator can't be called on a dependent expression.");
12383 
12384   // FIXME: Evaluating initializers for large array and record types can cause
12385   // performance problems. Only do so in C++11 for now.
12386   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
12387       !Ctx.getLangOpts().CPlusPlus11)
12388     return false;
12389 
12390   Expr::EvalStatus EStatus;
12391   EStatus.Diag = &Notes;
12392 
12393   EvalInfo Info(Ctx, EStatus, VD->isConstexpr()
12394                                       ? EvalInfo::EM_ConstantExpression
12395                                       : EvalInfo::EM_ConstantFold);
12396   Info.setEvaluatingDecl(VD, Value);
12397   Info.InConstantContext = true;
12398 
12399   SourceLocation DeclLoc = VD->getLocation();
12400   QualType DeclTy = VD->getType();
12401 
12402   if (Info.EnableNewConstInterp) {
12403     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
12404     switch (InterpCtx.evaluateAsInitializer(Info, VD, Value)) {
12405     case interp::InterpResult::Fail:
12406       // Bail out if an error was encountered.
12407       return false;
12408     case interp::InterpResult::Success:
12409       // Evaluation succeeded and value was set.
12410       return CheckConstantExpression(Info, DeclLoc, DeclTy, Value);
12411     case interp::InterpResult::Bail:
12412       // Evaluate the value again for the tree evaluator to use.
12413       break;
12414     }
12415   }
12416 
12417   LValue LVal;
12418   LVal.set(VD);
12419 
12420   // C++11 [basic.start.init]p2:
12421   //  Variables with static storage duration or thread storage duration shall be
12422   //  zero-initialized before any other initialization takes place.
12423   // This behavior is not present in C.
12424   if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
12425       !DeclTy->isReferenceType()) {
12426     ImplicitValueInitExpr VIE(DeclTy);
12427     if (!EvaluateInPlace(Value, Info, LVal, &VIE,
12428                          /*AllowNonLiteralTypes=*/true))
12429       return false;
12430   }
12431 
12432   if (!EvaluateInPlace(Value, Info, LVal, this,
12433                        /*AllowNonLiteralTypes=*/true) ||
12434       EStatus.HasSideEffects)
12435     return false;
12436 
12437   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value);
12438 }
12439 
12440 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
12441 /// constant folded, but discard the result.
12442 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
12443   assert(!isValueDependent() &&
12444          "Expression evaluator can't be called on a dependent expression.");
12445 
12446   EvalResult Result;
12447   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
12448          !hasUnacceptableSideEffect(Result, SEK);
12449 }
12450 
12451 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
12452                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
12453   assert(!isValueDependent() &&
12454          "Expression evaluator can't be called on a dependent expression.");
12455 
12456   EvalResult EVResult;
12457   EVResult.Diag = Diag;
12458   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
12459   Info.InConstantContext = true;
12460 
12461   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
12462   (void)Result;
12463   assert(Result && "Could not evaluate expression");
12464   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
12465 
12466   return EVResult.Val.getInt();
12467 }
12468 
12469 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
12470     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
12471   assert(!isValueDependent() &&
12472          "Expression evaluator can't be called on a dependent expression.");
12473 
12474   EvalResult EVResult;
12475   EVResult.Diag = Diag;
12476   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
12477   Info.InConstantContext = true;
12478   Info.CheckingForUndefinedBehavior = true;
12479 
12480   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
12481   (void)Result;
12482   assert(Result && "Could not evaluate expression");
12483   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
12484 
12485   return EVResult.Val.getInt();
12486 }
12487 
12488 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
12489   assert(!isValueDependent() &&
12490          "Expression evaluator can't be called on a dependent expression.");
12491 
12492   bool IsConst;
12493   EvalResult EVResult;
12494   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
12495     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
12496     Info.CheckingForUndefinedBehavior = true;
12497     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
12498   }
12499 }
12500 
12501 bool Expr::EvalResult::isGlobalLValue() const {
12502   assert(Val.isLValue());
12503   return IsGlobalLValue(Val.getLValueBase());
12504 }
12505 
12506 
12507 /// isIntegerConstantExpr - this recursive routine will test if an expression is
12508 /// an integer constant expression.
12509 
12510 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
12511 /// comma, etc
12512 
12513 // CheckICE - This function does the fundamental ICE checking: the returned
12514 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
12515 // and a (possibly null) SourceLocation indicating the location of the problem.
12516 //
12517 // Note that to reduce code duplication, this helper does no evaluation
12518 // itself; the caller checks whether the expression is evaluatable, and
12519 // in the rare cases where CheckICE actually cares about the evaluated
12520 // value, it calls into Evaluate.
12521 
12522 namespace {
12523 
12524 enum ICEKind {
12525   /// This expression is an ICE.
12526   IK_ICE,
12527   /// This expression is not an ICE, but if it isn't evaluated, it's
12528   /// a legal subexpression for an ICE. This return value is used to handle
12529   /// the comma operator in C99 mode, and non-constant subexpressions.
12530   IK_ICEIfUnevaluated,
12531   /// This expression is not an ICE, and is not a legal subexpression for one.
12532   IK_NotICE
12533 };
12534 
12535 struct ICEDiag {
12536   ICEKind Kind;
12537   SourceLocation Loc;
12538 
12539   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
12540 };
12541 
12542 }
12543 
12544 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
12545 
12546 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
12547 
12548 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
12549   Expr::EvalResult EVResult;
12550   Expr::EvalStatus Status;
12551   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
12552 
12553   Info.InConstantContext = true;
12554   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
12555       !EVResult.Val.isInt())
12556     return ICEDiag(IK_NotICE, E->getBeginLoc());
12557 
12558   return NoDiag();
12559 }
12560 
12561 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
12562   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
12563   if (!E->getType()->isIntegralOrEnumerationType())
12564     return ICEDiag(IK_NotICE, E->getBeginLoc());
12565 
12566   switch (E->getStmtClass()) {
12567 #define ABSTRACT_STMT(Node)
12568 #define STMT(Node, Base) case Expr::Node##Class:
12569 #define EXPR(Node, Base)
12570 #include "clang/AST/StmtNodes.inc"
12571   case Expr::PredefinedExprClass:
12572   case Expr::FloatingLiteralClass:
12573   case Expr::ImaginaryLiteralClass:
12574   case Expr::StringLiteralClass:
12575   case Expr::ArraySubscriptExprClass:
12576   case Expr::OMPArraySectionExprClass:
12577   case Expr::MemberExprClass:
12578   case Expr::CompoundAssignOperatorClass:
12579   case Expr::CompoundLiteralExprClass:
12580   case Expr::ExtVectorElementExprClass:
12581   case Expr::DesignatedInitExprClass:
12582   case Expr::ArrayInitLoopExprClass:
12583   case Expr::ArrayInitIndexExprClass:
12584   case Expr::NoInitExprClass:
12585   case Expr::DesignatedInitUpdateExprClass:
12586   case Expr::ImplicitValueInitExprClass:
12587   case Expr::ParenListExprClass:
12588   case Expr::VAArgExprClass:
12589   case Expr::AddrLabelExprClass:
12590   case Expr::StmtExprClass:
12591   case Expr::CXXMemberCallExprClass:
12592   case Expr::CUDAKernelCallExprClass:
12593   case Expr::CXXDynamicCastExprClass:
12594   case Expr::CXXTypeidExprClass:
12595   case Expr::CXXUuidofExprClass:
12596   case Expr::MSPropertyRefExprClass:
12597   case Expr::MSPropertySubscriptExprClass:
12598   case Expr::CXXNullPtrLiteralExprClass:
12599   case Expr::UserDefinedLiteralClass:
12600   case Expr::CXXThisExprClass:
12601   case Expr::CXXThrowExprClass:
12602   case Expr::CXXNewExprClass:
12603   case Expr::CXXDeleteExprClass:
12604   case Expr::CXXPseudoDestructorExprClass:
12605   case Expr::UnresolvedLookupExprClass:
12606   case Expr::TypoExprClass:
12607   case Expr::DependentScopeDeclRefExprClass:
12608   case Expr::CXXConstructExprClass:
12609   case Expr::CXXInheritedCtorInitExprClass:
12610   case Expr::CXXStdInitializerListExprClass:
12611   case Expr::CXXBindTemporaryExprClass:
12612   case Expr::ExprWithCleanupsClass:
12613   case Expr::CXXTemporaryObjectExprClass:
12614   case Expr::CXXUnresolvedConstructExprClass:
12615   case Expr::CXXDependentScopeMemberExprClass:
12616   case Expr::UnresolvedMemberExprClass:
12617   case Expr::ObjCStringLiteralClass:
12618   case Expr::ObjCBoxedExprClass:
12619   case Expr::ObjCArrayLiteralClass:
12620   case Expr::ObjCDictionaryLiteralClass:
12621   case Expr::ObjCEncodeExprClass:
12622   case Expr::ObjCMessageExprClass:
12623   case Expr::ObjCSelectorExprClass:
12624   case Expr::ObjCProtocolExprClass:
12625   case Expr::ObjCIvarRefExprClass:
12626   case Expr::ObjCPropertyRefExprClass:
12627   case Expr::ObjCSubscriptRefExprClass:
12628   case Expr::ObjCIsaExprClass:
12629   case Expr::ObjCAvailabilityCheckExprClass:
12630   case Expr::ShuffleVectorExprClass:
12631   case Expr::ConvertVectorExprClass:
12632   case Expr::BlockExprClass:
12633   case Expr::NoStmtClass:
12634   case Expr::OpaqueValueExprClass:
12635   case Expr::PackExpansionExprClass:
12636   case Expr::SubstNonTypeTemplateParmPackExprClass:
12637   case Expr::FunctionParmPackExprClass:
12638   case Expr::AsTypeExprClass:
12639   case Expr::ObjCIndirectCopyRestoreExprClass:
12640   case Expr::MaterializeTemporaryExprClass:
12641   case Expr::PseudoObjectExprClass:
12642   case Expr::AtomicExprClass:
12643   case Expr::LambdaExprClass:
12644   case Expr::CXXFoldExprClass:
12645   case Expr::CoawaitExprClass:
12646   case Expr::DependentCoawaitExprClass:
12647   case Expr::CoyieldExprClass:
12648     return ICEDiag(IK_NotICE, E->getBeginLoc());
12649 
12650   case Expr::InitListExprClass: {
12651     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
12652     // form "T x = { a };" is equivalent to "T x = a;".
12653     // Unless we're initializing a reference, T is a scalar as it is known to be
12654     // of integral or enumeration type.
12655     if (E->isRValue())
12656       if (cast<InitListExpr>(E)->getNumInits() == 1)
12657         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
12658     return ICEDiag(IK_NotICE, E->getBeginLoc());
12659   }
12660 
12661   case Expr::SizeOfPackExprClass:
12662   case Expr::GNUNullExprClass:
12663   case Expr::SourceLocExprClass:
12664     return NoDiag();
12665 
12666   case Expr::SubstNonTypeTemplateParmExprClass:
12667     return
12668       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
12669 
12670   case Expr::ConstantExprClass:
12671     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
12672 
12673   case Expr::ParenExprClass:
12674     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
12675   case Expr::GenericSelectionExprClass:
12676     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
12677   case Expr::IntegerLiteralClass:
12678   case Expr::FixedPointLiteralClass:
12679   case Expr::CharacterLiteralClass:
12680   case Expr::ObjCBoolLiteralExprClass:
12681   case Expr::CXXBoolLiteralExprClass:
12682   case Expr::CXXScalarValueInitExprClass:
12683   case Expr::TypeTraitExprClass:
12684   case Expr::ArrayTypeTraitExprClass:
12685   case Expr::ExpressionTraitExprClass:
12686   case Expr::CXXNoexceptExprClass:
12687     return NoDiag();
12688   case Expr::CallExprClass:
12689   case Expr::CXXOperatorCallExprClass: {
12690     // C99 6.6/3 allows function calls within unevaluated subexpressions of
12691     // constant expressions, but they can never be ICEs because an ICE cannot
12692     // contain an operand of (pointer to) function type.
12693     const CallExpr *CE = cast<CallExpr>(E);
12694     if (CE->getBuiltinCallee())
12695       return CheckEvalInICE(E, Ctx);
12696     return ICEDiag(IK_NotICE, E->getBeginLoc());
12697   }
12698   case Expr::DeclRefExprClass: {
12699     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
12700       return NoDiag();
12701     const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
12702     if (Ctx.getLangOpts().CPlusPlus &&
12703         D && IsConstNonVolatile(D->getType())) {
12704       // Parameter variables are never constants.  Without this check,
12705       // getAnyInitializer() can find a default argument, which leads
12706       // to chaos.
12707       if (isa<ParmVarDecl>(D))
12708         return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
12709 
12710       // C++ 7.1.5.1p2
12711       //   A variable of non-volatile const-qualified integral or enumeration
12712       //   type initialized by an ICE can be used in ICEs.
12713       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
12714         if (!Dcl->getType()->isIntegralOrEnumerationType())
12715           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
12716 
12717         const VarDecl *VD;
12718         // Look for a declaration of this variable that has an initializer, and
12719         // check whether it is an ICE.
12720         if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
12721           return NoDiag();
12722         else
12723           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
12724       }
12725     }
12726     return ICEDiag(IK_NotICE, E->getBeginLoc());
12727   }
12728   case Expr::UnaryOperatorClass: {
12729     const UnaryOperator *Exp = cast<UnaryOperator>(E);
12730     switch (Exp->getOpcode()) {
12731     case UO_PostInc:
12732     case UO_PostDec:
12733     case UO_PreInc:
12734     case UO_PreDec:
12735     case UO_AddrOf:
12736     case UO_Deref:
12737     case UO_Coawait:
12738       // C99 6.6/3 allows increment and decrement within unevaluated
12739       // subexpressions of constant expressions, but they can never be ICEs
12740       // because an ICE cannot contain an lvalue operand.
12741       return ICEDiag(IK_NotICE, E->getBeginLoc());
12742     case UO_Extension:
12743     case UO_LNot:
12744     case UO_Plus:
12745     case UO_Minus:
12746     case UO_Not:
12747     case UO_Real:
12748     case UO_Imag:
12749       return CheckICE(Exp->getSubExpr(), Ctx);
12750     }
12751     llvm_unreachable("invalid unary operator class");
12752   }
12753   case Expr::OffsetOfExprClass: {
12754     // Note that per C99, offsetof must be an ICE. And AFAIK, using
12755     // EvaluateAsRValue matches the proposed gcc behavior for cases like
12756     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
12757     // compliance: we should warn earlier for offsetof expressions with
12758     // array subscripts that aren't ICEs, and if the array subscripts
12759     // are ICEs, the value of the offsetof must be an integer constant.
12760     return CheckEvalInICE(E, Ctx);
12761   }
12762   case Expr::UnaryExprOrTypeTraitExprClass: {
12763     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
12764     if ((Exp->getKind() ==  UETT_SizeOf) &&
12765         Exp->getTypeOfArgument()->isVariableArrayType())
12766       return ICEDiag(IK_NotICE, E->getBeginLoc());
12767     return NoDiag();
12768   }
12769   case Expr::BinaryOperatorClass: {
12770     const BinaryOperator *Exp = cast<BinaryOperator>(E);
12771     switch (Exp->getOpcode()) {
12772     case BO_PtrMemD:
12773     case BO_PtrMemI:
12774     case BO_Assign:
12775     case BO_MulAssign:
12776     case BO_DivAssign:
12777     case BO_RemAssign:
12778     case BO_AddAssign:
12779     case BO_SubAssign:
12780     case BO_ShlAssign:
12781     case BO_ShrAssign:
12782     case BO_AndAssign:
12783     case BO_XorAssign:
12784     case BO_OrAssign:
12785       // C99 6.6/3 allows assignments within unevaluated subexpressions of
12786       // constant expressions, but they can never be ICEs because an ICE cannot
12787       // contain an lvalue operand.
12788       return ICEDiag(IK_NotICE, E->getBeginLoc());
12789 
12790     case BO_Mul:
12791     case BO_Div:
12792     case BO_Rem:
12793     case BO_Add:
12794     case BO_Sub:
12795     case BO_Shl:
12796     case BO_Shr:
12797     case BO_LT:
12798     case BO_GT:
12799     case BO_LE:
12800     case BO_GE:
12801     case BO_EQ:
12802     case BO_NE:
12803     case BO_And:
12804     case BO_Xor:
12805     case BO_Or:
12806     case BO_Comma:
12807     case BO_Cmp: {
12808       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12809       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
12810       if (Exp->getOpcode() == BO_Div ||
12811           Exp->getOpcode() == BO_Rem) {
12812         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
12813         // we don't evaluate one.
12814         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
12815           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
12816           if (REval == 0)
12817             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
12818           if (REval.isSigned() && REval.isAllOnesValue()) {
12819             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
12820             if (LEval.isMinSignedValue())
12821               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
12822           }
12823         }
12824       }
12825       if (Exp->getOpcode() == BO_Comma) {
12826         if (Ctx.getLangOpts().C99) {
12827           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
12828           // if it isn't evaluated.
12829           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
12830             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
12831         } else {
12832           // In both C89 and C++, commas in ICEs are illegal.
12833           return ICEDiag(IK_NotICE, E->getBeginLoc());
12834         }
12835       }
12836       return Worst(LHSResult, RHSResult);
12837     }
12838     case BO_LAnd:
12839     case BO_LOr: {
12840       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12841       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
12842       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
12843         // Rare case where the RHS has a comma "side-effect"; we need
12844         // to actually check the condition to see whether the side
12845         // with the comma is evaluated.
12846         if ((Exp->getOpcode() == BO_LAnd) !=
12847             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
12848           return RHSResult;
12849         return NoDiag();
12850       }
12851 
12852       return Worst(LHSResult, RHSResult);
12853     }
12854     }
12855     llvm_unreachable("invalid binary operator kind");
12856   }
12857   case Expr::ImplicitCastExprClass:
12858   case Expr::CStyleCastExprClass:
12859   case Expr::CXXFunctionalCastExprClass:
12860   case Expr::CXXStaticCastExprClass:
12861   case Expr::CXXReinterpretCastExprClass:
12862   case Expr::CXXConstCastExprClass:
12863   case Expr::ObjCBridgedCastExprClass: {
12864     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
12865     if (isa<ExplicitCastExpr>(E)) {
12866       if (const FloatingLiteral *FL
12867             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
12868         unsigned DestWidth = Ctx.getIntWidth(E->getType());
12869         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
12870         APSInt IgnoredVal(DestWidth, !DestSigned);
12871         bool Ignored;
12872         // If the value does not fit in the destination type, the behavior is
12873         // undefined, so we are not required to treat it as a constant
12874         // expression.
12875         if (FL->getValue().convertToInteger(IgnoredVal,
12876                                             llvm::APFloat::rmTowardZero,
12877                                             &Ignored) & APFloat::opInvalidOp)
12878           return ICEDiag(IK_NotICE, E->getBeginLoc());
12879         return NoDiag();
12880       }
12881     }
12882     switch (cast<CastExpr>(E)->getCastKind()) {
12883     case CK_LValueToRValue:
12884     case CK_AtomicToNonAtomic:
12885     case CK_NonAtomicToAtomic:
12886     case CK_NoOp:
12887     case CK_IntegralToBoolean:
12888     case CK_IntegralCast:
12889       return CheckICE(SubExpr, Ctx);
12890     default:
12891       return ICEDiag(IK_NotICE, E->getBeginLoc());
12892     }
12893   }
12894   case Expr::BinaryConditionalOperatorClass: {
12895     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
12896     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
12897     if (CommonResult.Kind == IK_NotICE) return CommonResult;
12898     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
12899     if (FalseResult.Kind == IK_NotICE) return FalseResult;
12900     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
12901     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
12902         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
12903     return FalseResult;
12904   }
12905   case Expr::ConditionalOperatorClass: {
12906     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
12907     // If the condition (ignoring parens) is a __builtin_constant_p call,
12908     // then only the true side is actually considered in an integer constant
12909     // expression, and it is fully evaluated.  This is an important GNU
12910     // extension.  See GCC PR38377 for discussion.
12911     if (const CallExpr *CallCE
12912         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
12913       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
12914         return CheckEvalInICE(E, Ctx);
12915     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
12916     if (CondResult.Kind == IK_NotICE)
12917       return CondResult;
12918 
12919     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
12920     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
12921 
12922     if (TrueResult.Kind == IK_NotICE)
12923       return TrueResult;
12924     if (FalseResult.Kind == IK_NotICE)
12925       return FalseResult;
12926     if (CondResult.Kind == IK_ICEIfUnevaluated)
12927       return CondResult;
12928     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
12929       return NoDiag();
12930     // Rare case where the diagnostics depend on which side is evaluated
12931     // Note that if we get here, CondResult is 0, and at least one of
12932     // TrueResult and FalseResult is non-zero.
12933     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
12934       return FalseResult;
12935     return TrueResult;
12936   }
12937   case Expr::CXXDefaultArgExprClass:
12938     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
12939   case Expr::CXXDefaultInitExprClass:
12940     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
12941   case Expr::ChooseExprClass: {
12942     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
12943   }
12944   case Expr::BuiltinBitCastExprClass: {
12945     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
12946       return ICEDiag(IK_NotICE, E->getBeginLoc());
12947     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
12948   }
12949   }
12950 
12951   llvm_unreachable("Invalid StmtClass!");
12952 }
12953 
12954 /// Evaluate an expression as a C++11 integral constant expression.
12955 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
12956                                                     const Expr *E,
12957                                                     llvm::APSInt *Value,
12958                                                     SourceLocation *Loc) {
12959   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
12960     if (Loc) *Loc = E->getExprLoc();
12961     return false;
12962   }
12963 
12964   APValue Result;
12965   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
12966     return false;
12967 
12968   if (!Result.isInt()) {
12969     if (Loc) *Loc = E->getExprLoc();
12970     return false;
12971   }
12972 
12973   if (Value) *Value = Result.getInt();
12974   return true;
12975 }
12976 
12977 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
12978                                  SourceLocation *Loc) const {
12979   assert(!isValueDependent() &&
12980          "Expression evaluator can't be called on a dependent expression.");
12981 
12982   if (Ctx.getLangOpts().CPlusPlus11)
12983     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
12984 
12985   ICEDiag D = CheckICE(this, Ctx);
12986   if (D.Kind != IK_ICE) {
12987     if (Loc) *Loc = D.Loc;
12988     return false;
12989   }
12990   return true;
12991 }
12992 
12993 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
12994                                  SourceLocation *Loc, bool isEvaluated) const {
12995   assert(!isValueDependent() &&
12996          "Expression evaluator can't be called on a dependent expression.");
12997 
12998   if (Ctx.getLangOpts().CPlusPlus11)
12999     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
13000 
13001   if (!isIntegerConstantExpr(Ctx, Loc))
13002     return false;
13003 
13004   // The only possible side-effects here are due to UB discovered in the
13005   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
13006   // required to treat the expression as an ICE, so we produce the folded
13007   // value.
13008   EvalResult ExprResult;
13009   Expr::EvalStatus Status;
13010   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
13011   Info.InConstantContext = true;
13012 
13013   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
13014     llvm_unreachable("ICE cannot be evaluated!");
13015 
13016   Value = ExprResult.Val.getInt();
13017   return true;
13018 }
13019 
13020 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
13021   assert(!isValueDependent() &&
13022          "Expression evaluator can't be called on a dependent expression.");
13023 
13024   return CheckICE(this, Ctx).Kind == IK_ICE;
13025 }
13026 
13027 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
13028                                SourceLocation *Loc) const {
13029   assert(!isValueDependent() &&
13030          "Expression evaluator can't be called on a dependent expression.");
13031 
13032   // We support this checking in C++98 mode in order to diagnose compatibility
13033   // issues.
13034   assert(Ctx.getLangOpts().CPlusPlus);
13035 
13036   // Build evaluation settings.
13037   Expr::EvalStatus Status;
13038   SmallVector<PartialDiagnosticAt, 8> Diags;
13039   Status.Diag = &Diags;
13040   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
13041 
13042   APValue Scratch;
13043   bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
13044 
13045   if (!Diags.empty()) {
13046     IsConstExpr = false;
13047     if (Loc) *Loc = Diags[0].first;
13048   } else if (!IsConstExpr) {
13049     // FIXME: This shouldn't happen.
13050     if (Loc) *Loc = getExprLoc();
13051   }
13052 
13053   return IsConstExpr;
13054 }
13055 
13056 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
13057                                     const FunctionDecl *Callee,
13058                                     ArrayRef<const Expr*> Args,
13059                                     const Expr *This) const {
13060   assert(!isValueDependent() &&
13061          "Expression evaluator can't be called on a dependent expression.");
13062 
13063   Expr::EvalStatus Status;
13064   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
13065   Info.InConstantContext = true;
13066 
13067   LValue ThisVal;
13068   const LValue *ThisPtr = nullptr;
13069   if (This) {
13070 #ifndef NDEBUG
13071     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
13072     assert(MD && "Don't provide `this` for non-methods.");
13073     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
13074 #endif
13075     if (EvaluateObjectArgument(Info, This, ThisVal))
13076       ThisPtr = &ThisVal;
13077     if (Info.EvalStatus.HasSideEffects)
13078       return false;
13079   }
13080 
13081   ArgVector ArgValues(Args.size());
13082   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
13083        I != E; ++I) {
13084     if ((*I)->isValueDependent() ||
13085         !Evaluate(ArgValues[I - Args.begin()], Info, *I))
13086       // If evaluation fails, throw away the argument entirely.
13087       ArgValues[I - Args.begin()] = APValue();
13088     if (Info.EvalStatus.HasSideEffects)
13089       return false;
13090   }
13091 
13092   // Build fake call to Callee.
13093   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
13094                        ArgValues.data());
13095   return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
13096 }
13097 
13098 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
13099                                    SmallVectorImpl<
13100                                      PartialDiagnosticAt> &Diags) {
13101   // FIXME: It would be useful to check constexpr function templates, but at the
13102   // moment the constant expression evaluator cannot cope with the non-rigorous
13103   // ASTs which we build for dependent expressions.
13104   if (FD->isDependentContext())
13105     return true;
13106 
13107   Expr::EvalStatus Status;
13108   Status.Diag = &Diags;
13109 
13110   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
13111   Info.InConstantContext = true;
13112   Info.CheckingPotentialConstantExpression = true;
13113 
13114   // The constexpr VM attempts to compile all methods to bytecode here.
13115   if (Info.EnableNewConstInterp) {
13116     auto &InterpCtx = Info.Ctx.getInterpContext();
13117     switch (InterpCtx.isPotentialConstantExpr(Info, FD)) {
13118     case interp::InterpResult::Success:
13119     case interp::InterpResult::Fail:
13120       return Diags.empty();
13121     case interp::InterpResult::Bail:
13122       break;
13123     }
13124   }
13125 
13126   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
13127   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
13128 
13129   // Fabricate an arbitrary expression on the stack and pretend that it
13130   // is a temporary being used as the 'this' pointer.
13131   LValue This;
13132   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
13133   This.set({&VIE, Info.CurrentCall->Index});
13134 
13135   ArrayRef<const Expr*> Args;
13136 
13137   APValue Scratch;
13138   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
13139     // Evaluate the call as a constant initializer, to allow the construction
13140     // of objects of non-literal types.
13141     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
13142     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
13143   } else {
13144     SourceLocation Loc = FD->getLocation();
13145     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
13146                        Args, FD->getBody(), Info, Scratch, nullptr);
13147   }
13148 
13149   return Diags.empty();
13150 }
13151 
13152 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
13153                                               const FunctionDecl *FD,
13154                                               SmallVectorImpl<
13155                                                 PartialDiagnosticAt> &Diags) {
13156   assert(!E->isValueDependent() &&
13157          "Expression evaluator can't be called on a dependent expression.");
13158 
13159   Expr::EvalStatus Status;
13160   Status.Diag = &Diags;
13161 
13162   EvalInfo Info(FD->getASTContext(), Status,
13163                 EvalInfo::EM_ConstantExpressionUnevaluated);
13164   Info.InConstantContext = true;
13165   Info.CheckingPotentialConstantExpression = true;
13166 
13167   // Fabricate a call stack frame to give the arguments a plausible cover story.
13168   ArrayRef<const Expr*> Args;
13169   ArgVector ArgValues(0);
13170   bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
13171   (void)Success;
13172   assert(Success &&
13173          "Failed to set up arguments for potential constant evaluation");
13174   CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
13175 
13176   APValue ResultScratch;
13177   Evaluate(ResultScratch, Info, E);
13178   return Diags.empty();
13179 }
13180 
13181 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
13182                                  unsigned Type) const {
13183   if (!getType()->isPointerType())
13184     return false;
13185 
13186   Expr::EvalStatus Status;
13187   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
13188   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
13189 }
13190