1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Expr constant evaluator.
11 //
12 // Constant expression evaluation produces four main results:
13 //
14 //  * A success/failure flag indicating whether constant folding was successful.
15 //    This is the 'bool' return value used by most of the code in this file. A
16 //    'false' return value indicates that constant folding has failed, and any
17 //    appropriate diagnostic has already been produced.
18 //
19 //  * An evaluated result, valid only if constant folding has not failed.
20 //
21 //  * A flag indicating if evaluation encountered (unevaluated) side-effects.
22 //    These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23 //    where it is possible to determine the evaluated result regardless.
24 //
25 //  * A set of notes indicating why the evaluation was not a constant expression
26 //    (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27 //    too, why the expression could not be folded.
28 //
29 // If we are checking for a potential constant expression, failure to constant
30 // fold a potential constant sub-expression will be indicated by a 'false'
31 // return value (the expression could not be folded) and no diagnostic (the
32 // expression is not necessarily non-constant).
33 //
34 //===----------------------------------------------------------------------===//
35 
36 #include "clang/AST/APValue.h"
37 #include "clang/AST/ASTContext.h"
38 #include "clang/AST/ASTDiagnostic.h"
39 #include "clang/AST/ASTLambda.h"
40 #include "clang/AST/CharUnits.h"
41 #include "clang/AST/Expr.h"
42 #include "clang/AST/RecordLayout.h"
43 #include "clang/AST/StmtVisitor.h"
44 #include "clang/AST/TypeLoc.h"
45 #include "clang/Basic/Builtins.h"
46 #include "clang/Basic/TargetInfo.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include <cstring>
49 #include <functional>
50 
51 #define DEBUG_TYPE "exprconstant"
52 
53 using namespace clang;
54 using llvm::APSInt;
55 using llvm::APFloat;
56 
57 static bool IsGlobalLValue(APValue::LValueBase B);
58 
59 namespace {
60   struct LValue;
61   struct CallStackFrame;
62   struct EvalInfo;
63 
64   static QualType getType(APValue::LValueBase B) {
65     if (!B) return QualType();
66     if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
67       // FIXME: It's unclear where we're supposed to take the type from, and
68       // this actually matters for arrays of unknown bound. Eg:
69       //
70       // extern int arr[]; void f() { extern int arr[3]; };
71       // constexpr int *p = &arr[1]; // valid?
72       //
73       // For now, we take the array bound from the most recent declaration.
74       for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
75            Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
76         QualType T = Redecl->getType();
77         if (!T->isIncompleteArrayType())
78           return T;
79       }
80       return D->getType();
81     }
82 
83     const Expr *Base = B.get<const Expr*>();
84 
85     // For a materialized temporary, the type of the temporary we materialized
86     // may not be the type of the expression.
87     if (const MaterializeTemporaryExpr *MTE =
88             dyn_cast<MaterializeTemporaryExpr>(Base)) {
89       SmallVector<const Expr *, 2> CommaLHSs;
90       SmallVector<SubobjectAdjustment, 2> Adjustments;
91       const Expr *Temp = MTE->GetTemporaryExpr();
92       const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
93                                                                Adjustments);
94       // Keep any cv-qualifiers from the reference if we generated a temporary
95       // for it directly. Otherwise use the type after adjustment.
96       if (!Adjustments.empty())
97         return Inner->getType();
98     }
99 
100     return Base->getType();
101   }
102 
103   /// Get an LValue path entry, which is known to not be an array index, as a
104   /// field or base class.
105   static
106   APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
107     APValue::BaseOrMemberType Value;
108     Value.setFromOpaqueValue(E.BaseOrMember);
109     return Value;
110   }
111 
112   /// Get an LValue path entry, which is known to not be an array index, as a
113   /// field declaration.
114   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
115     return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
116   }
117   /// Get an LValue path entry, which is known to not be an array index, as a
118   /// base class declaration.
119   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
120     return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
121   }
122   /// Determine whether this LValue path entry for a base class names a virtual
123   /// base class.
124   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
125     return getAsBaseOrMember(E).getInt();
126   }
127 
128   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
129   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
130     const FunctionDecl *Callee = CE->getDirectCallee();
131     return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
132   }
133 
134   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
135   /// This will look through a single cast.
136   ///
137   /// Returns null if we couldn't unwrap a function with alloc_size.
138   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
139     if (!E->getType()->isPointerType())
140       return nullptr;
141 
142     E = E->IgnoreParens();
143     // If we're doing a variable assignment from e.g. malloc(N), there will
144     // probably be a cast of some kind. In exotic cases, we might also see a
145     // top-level ExprWithCleanups. Ignore them either way.
146     if (const auto *EC = dyn_cast<ExprWithCleanups>(E))
147       E = EC->getSubExpr()->IgnoreParens();
148 
149     if (const auto *Cast = dyn_cast<CastExpr>(E))
150       E = Cast->getSubExpr()->IgnoreParens();
151 
152     if (const auto *CE = dyn_cast<CallExpr>(E))
153       return getAllocSizeAttr(CE) ? CE : nullptr;
154     return nullptr;
155   }
156 
157   /// Determines whether or not the given Base contains a call to a function
158   /// with the alloc_size attribute.
159   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
160     const auto *E = Base.dyn_cast<const Expr *>();
161     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
162   }
163 
164   /// The bound to claim that an array of unknown bound has.
165   /// The value in MostDerivedArraySize is undefined in this case. So, set it
166   /// to an arbitrary value that's likely to loudly break things if it's used.
167   static const uint64_t AssumedSizeForUnsizedArray =
168       std::numeric_limits<uint64_t>::max() / 2;
169 
170   /// Determines if an LValue with the given LValueBase will have an unsized
171   /// array in its designator.
172   /// Find the path length and type of the most-derived subobject in the given
173   /// path, and find the size of the containing array, if any.
174   static unsigned
175   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
176                            ArrayRef<APValue::LValuePathEntry> Path,
177                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
178                            bool &FirstEntryIsUnsizedArray) {
179     // This only accepts LValueBases from APValues, and APValues don't support
180     // arrays that lack size info.
181     assert(!isBaseAnAllocSizeCall(Base) &&
182            "Unsized arrays shouldn't appear here");
183     unsigned MostDerivedLength = 0;
184     Type = getType(Base);
185 
186     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
187       if (Type->isArrayType()) {
188         const ArrayType *AT = Ctx.getAsArrayType(Type);
189         Type = AT->getElementType();
190         MostDerivedLength = I + 1;
191         IsArray = true;
192 
193         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
194           ArraySize = CAT->getSize().getZExtValue();
195         } else {
196           assert(I == 0 && "unexpected unsized array designator");
197           FirstEntryIsUnsizedArray = true;
198           ArraySize = AssumedSizeForUnsizedArray;
199         }
200       } else if (Type->isAnyComplexType()) {
201         const ComplexType *CT = Type->castAs<ComplexType>();
202         Type = CT->getElementType();
203         ArraySize = 2;
204         MostDerivedLength = I + 1;
205         IsArray = true;
206       } else if (const FieldDecl *FD = getAsField(Path[I])) {
207         Type = FD->getType();
208         ArraySize = 0;
209         MostDerivedLength = I + 1;
210         IsArray = false;
211       } else {
212         // Path[I] describes a base class.
213         ArraySize = 0;
214         IsArray = false;
215       }
216     }
217     return MostDerivedLength;
218   }
219 
220   // The order of this enum is important for diagnostics.
221   enum CheckSubobjectKind {
222     CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
223     CSK_This, CSK_Real, CSK_Imag
224   };
225 
226   /// A path from a glvalue to a subobject of that glvalue.
227   struct SubobjectDesignator {
228     /// True if the subobject was named in a manner not supported by C++11. Such
229     /// lvalues can still be folded, but they are not core constant expressions
230     /// and we cannot perform lvalue-to-rvalue conversions on them.
231     unsigned Invalid : 1;
232 
233     /// Is this a pointer one past the end of an object?
234     unsigned IsOnePastTheEnd : 1;
235 
236     /// Indicator of whether the first entry is an unsized array.
237     unsigned FirstEntryIsAnUnsizedArray : 1;
238 
239     /// Indicator of whether the most-derived object is an array element.
240     unsigned MostDerivedIsArrayElement : 1;
241 
242     /// The length of the path to the most-derived object of which this is a
243     /// subobject.
244     unsigned MostDerivedPathLength : 28;
245 
246     /// The size of the array of which the most-derived object is an element.
247     /// This will always be 0 if the most-derived object is not an array
248     /// element. 0 is not an indicator of whether or not the most-derived object
249     /// is an array, however, because 0-length arrays are allowed.
250     ///
251     /// If the current array is an unsized array, the value of this is
252     /// undefined.
253     uint64_t MostDerivedArraySize;
254 
255     /// The type of the most derived object referred to by this address.
256     QualType MostDerivedType;
257 
258     typedef APValue::LValuePathEntry PathEntry;
259 
260     /// The entries on the path from the glvalue to the designated subobject.
261     SmallVector<PathEntry, 8> Entries;
262 
263     SubobjectDesignator() : Invalid(true) {}
264 
265     explicit SubobjectDesignator(QualType T)
266         : Invalid(false), IsOnePastTheEnd(false),
267           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
268           MostDerivedPathLength(0), MostDerivedArraySize(0),
269           MostDerivedType(T) {}
270 
271     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
272         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
273           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
274           MostDerivedPathLength(0), MostDerivedArraySize(0) {
275       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
276       if (!Invalid) {
277         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
278         ArrayRef<PathEntry> VEntries = V.getLValuePath();
279         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
280         if (V.getLValueBase()) {
281           bool IsArray = false;
282           bool FirstIsUnsizedArray = false;
283           MostDerivedPathLength = findMostDerivedSubobject(
284               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
285               MostDerivedType, IsArray, FirstIsUnsizedArray);
286           MostDerivedIsArrayElement = IsArray;
287           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
288         }
289       }
290     }
291 
292     void setInvalid() {
293       Invalid = true;
294       Entries.clear();
295     }
296 
297     /// Determine whether the most derived subobject is an array without a
298     /// known bound.
299     bool isMostDerivedAnUnsizedArray() const {
300       assert(!Invalid && "Calling this makes no sense on invalid designators");
301       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
302     }
303 
304     /// Determine what the most derived array's size is. Results in an assertion
305     /// failure if the most derived array lacks a size.
306     uint64_t getMostDerivedArraySize() const {
307       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
308       return MostDerivedArraySize;
309     }
310 
311     /// Determine whether this is a one-past-the-end pointer.
312     bool isOnePastTheEnd() const {
313       assert(!Invalid);
314       if (IsOnePastTheEnd)
315         return true;
316       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
317           Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
318         return true;
319       return false;
320     }
321 
322     /// Get the range of valid index adjustments in the form
323     ///   {maximum value that can be subtracted from this pointer,
324     ///    maximum value that can be added to this pointer}
325     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
326       if (Invalid || isMostDerivedAnUnsizedArray())
327         return {0, 0};
328 
329       // [expr.add]p4: For the purposes of these operators, a pointer to a
330       // nonarray object behaves the same as a pointer to the first element of
331       // an array of length one with the type of the object as its element type.
332       bool IsArray = MostDerivedPathLength == Entries.size() &&
333                      MostDerivedIsArrayElement;
334       uint64_t ArrayIndex =
335           IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
336       uint64_t ArraySize =
337           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
338       return {ArrayIndex, ArraySize - ArrayIndex};
339     }
340 
341     /// Check that this refers to a valid subobject.
342     bool isValidSubobject() const {
343       if (Invalid)
344         return false;
345       return !isOnePastTheEnd();
346     }
347     /// Check that this refers to a valid subobject, and if not, produce a
348     /// relevant diagnostic and set the designator as invalid.
349     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
350 
351     /// Get the type of the designated object.
352     QualType getType(ASTContext &Ctx) const {
353       assert(!Invalid && "invalid designator has no subobject type");
354       return MostDerivedPathLength == Entries.size()
355                  ? MostDerivedType
356                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
357     }
358 
359     /// Update this designator to refer to the first element within this array.
360     void addArrayUnchecked(const ConstantArrayType *CAT) {
361       PathEntry Entry;
362       Entry.ArrayIndex = 0;
363       Entries.push_back(Entry);
364 
365       // This is a most-derived object.
366       MostDerivedType = CAT->getElementType();
367       MostDerivedIsArrayElement = true;
368       MostDerivedArraySize = CAT->getSize().getZExtValue();
369       MostDerivedPathLength = Entries.size();
370     }
371     /// Update this designator to refer to the first element within the array of
372     /// elements of type T. This is an array of unknown size.
373     void addUnsizedArrayUnchecked(QualType ElemTy) {
374       PathEntry Entry;
375       Entry.ArrayIndex = 0;
376       Entries.push_back(Entry);
377 
378       MostDerivedType = ElemTy;
379       MostDerivedIsArrayElement = true;
380       // The value in MostDerivedArraySize is undefined in this case. So, set it
381       // to an arbitrary value that's likely to loudly break things if it's
382       // used.
383       MostDerivedArraySize = AssumedSizeForUnsizedArray;
384       MostDerivedPathLength = Entries.size();
385     }
386     /// Update this designator to refer to the given base or member of this
387     /// object.
388     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
389       PathEntry Entry;
390       APValue::BaseOrMemberType Value(D, Virtual);
391       Entry.BaseOrMember = Value.getOpaqueValue();
392       Entries.push_back(Entry);
393 
394       // If this isn't a base class, it's a new most-derived object.
395       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
396         MostDerivedType = FD->getType();
397         MostDerivedIsArrayElement = false;
398         MostDerivedArraySize = 0;
399         MostDerivedPathLength = Entries.size();
400       }
401     }
402     /// Update this designator to refer to the given complex component.
403     void addComplexUnchecked(QualType EltTy, bool Imag) {
404       PathEntry Entry;
405       Entry.ArrayIndex = Imag;
406       Entries.push_back(Entry);
407 
408       // This is technically a most-derived object, though in practice this
409       // is unlikely to matter.
410       MostDerivedType = EltTy;
411       MostDerivedIsArrayElement = true;
412       MostDerivedArraySize = 2;
413       MostDerivedPathLength = Entries.size();
414     }
415     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
416     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
417                                    const APSInt &N);
418     /// Add N to the address of this subobject.
419     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
420       if (Invalid || !N) return;
421       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
422       if (isMostDerivedAnUnsizedArray()) {
423         diagnoseUnsizedArrayPointerArithmetic(Info, E);
424         // Can't verify -- trust that the user is doing the right thing (or if
425         // not, trust that the caller will catch the bad behavior).
426         // FIXME: Should we reject if this overflows, at least?
427         Entries.back().ArrayIndex += TruncatedN;
428         return;
429       }
430 
431       // [expr.add]p4: For the purposes of these operators, a pointer to a
432       // nonarray object behaves the same as a pointer to the first element of
433       // an array of length one with the type of the object as its element type.
434       bool IsArray = MostDerivedPathLength == Entries.size() &&
435                      MostDerivedIsArrayElement;
436       uint64_t ArrayIndex =
437           IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
438       uint64_t ArraySize =
439           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
440 
441       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
442         // Calculate the actual index in a wide enough type, so we can include
443         // it in the note.
444         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
445         (llvm::APInt&)N += ArrayIndex;
446         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
447         diagnosePointerArithmetic(Info, E, N);
448         setInvalid();
449         return;
450       }
451 
452       ArrayIndex += TruncatedN;
453       assert(ArrayIndex <= ArraySize &&
454              "bounds check succeeded for out-of-bounds index");
455 
456       if (IsArray)
457         Entries.back().ArrayIndex = ArrayIndex;
458       else
459         IsOnePastTheEnd = (ArrayIndex != 0);
460     }
461   };
462 
463   /// A stack frame in the constexpr call stack.
464   struct CallStackFrame {
465     EvalInfo &Info;
466 
467     /// Parent - The caller of this stack frame.
468     CallStackFrame *Caller;
469 
470     /// Callee - The function which was called.
471     const FunctionDecl *Callee;
472 
473     /// This - The binding for the this pointer in this call, if any.
474     const LValue *This;
475 
476     /// Arguments - Parameter bindings for this function call, indexed by
477     /// parameters' function scope indices.
478     APValue *Arguments;
479 
480     // Note that we intentionally use std::map here so that references to
481     // values are stable.
482     typedef std::pair<const void *, unsigned> MapKeyTy;
483     typedef std::map<MapKeyTy, APValue> MapTy;
484     /// Temporaries - Temporary lvalues materialized within this stack frame.
485     MapTy Temporaries;
486 
487     /// CallLoc - The location of the call expression for this call.
488     SourceLocation CallLoc;
489 
490     /// Index - The call index of this call.
491     unsigned Index;
492 
493     /// The stack of integers for tracking version numbers for temporaries.
494     SmallVector<unsigned, 2> TempVersionStack = {1};
495     unsigned CurTempVersion = TempVersionStack.back();
496 
497     unsigned getTempVersion() const { return TempVersionStack.back(); }
498 
499     void pushTempVersion() {
500       TempVersionStack.push_back(++CurTempVersion);
501     }
502 
503     void popTempVersion() {
504       TempVersionStack.pop_back();
505     }
506 
507     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
508     // on the overall stack usage of deeply-recursing constexpr evaluataions.
509     // (We should cache this map rather than recomputing it repeatedly.)
510     // But let's try this and see how it goes; we can look into caching the map
511     // as a later change.
512 
513     /// LambdaCaptureFields - Mapping from captured variables/this to
514     /// corresponding data members in the closure class.
515     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
516     FieldDecl *LambdaThisCaptureField;
517 
518     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
519                    const FunctionDecl *Callee, const LValue *This,
520                    APValue *Arguments);
521     ~CallStackFrame();
522 
523     // Return the temporary for Key whose version number is Version.
524     APValue *getTemporary(const void *Key, unsigned Version) {
525       MapKeyTy KV(Key, Version);
526       auto LB = Temporaries.lower_bound(KV);
527       if (LB != Temporaries.end() && LB->first == KV)
528         return &LB->second;
529       // Pair (Key,Version) wasn't found in the map. Check that no elements
530       // in the map have 'Key' as their key.
531       assert((LB == Temporaries.end() || LB->first.first != Key) &&
532              (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
533              "Element with key 'Key' found in map");
534       return nullptr;
535     }
536 
537     // Return the current temporary for Key in the map.
538     APValue *getCurrentTemporary(const void *Key) {
539       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
540       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
541         return &std::prev(UB)->second;
542       return nullptr;
543     }
544 
545     // Return the version number of the current temporary for Key.
546     unsigned getCurrentTemporaryVersion(const void *Key) const {
547       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
548       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
549         return std::prev(UB)->first.second;
550       return 0;
551     }
552 
553     APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
554   };
555 
556   /// Temporarily override 'this'.
557   class ThisOverrideRAII {
558   public:
559     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
560         : Frame(Frame), OldThis(Frame.This) {
561       if (Enable)
562         Frame.This = NewThis;
563     }
564     ~ThisOverrideRAII() {
565       Frame.This = OldThis;
566     }
567   private:
568     CallStackFrame &Frame;
569     const LValue *OldThis;
570   };
571 
572   /// A partial diagnostic which we might know in advance that we are not going
573   /// to emit.
574   class OptionalDiagnostic {
575     PartialDiagnostic *Diag;
576 
577   public:
578     explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
579       : Diag(Diag) {}
580 
581     template<typename T>
582     OptionalDiagnostic &operator<<(const T &v) {
583       if (Diag)
584         *Diag << v;
585       return *this;
586     }
587 
588     OptionalDiagnostic &operator<<(const APSInt &I) {
589       if (Diag) {
590         SmallVector<char, 32> Buffer;
591         I.toString(Buffer);
592         *Diag << StringRef(Buffer.data(), Buffer.size());
593       }
594       return *this;
595     }
596 
597     OptionalDiagnostic &operator<<(const APFloat &F) {
598       if (Diag) {
599         // FIXME: Force the precision of the source value down so we don't
600         // print digits which are usually useless (we don't really care here if
601         // we truncate a digit by accident in edge cases).  Ideally,
602         // APFloat::toString would automatically print the shortest
603         // representation which rounds to the correct value, but it's a bit
604         // tricky to implement.
605         unsigned precision =
606             llvm::APFloat::semanticsPrecision(F.getSemantics());
607         precision = (precision * 59 + 195) / 196;
608         SmallVector<char, 32> Buffer;
609         F.toString(Buffer, precision);
610         *Diag << StringRef(Buffer.data(), Buffer.size());
611       }
612       return *this;
613     }
614   };
615 
616   /// A cleanup, and a flag indicating whether it is lifetime-extended.
617   class Cleanup {
618     llvm::PointerIntPair<APValue*, 1, bool> Value;
619 
620   public:
621     Cleanup(APValue *Val, bool IsLifetimeExtended)
622         : Value(Val, IsLifetimeExtended) {}
623 
624     bool isLifetimeExtended() const { return Value.getInt(); }
625     void endLifetime() {
626       *Value.getPointer() = APValue();
627     }
628   };
629 
630   /// EvalInfo - This is a private struct used by the evaluator to capture
631   /// information about a subexpression as it is folded.  It retains information
632   /// about the AST context, but also maintains information about the folded
633   /// expression.
634   ///
635   /// If an expression could be evaluated, it is still possible it is not a C
636   /// "integer constant expression" or constant expression.  If not, this struct
637   /// captures information about how and why not.
638   ///
639   /// One bit of information passed *into* the request for constant folding
640   /// indicates whether the subexpression is "evaluated" or not according to C
641   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
642   /// evaluate the expression regardless of what the RHS is, but C only allows
643   /// certain things in certain situations.
644   struct EvalInfo {
645     ASTContext &Ctx;
646 
647     /// EvalStatus - Contains information about the evaluation.
648     Expr::EvalStatus &EvalStatus;
649 
650     /// CurrentCall - The top of the constexpr call stack.
651     CallStackFrame *CurrentCall;
652 
653     /// CallStackDepth - The number of calls in the call stack right now.
654     unsigned CallStackDepth;
655 
656     /// NextCallIndex - The next call index to assign.
657     unsigned NextCallIndex;
658 
659     /// StepsLeft - The remaining number of evaluation steps we're permitted
660     /// to perform. This is essentially a limit for the number of statements
661     /// we will evaluate.
662     unsigned StepsLeft;
663 
664     /// BottomFrame - The frame in which evaluation started. This must be
665     /// initialized after CurrentCall and CallStackDepth.
666     CallStackFrame BottomFrame;
667 
668     /// A stack of values whose lifetimes end at the end of some surrounding
669     /// evaluation frame.
670     llvm::SmallVector<Cleanup, 16> CleanupStack;
671 
672     /// EvaluatingDecl - This is the declaration whose initializer is being
673     /// evaluated, if any.
674     APValue::LValueBase EvaluatingDecl;
675 
676     /// EvaluatingDeclValue - This is the value being constructed for the
677     /// declaration whose initializer is being evaluated, if any.
678     APValue *EvaluatingDeclValue;
679 
680     /// EvaluatingObject - Pair of the AST node that an lvalue represents and
681     /// the call index that that lvalue was allocated in.
682     typedef std::pair<APValue::LValueBase, std::pair<unsigned, unsigned>>
683         EvaluatingObject;
684 
685     /// EvaluatingConstructors - Set of objects that are currently being
686     /// constructed.
687     llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
688 
689     struct EvaluatingConstructorRAII {
690       EvalInfo &EI;
691       EvaluatingObject Object;
692       bool DidInsert;
693       EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
694           : EI(EI), Object(Object) {
695         DidInsert = EI.EvaluatingConstructors.insert(Object).second;
696       }
697       ~EvaluatingConstructorRAII() {
698         if (DidInsert) EI.EvaluatingConstructors.erase(Object);
699       }
700     };
701 
702     bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex,
703                                  unsigned Version) {
704       return EvaluatingConstructors.count(
705           EvaluatingObject(Decl, {CallIndex, Version}));
706     }
707 
708     /// The current array initialization index, if we're performing array
709     /// initialization.
710     uint64_t ArrayInitIndex = -1;
711 
712     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
713     /// notes attached to it will also be stored, otherwise they will not be.
714     bool HasActiveDiagnostic;
715 
716     /// Have we emitted a diagnostic explaining why we couldn't constant
717     /// fold (not just why it's not strictly a constant expression)?
718     bool HasFoldFailureDiagnostic;
719 
720     /// Whether or not we're currently speculatively evaluating.
721     bool IsSpeculativelyEvaluating;
722 
723     enum EvaluationMode {
724       /// Evaluate as a constant expression. Stop if we find that the expression
725       /// is not a constant expression.
726       EM_ConstantExpression,
727 
728       /// Evaluate as a potential constant expression. Keep going if we hit a
729       /// construct that we can't evaluate yet (because we don't yet know the
730       /// value of something) but stop if we hit something that could never be
731       /// a constant expression.
732       EM_PotentialConstantExpression,
733 
734       /// Fold the expression to a constant. Stop if we hit a side-effect that
735       /// we can't model.
736       EM_ConstantFold,
737 
738       /// Evaluate the expression looking for integer overflow and similar
739       /// issues. Don't worry about side-effects, and try to visit all
740       /// subexpressions.
741       EM_EvaluateForOverflow,
742 
743       /// Evaluate in any way we know how. Don't worry about side-effects that
744       /// can't be modeled.
745       EM_IgnoreSideEffects,
746 
747       /// Evaluate as a constant expression. Stop if we find that the expression
748       /// is not a constant expression. Some expressions can be retried in the
749       /// optimizer if we don't constant fold them here, but in an unevaluated
750       /// context we try to fold them immediately since the optimizer never
751       /// gets a chance to look at it.
752       EM_ConstantExpressionUnevaluated,
753 
754       /// Evaluate as a potential constant expression. Keep going if we hit a
755       /// construct that we can't evaluate yet (because we don't yet know the
756       /// value of something) but stop if we hit something that could never be
757       /// a constant expression. Some expressions can be retried in the
758       /// optimizer if we don't constant fold them here, but in an unevaluated
759       /// context we try to fold them immediately since the optimizer never
760       /// gets a chance to look at it.
761       EM_PotentialConstantExpressionUnevaluated,
762     } EvalMode;
763 
764     /// Are we checking whether the expression is a potential constant
765     /// expression?
766     bool checkingPotentialConstantExpression() const {
767       return EvalMode == EM_PotentialConstantExpression ||
768              EvalMode == EM_PotentialConstantExpressionUnevaluated;
769     }
770 
771     /// Are we checking an expression for overflow?
772     // FIXME: We should check for any kind of undefined or suspicious behavior
773     // in such constructs, not just overflow.
774     bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
775 
776     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
777       : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
778         CallStackDepth(0), NextCallIndex(1),
779         StepsLeft(getLangOpts().ConstexprStepLimit),
780         BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
781         EvaluatingDecl((const ValueDecl *)nullptr),
782         EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
783         HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
784         EvalMode(Mode) {}
785 
786     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
787       EvaluatingDecl = Base;
788       EvaluatingDeclValue = &Value;
789       EvaluatingConstructors.insert({Base, {0, 0}});
790     }
791 
792     const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
793 
794     bool CheckCallLimit(SourceLocation Loc) {
795       // Don't perform any constexpr calls (other than the call we're checking)
796       // when checking a potential constant expression.
797       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
798         return false;
799       if (NextCallIndex == 0) {
800         // NextCallIndex has wrapped around.
801         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
802         return false;
803       }
804       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
805         return true;
806       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
807         << getLangOpts().ConstexprCallDepth;
808       return false;
809     }
810 
811     CallStackFrame *getCallFrame(unsigned CallIndex) {
812       assert(CallIndex && "no call index in getCallFrame");
813       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
814       // be null in this loop.
815       CallStackFrame *Frame = CurrentCall;
816       while (Frame->Index > CallIndex)
817         Frame = Frame->Caller;
818       return (Frame->Index == CallIndex) ? Frame : nullptr;
819     }
820 
821     bool nextStep(const Stmt *S) {
822       if (!StepsLeft) {
823         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
824         return false;
825       }
826       --StepsLeft;
827       return true;
828     }
829 
830   private:
831     /// Add a diagnostic to the diagnostics list.
832     PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
833       PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
834       EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
835       return EvalStatus.Diag->back().second;
836     }
837 
838     /// Add notes containing a call stack to the current point of evaluation.
839     void addCallStack(unsigned Limit);
840 
841   private:
842     OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
843                             unsigned ExtraNotes, bool IsCCEDiag) {
844 
845       if (EvalStatus.Diag) {
846         // If we have a prior diagnostic, it will be noting that the expression
847         // isn't a constant expression. This diagnostic is more important,
848         // unless we require this evaluation to produce a constant expression.
849         //
850         // FIXME: We might want to show both diagnostics to the user in
851         // EM_ConstantFold mode.
852         if (!EvalStatus.Diag->empty()) {
853           switch (EvalMode) {
854           case EM_ConstantFold:
855           case EM_IgnoreSideEffects:
856           case EM_EvaluateForOverflow:
857             if (!HasFoldFailureDiagnostic)
858               break;
859             // We've already failed to fold something. Keep that diagnostic.
860             LLVM_FALLTHROUGH;
861           case EM_ConstantExpression:
862           case EM_PotentialConstantExpression:
863           case EM_ConstantExpressionUnevaluated:
864           case EM_PotentialConstantExpressionUnevaluated:
865             HasActiveDiagnostic = false;
866             return OptionalDiagnostic();
867           }
868         }
869 
870         unsigned CallStackNotes = CallStackDepth - 1;
871         unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
872         if (Limit)
873           CallStackNotes = std::min(CallStackNotes, Limit + 1);
874         if (checkingPotentialConstantExpression())
875           CallStackNotes = 0;
876 
877         HasActiveDiagnostic = true;
878         HasFoldFailureDiagnostic = !IsCCEDiag;
879         EvalStatus.Diag->clear();
880         EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
881         addDiag(Loc, DiagId);
882         if (!checkingPotentialConstantExpression())
883           addCallStack(Limit);
884         return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
885       }
886       HasActiveDiagnostic = false;
887       return OptionalDiagnostic();
888     }
889   public:
890     // Diagnose that the evaluation could not be folded (FF => FoldFailure)
891     OptionalDiagnostic
892     FFDiag(SourceLocation Loc,
893           diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
894           unsigned ExtraNotes = 0) {
895       return Diag(Loc, DiagId, ExtraNotes, false);
896     }
897 
898     OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
899                               = diag::note_invalid_subexpr_in_const_expr,
900                             unsigned ExtraNotes = 0) {
901       if (EvalStatus.Diag)
902         return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
903       HasActiveDiagnostic = false;
904       return OptionalDiagnostic();
905     }
906 
907     /// Diagnose that the evaluation does not produce a C++11 core constant
908     /// expression.
909     ///
910     /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
911     /// EM_PotentialConstantExpression mode and we produce one of these.
912     OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
913                                  = diag::note_invalid_subexpr_in_const_expr,
914                                unsigned ExtraNotes = 0) {
915       // Don't override a previous diagnostic. Don't bother collecting
916       // diagnostics if we're evaluating for overflow.
917       if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
918         HasActiveDiagnostic = false;
919         return OptionalDiagnostic();
920       }
921       return Diag(Loc, DiagId, ExtraNotes, true);
922     }
923     OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
924                                  = diag::note_invalid_subexpr_in_const_expr,
925                                unsigned ExtraNotes = 0) {
926       return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
927     }
928     /// Add a note to a prior diagnostic.
929     OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
930       if (!HasActiveDiagnostic)
931         return OptionalDiagnostic();
932       return OptionalDiagnostic(&addDiag(Loc, DiagId));
933     }
934 
935     /// Add a stack of notes to a prior diagnostic.
936     void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
937       if (HasActiveDiagnostic) {
938         EvalStatus.Diag->insert(EvalStatus.Diag->end(),
939                                 Diags.begin(), Diags.end());
940       }
941     }
942 
943     /// Should we continue evaluation after encountering a side-effect that we
944     /// couldn't model?
945     bool keepEvaluatingAfterSideEffect() {
946       switch (EvalMode) {
947       case EM_PotentialConstantExpression:
948       case EM_PotentialConstantExpressionUnevaluated:
949       case EM_EvaluateForOverflow:
950       case EM_IgnoreSideEffects:
951         return true;
952 
953       case EM_ConstantExpression:
954       case EM_ConstantExpressionUnevaluated:
955       case EM_ConstantFold:
956         return false;
957       }
958       llvm_unreachable("Missed EvalMode case");
959     }
960 
961     /// Note that we have had a side-effect, and determine whether we should
962     /// keep evaluating.
963     bool noteSideEffect() {
964       EvalStatus.HasSideEffects = true;
965       return keepEvaluatingAfterSideEffect();
966     }
967 
968     /// Should we continue evaluation after encountering undefined behavior?
969     bool keepEvaluatingAfterUndefinedBehavior() {
970       switch (EvalMode) {
971       case EM_EvaluateForOverflow:
972       case EM_IgnoreSideEffects:
973       case EM_ConstantFold:
974         return true;
975 
976       case EM_PotentialConstantExpression:
977       case EM_PotentialConstantExpressionUnevaluated:
978       case EM_ConstantExpression:
979       case EM_ConstantExpressionUnevaluated:
980         return false;
981       }
982       llvm_unreachable("Missed EvalMode case");
983     }
984 
985     /// Note that we hit something that was technically undefined behavior, but
986     /// that we can evaluate past it (such as signed overflow or floating-point
987     /// division by zero.)
988     bool noteUndefinedBehavior() {
989       EvalStatus.HasUndefinedBehavior = true;
990       return keepEvaluatingAfterUndefinedBehavior();
991     }
992 
993     /// Should we continue evaluation as much as possible after encountering a
994     /// construct which can't be reduced to a value?
995     bool keepEvaluatingAfterFailure() {
996       if (!StepsLeft)
997         return false;
998 
999       switch (EvalMode) {
1000       case EM_PotentialConstantExpression:
1001       case EM_PotentialConstantExpressionUnevaluated:
1002       case EM_EvaluateForOverflow:
1003         return true;
1004 
1005       case EM_ConstantExpression:
1006       case EM_ConstantExpressionUnevaluated:
1007       case EM_ConstantFold:
1008       case EM_IgnoreSideEffects:
1009         return false;
1010       }
1011       llvm_unreachable("Missed EvalMode case");
1012     }
1013 
1014     /// Notes that we failed to evaluate an expression that other expressions
1015     /// directly depend on, and determine if we should keep evaluating. This
1016     /// should only be called if we actually intend to keep evaluating.
1017     ///
1018     /// Call noteSideEffect() instead if we may be able to ignore the value that
1019     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1020     ///
1021     /// (Foo(), 1)      // use noteSideEffect
1022     /// (Foo() || true) // use noteSideEffect
1023     /// Foo() + 1       // use noteFailure
1024     LLVM_NODISCARD bool noteFailure() {
1025       // Failure when evaluating some expression often means there is some
1026       // subexpression whose evaluation was skipped. Therefore, (because we
1027       // don't track whether we skipped an expression when unwinding after an
1028       // evaluation failure) every evaluation failure that bubbles up from a
1029       // subexpression implies that a side-effect has potentially happened. We
1030       // skip setting the HasSideEffects flag to true until we decide to
1031       // continue evaluating after that point, which happens here.
1032       bool KeepGoing = keepEvaluatingAfterFailure();
1033       EvalStatus.HasSideEffects |= KeepGoing;
1034       return KeepGoing;
1035     }
1036 
1037     class ArrayInitLoopIndex {
1038       EvalInfo &Info;
1039       uint64_t OuterIndex;
1040 
1041     public:
1042       ArrayInitLoopIndex(EvalInfo &Info)
1043           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1044         Info.ArrayInitIndex = 0;
1045       }
1046       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1047 
1048       operator uint64_t&() { return Info.ArrayInitIndex; }
1049     };
1050   };
1051 
1052   /// Object used to treat all foldable expressions as constant expressions.
1053   struct FoldConstant {
1054     EvalInfo &Info;
1055     bool Enabled;
1056     bool HadNoPriorDiags;
1057     EvalInfo::EvaluationMode OldMode;
1058 
1059     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1060       : Info(Info),
1061         Enabled(Enabled),
1062         HadNoPriorDiags(Info.EvalStatus.Diag &&
1063                         Info.EvalStatus.Diag->empty() &&
1064                         !Info.EvalStatus.HasSideEffects),
1065         OldMode(Info.EvalMode) {
1066       if (Enabled &&
1067           (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1068            Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
1069         Info.EvalMode = EvalInfo::EM_ConstantFold;
1070     }
1071     void keepDiagnostics() { Enabled = false; }
1072     ~FoldConstant() {
1073       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1074           !Info.EvalStatus.HasSideEffects)
1075         Info.EvalStatus.Diag->clear();
1076       Info.EvalMode = OldMode;
1077     }
1078   };
1079 
1080   /// RAII object used to set the current evaluation mode to ignore
1081   /// side-effects.
1082   struct IgnoreSideEffectsRAII {
1083     EvalInfo &Info;
1084     EvalInfo::EvaluationMode OldMode;
1085     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1086         : Info(Info), OldMode(Info.EvalMode) {
1087       if (!Info.checkingPotentialConstantExpression())
1088         Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1089     }
1090 
1091     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1092   };
1093 
1094   /// RAII object used to optionally suppress diagnostics and side-effects from
1095   /// a speculative evaluation.
1096   class SpeculativeEvaluationRAII {
1097     EvalInfo *Info = nullptr;
1098     Expr::EvalStatus OldStatus;
1099     bool OldIsSpeculativelyEvaluating;
1100 
1101     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1102       Info = Other.Info;
1103       OldStatus = Other.OldStatus;
1104       OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
1105       Other.Info = nullptr;
1106     }
1107 
1108     void maybeRestoreState() {
1109       if (!Info)
1110         return;
1111 
1112       Info->EvalStatus = OldStatus;
1113       Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
1114     }
1115 
1116   public:
1117     SpeculativeEvaluationRAII() = default;
1118 
1119     SpeculativeEvaluationRAII(
1120         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1121         : Info(&Info), OldStatus(Info.EvalStatus),
1122           OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
1123       Info.EvalStatus.Diag = NewDiag;
1124       Info.IsSpeculativelyEvaluating = true;
1125     }
1126 
1127     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1128     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1129       moveFromAndCancel(std::move(Other));
1130     }
1131 
1132     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1133       maybeRestoreState();
1134       moveFromAndCancel(std::move(Other));
1135       return *this;
1136     }
1137 
1138     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1139   };
1140 
1141   /// RAII object wrapping a full-expression or block scope, and handling
1142   /// the ending of the lifetime of temporaries created within it.
1143   template<bool IsFullExpression>
1144   class ScopeRAII {
1145     EvalInfo &Info;
1146     unsigned OldStackSize;
1147   public:
1148     ScopeRAII(EvalInfo &Info)
1149         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1150       // Push a new temporary version. This is needed to distinguish between
1151       // temporaries created in different iterations of a loop.
1152       Info.CurrentCall->pushTempVersion();
1153     }
1154     ~ScopeRAII() {
1155       // Body moved to a static method to encourage the compiler to inline away
1156       // instances of this class.
1157       cleanup(Info, OldStackSize);
1158       Info.CurrentCall->popTempVersion();
1159     }
1160   private:
1161     static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1162       unsigned NewEnd = OldStackSize;
1163       for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1164            I != N; ++I) {
1165         if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1166           // Full-expression cleanup of a lifetime-extended temporary: nothing
1167           // to do, just move this cleanup to the right place in the stack.
1168           std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1169           ++NewEnd;
1170         } else {
1171           // End the lifetime of the object.
1172           Info.CleanupStack[I].endLifetime();
1173         }
1174       }
1175       Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1176                               Info.CleanupStack.end());
1177     }
1178   };
1179   typedef ScopeRAII<false> BlockScopeRAII;
1180   typedef ScopeRAII<true> FullExpressionRAII;
1181 }
1182 
1183 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1184                                          CheckSubobjectKind CSK) {
1185   if (Invalid)
1186     return false;
1187   if (isOnePastTheEnd()) {
1188     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1189       << CSK;
1190     setInvalid();
1191     return false;
1192   }
1193   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1194   // must actually be at least one array element; even a VLA cannot have a
1195   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1196   return true;
1197 }
1198 
1199 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1200                                                                 const Expr *E) {
1201   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1202   // Do not set the designator as invalid: we can represent this situation,
1203   // and correct handling of __builtin_object_size requires us to do so.
1204 }
1205 
1206 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1207                                                     const Expr *E,
1208                                                     const APSInt &N) {
1209   // If we're complaining, we must be able to statically determine the size of
1210   // the most derived array.
1211   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1212     Info.CCEDiag(E, diag::note_constexpr_array_index)
1213       << N << /*array*/ 0
1214       << static_cast<unsigned>(getMostDerivedArraySize());
1215   else
1216     Info.CCEDiag(E, diag::note_constexpr_array_index)
1217       << N << /*non-array*/ 1;
1218   setInvalid();
1219 }
1220 
1221 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1222                                const FunctionDecl *Callee, const LValue *This,
1223                                APValue *Arguments)
1224     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1225       Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1226   Info.CurrentCall = this;
1227   ++Info.CallStackDepth;
1228 }
1229 
1230 CallStackFrame::~CallStackFrame() {
1231   assert(Info.CurrentCall == this && "calls retired out of order");
1232   --Info.CallStackDepth;
1233   Info.CurrentCall = Caller;
1234 }
1235 
1236 APValue &CallStackFrame::createTemporary(const void *Key,
1237                                          bool IsLifetimeExtended) {
1238   unsigned Version = Info.CurrentCall->getTempVersion();
1239   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1240   assert(Result.isUninit() && "temporary created multiple times");
1241   Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1242   return Result;
1243 }
1244 
1245 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
1246 
1247 void EvalInfo::addCallStack(unsigned Limit) {
1248   // Determine which calls to skip, if any.
1249   unsigned ActiveCalls = CallStackDepth - 1;
1250   unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1251   if (Limit && Limit < ActiveCalls) {
1252     SkipStart = Limit / 2 + Limit % 2;
1253     SkipEnd = ActiveCalls - Limit / 2;
1254   }
1255 
1256   // Walk the call stack and add the diagnostics.
1257   unsigned CallIdx = 0;
1258   for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1259        Frame = Frame->Caller, ++CallIdx) {
1260     // Skip this call?
1261     if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1262       if (CallIdx == SkipStart) {
1263         // Note that we're skipping calls.
1264         addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1265           << unsigned(ActiveCalls - Limit);
1266       }
1267       continue;
1268     }
1269 
1270     // Use a different note for an inheriting constructor, because from the
1271     // user's perspective it's not really a function at all.
1272     if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1273       if (CD->isInheritingConstructor()) {
1274         addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1275           << CD->getParent();
1276         continue;
1277       }
1278     }
1279 
1280     SmallVector<char, 128> Buffer;
1281     llvm::raw_svector_ostream Out(Buffer);
1282     describeCall(Frame, Out);
1283     addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1284   }
1285 }
1286 
1287 namespace {
1288   struct ComplexValue {
1289   private:
1290     bool IsInt;
1291 
1292   public:
1293     APSInt IntReal, IntImag;
1294     APFloat FloatReal, FloatImag;
1295 
1296     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1297 
1298     void makeComplexFloat() { IsInt = false; }
1299     bool isComplexFloat() const { return !IsInt; }
1300     APFloat &getComplexFloatReal() { return FloatReal; }
1301     APFloat &getComplexFloatImag() { return FloatImag; }
1302 
1303     void makeComplexInt() { IsInt = true; }
1304     bool isComplexInt() const { return IsInt; }
1305     APSInt &getComplexIntReal() { return IntReal; }
1306     APSInt &getComplexIntImag() { return IntImag; }
1307 
1308     void moveInto(APValue &v) const {
1309       if (isComplexFloat())
1310         v = APValue(FloatReal, FloatImag);
1311       else
1312         v = APValue(IntReal, IntImag);
1313     }
1314     void setFrom(const APValue &v) {
1315       assert(v.isComplexFloat() || v.isComplexInt());
1316       if (v.isComplexFloat()) {
1317         makeComplexFloat();
1318         FloatReal = v.getComplexFloatReal();
1319         FloatImag = v.getComplexFloatImag();
1320       } else {
1321         makeComplexInt();
1322         IntReal = v.getComplexIntReal();
1323         IntImag = v.getComplexIntImag();
1324       }
1325     }
1326   };
1327 
1328   struct LValue {
1329     APValue::LValueBase Base;
1330     CharUnits Offset;
1331     SubobjectDesignator Designator;
1332     bool IsNullPtr : 1;
1333     bool InvalidBase : 1;
1334 
1335     const APValue::LValueBase getLValueBase() const { return Base; }
1336     CharUnits &getLValueOffset() { return Offset; }
1337     const CharUnits &getLValueOffset() const { return Offset; }
1338     SubobjectDesignator &getLValueDesignator() { return Designator; }
1339     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1340     bool isNullPointer() const { return IsNullPtr;}
1341 
1342     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1343     unsigned getLValueVersion() const { return Base.getVersion(); }
1344 
1345     void moveInto(APValue &V) const {
1346       if (Designator.Invalid)
1347         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1348       else {
1349         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1350         V = APValue(Base, Offset, Designator.Entries,
1351                     Designator.IsOnePastTheEnd, IsNullPtr);
1352       }
1353     }
1354     void setFrom(ASTContext &Ctx, const APValue &V) {
1355       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1356       Base = V.getLValueBase();
1357       Offset = V.getLValueOffset();
1358       InvalidBase = false;
1359       Designator = SubobjectDesignator(Ctx, V);
1360       IsNullPtr = V.isNullPointer();
1361     }
1362 
1363     void set(APValue::LValueBase B, bool BInvalid = false) {
1364 #ifndef NDEBUG
1365       // We only allow a few types of invalid bases. Enforce that here.
1366       if (BInvalid) {
1367         const auto *E = B.get<const Expr *>();
1368         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1369                "Unexpected type of invalid base");
1370       }
1371 #endif
1372 
1373       Base = B;
1374       Offset = CharUnits::fromQuantity(0);
1375       InvalidBase = BInvalid;
1376       Designator = SubobjectDesignator(getType(B));
1377       IsNullPtr = false;
1378     }
1379 
1380     void setNull(QualType PointerTy, uint64_t TargetVal) {
1381       Base = (Expr *)nullptr;
1382       Offset = CharUnits::fromQuantity(TargetVal);
1383       InvalidBase = false;
1384       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1385       IsNullPtr = true;
1386     }
1387 
1388     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1389       set(B, true);
1390     }
1391 
1392     // Check that this LValue is not based on a null pointer. If it is, produce
1393     // a diagnostic and mark the designator as invalid.
1394     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1395                           CheckSubobjectKind CSK) {
1396       if (Designator.Invalid)
1397         return false;
1398       if (IsNullPtr) {
1399         Info.CCEDiag(E, diag::note_constexpr_null_subobject)
1400           << CSK;
1401         Designator.setInvalid();
1402         return false;
1403       }
1404       return true;
1405     }
1406 
1407     // Check this LValue refers to an object. If not, set the designator to be
1408     // invalid and emit a diagnostic.
1409     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1410       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1411              Designator.checkSubobject(Info, E, CSK);
1412     }
1413 
1414     void addDecl(EvalInfo &Info, const Expr *E,
1415                  const Decl *D, bool Virtual = false) {
1416       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1417         Designator.addDeclUnchecked(D, Virtual);
1418     }
1419     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1420       if (!Designator.Entries.empty()) {
1421         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1422         Designator.setInvalid();
1423         return;
1424       }
1425       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1426         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1427         Designator.FirstEntryIsAnUnsizedArray = true;
1428         Designator.addUnsizedArrayUnchecked(ElemTy);
1429       }
1430     }
1431     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1432       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1433         Designator.addArrayUnchecked(CAT);
1434     }
1435     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1436       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1437         Designator.addComplexUnchecked(EltTy, Imag);
1438     }
1439     void clearIsNullPointer() {
1440       IsNullPtr = false;
1441     }
1442     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1443                               const APSInt &Index, CharUnits ElementSize) {
1444       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1445       // but we're not required to diagnose it and it's valid in C++.)
1446       if (!Index)
1447         return;
1448 
1449       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1450       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1451       // offsets.
1452       uint64_t Offset64 = Offset.getQuantity();
1453       uint64_t ElemSize64 = ElementSize.getQuantity();
1454       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1455       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1456 
1457       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1458         Designator.adjustIndex(Info, E, Index);
1459       clearIsNullPointer();
1460     }
1461     void adjustOffset(CharUnits N) {
1462       Offset += N;
1463       if (N.getQuantity())
1464         clearIsNullPointer();
1465     }
1466   };
1467 
1468   struct MemberPtr {
1469     MemberPtr() {}
1470     explicit MemberPtr(const ValueDecl *Decl) :
1471       DeclAndIsDerivedMember(Decl, false), Path() {}
1472 
1473     /// The member or (direct or indirect) field referred to by this member
1474     /// pointer, or 0 if this is a null member pointer.
1475     const ValueDecl *getDecl() const {
1476       return DeclAndIsDerivedMember.getPointer();
1477     }
1478     /// Is this actually a member of some type derived from the relevant class?
1479     bool isDerivedMember() const {
1480       return DeclAndIsDerivedMember.getInt();
1481     }
1482     /// Get the class which the declaration actually lives in.
1483     const CXXRecordDecl *getContainingRecord() const {
1484       return cast<CXXRecordDecl>(
1485           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1486     }
1487 
1488     void moveInto(APValue &V) const {
1489       V = APValue(getDecl(), isDerivedMember(), Path);
1490     }
1491     void setFrom(const APValue &V) {
1492       assert(V.isMemberPointer());
1493       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1494       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1495       Path.clear();
1496       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1497       Path.insert(Path.end(), P.begin(), P.end());
1498     }
1499 
1500     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1501     /// whether the member is a member of some class derived from the class type
1502     /// of the member pointer.
1503     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1504     /// Path - The path of base/derived classes from the member declaration's
1505     /// class (exclusive) to the class type of the member pointer (inclusive).
1506     SmallVector<const CXXRecordDecl*, 4> Path;
1507 
1508     /// Perform a cast towards the class of the Decl (either up or down the
1509     /// hierarchy).
1510     bool castBack(const CXXRecordDecl *Class) {
1511       assert(!Path.empty());
1512       const CXXRecordDecl *Expected;
1513       if (Path.size() >= 2)
1514         Expected = Path[Path.size() - 2];
1515       else
1516         Expected = getContainingRecord();
1517       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1518         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1519         // if B does not contain the original member and is not a base or
1520         // derived class of the class containing the original member, the result
1521         // of the cast is undefined.
1522         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1523         // (D::*). We consider that to be a language defect.
1524         return false;
1525       }
1526       Path.pop_back();
1527       return true;
1528     }
1529     /// Perform a base-to-derived member pointer cast.
1530     bool castToDerived(const CXXRecordDecl *Derived) {
1531       if (!getDecl())
1532         return true;
1533       if (!isDerivedMember()) {
1534         Path.push_back(Derived);
1535         return true;
1536       }
1537       if (!castBack(Derived))
1538         return false;
1539       if (Path.empty())
1540         DeclAndIsDerivedMember.setInt(false);
1541       return true;
1542     }
1543     /// Perform a derived-to-base member pointer cast.
1544     bool castToBase(const CXXRecordDecl *Base) {
1545       if (!getDecl())
1546         return true;
1547       if (Path.empty())
1548         DeclAndIsDerivedMember.setInt(true);
1549       if (isDerivedMember()) {
1550         Path.push_back(Base);
1551         return true;
1552       }
1553       return castBack(Base);
1554     }
1555   };
1556 
1557   /// Compare two member pointers, which are assumed to be of the same type.
1558   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1559     if (!LHS.getDecl() || !RHS.getDecl())
1560       return !LHS.getDecl() && !RHS.getDecl();
1561     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1562       return false;
1563     return LHS.Path == RHS.Path;
1564   }
1565 }
1566 
1567 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1568 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1569                             const LValue &This, const Expr *E,
1570                             bool AllowNonLiteralTypes = false);
1571 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1572                            bool InvalidBaseOK = false);
1573 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1574                             bool InvalidBaseOK = false);
1575 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1576                                   EvalInfo &Info);
1577 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1578 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1579 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1580                                     EvalInfo &Info);
1581 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1582 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1583 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1584                            EvalInfo &Info);
1585 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1586 
1587 //===----------------------------------------------------------------------===//
1588 // Misc utilities
1589 //===----------------------------------------------------------------------===//
1590 
1591 /// A helper function to create a temporary and set an LValue.
1592 template <class KeyTy>
1593 static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1594                                 LValue &LV, CallStackFrame &Frame) {
1595   LV.set({Key, Frame.Info.CurrentCall->Index,
1596           Frame.Info.CurrentCall->getTempVersion()});
1597   return Frame.createTemporary(Key, IsLifetimeExtended);
1598 }
1599 
1600 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1601 /// preserving its value (by extending by up to one bit as needed).
1602 static void negateAsSigned(APSInt &Int) {
1603   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1604     Int = Int.extend(Int.getBitWidth() + 1);
1605     Int.setIsSigned(true);
1606   }
1607   Int = -Int;
1608 }
1609 
1610 /// Produce a string describing the given constexpr call.
1611 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1612   unsigned ArgIndex = 0;
1613   bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1614                       !isa<CXXConstructorDecl>(Frame->Callee) &&
1615                       cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1616 
1617   if (!IsMemberCall)
1618     Out << *Frame->Callee << '(';
1619 
1620   if (Frame->This && IsMemberCall) {
1621     APValue Val;
1622     Frame->This->moveInto(Val);
1623     Val.printPretty(Out, Frame->Info.Ctx,
1624                     Frame->This->Designator.MostDerivedType);
1625     // FIXME: Add parens around Val if needed.
1626     Out << "->" << *Frame->Callee << '(';
1627     IsMemberCall = false;
1628   }
1629 
1630   for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1631        E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1632     if (ArgIndex > (unsigned)IsMemberCall)
1633       Out << ", ";
1634 
1635     const ParmVarDecl *Param = *I;
1636     const APValue &Arg = Frame->Arguments[ArgIndex];
1637     Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1638 
1639     if (ArgIndex == 0 && IsMemberCall)
1640       Out << "->" << *Frame->Callee << '(';
1641   }
1642 
1643   Out << ')';
1644 }
1645 
1646 /// Evaluate an expression to see if it had side-effects, and discard its
1647 /// result.
1648 /// \return \c true if the caller should keep evaluating.
1649 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1650   APValue Scratch;
1651   if (!Evaluate(Scratch, Info, E))
1652     // We don't need the value, but we might have skipped a side effect here.
1653     return Info.noteSideEffect();
1654   return true;
1655 }
1656 
1657 /// Should this call expression be treated as a string literal?
1658 static bool IsStringLiteralCall(const CallExpr *E) {
1659   unsigned Builtin = E->getBuiltinCallee();
1660   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1661           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1662 }
1663 
1664 static bool IsGlobalLValue(APValue::LValueBase B) {
1665   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1666   // constant expression of pointer type that evaluates to...
1667 
1668   // ... a null pointer value, or a prvalue core constant expression of type
1669   // std::nullptr_t.
1670   if (!B) return true;
1671 
1672   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1673     // ... the address of an object with static storage duration,
1674     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1675       return VD->hasGlobalStorage();
1676     // ... the address of a function,
1677     return isa<FunctionDecl>(D);
1678   }
1679 
1680   const Expr *E = B.get<const Expr*>();
1681   switch (E->getStmtClass()) {
1682   default:
1683     return false;
1684   case Expr::CompoundLiteralExprClass: {
1685     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1686     return CLE->isFileScope() && CLE->isLValue();
1687   }
1688   case Expr::MaterializeTemporaryExprClass:
1689     // A materialized temporary might have been lifetime-extended to static
1690     // storage duration.
1691     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1692   // A string literal has static storage duration.
1693   case Expr::StringLiteralClass:
1694   case Expr::PredefinedExprClass:
1695   case Expr::ObjCStringLiteralClass:
1696   case Expr::ObjCEncodeExprClass:
1697   case Expr::CXXTypeidExprClass:
1698   case Expr::CXXUuidofExprClass:
1699     return true;
1700   case Expr::CallExprClass:
1701     return IsStringLiteralCall(cast<CallExpr>(E));
1702   // For GCC compatibility, &&label has static storage duration.
1703   case Expr::AddrLabelExprClass:
1704     return true;
1705   // A Block literal expression may be used as the initialization value for
1706   // Block variables at global or local static scope.
1707   case Expr::BlockExprClass:
1708     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1709   case Expr::ImplicitValueInitExprClass:
1710     // FIXME:
1711     // We can never form an lvalue with an implicit value initialization as its
1712     // base through expression evaluation, so these only appear in one case: the
1713     // implicit variable declaration we invent when checking whether a constexpr
1714     // constructor can produce a constant expression. We must assume that such
1715     // an expression might be a global lvalue.
1716     return true;
1717   }
1718 }
1719 
1720 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1721   return LVal.Base.dyn_cast<const ValueDecl*>();
1722 }
1723 
1724 static bool IsLiteralLValue(const LValue &Value) {
1725   if (Value.getLValueCallIndex())
1726     return false;
1727   const Expr *E = Value.Base.dyn_cast<const Expr*>();
1728   return E && !isa<MaterializeTemporaryExpr>(E);
1729 }
1730 
1731 static bool IsWeakLValue(const LValue &Value) {
1732   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1733   return Decl && Decl->isWeak();
1734 }
1735 
1736 static bool isZeroSized(const LValue &Value) {
1737   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1738   if (Decl && isa<VarDecl>(Decl)) {
1739     QualType Ty = Decl->getType();
1740     if (Ty->isArrayType())
1741       return Ty->isIncompleteType() ||
1742              Decl->getASTContext().getTypeSize(Ty) == 0;
1743   }
1744   return false;
1745 }
1746 
1747 static bool HasSameBase(const LValue &A, const LValue &B) {
1748   if (!A.getLValueBase())
1749     return !B.getLValueBase();
1750   if (!B.getLValueBase())
1751     return false;
1752 
1753   if (A.getLValueBase().getOpaqueValue() !=
1754       B.getLValueBase().getOpaqueValue()) {
1755     const Decl *ADecl = GetLValueBaseDecl(A);
1756     if (!ADecl)
1757       return false;
1758     const Decl *BDecl = GetLValueBaseDecl(B);
1759     if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1760       return false;
1761   }
1762 
1763   return IsGlobalLValue(A.getLValueBase()) ||
1764          (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1765           A.getLValueVersion() == B.getLValueVersion());
1766 }
1767 
1768 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1769   assert(Base && "no location for a null lvalue");
1770   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1771   if (VD)
1772     Info.Note(VD->getLocation(), diag::note_declared_at);
1773   else
1774     Info.Note(Base.get<const Expr*>()->getExprLoc(),
1775               diag::note_constexpr_temporary_here);
1776 }
1777 
1778 /// Check that this reference or pointer core constant expression is a valid
1779 /// value for an address or reference constant expression. Return true if we
1780 /// can fold this expression, whether or not it's a constant expression.
1781 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1782                                           QualType Type, const LValue &LVal,
1783                                           Expr::ConstExprUsage Usage) {
1784   bool IsReferenceType = Type->isReferenceType();
1785 
1786   APValue::LValueBase Base = LVal.getLValueBase();
1787   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1788 
1789   // Check that the object is a global. Note that the fake 'this' object we
1790   // manufacture when checking potential constant expressions is conservatively
1791   // assumed to be global here.
1792   if (!IsGlobalLValue(Base)) {
1793     if (Info.getLangOpts().CPlusPlus11) {
1794       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1795       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
1796         << IsReferenceType << !Designator.Entries.empty()
1797         << !!VD << VD;
1798       NoteLValueLocation(Info, Base);
1799     } else {
1800       Info.FFDiag(Loc);
1801     }
1802     // Don't allow references to temporaries to escape.
1803     return false;
1804   }
1805   assert((Info.checkingPotentialConstantExpression() ||
1806           LVal.getLValueCallIndex() == 0) &&
1807          "have call index for global lvalue");
1808 
1809   if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1810     if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1811       // Check if this is a thread-local variable.
1812       if (Var->getTLSKind())
1813         return false;
1814 
1815       // A dllimport variable never acts like a constant.
1816       if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
1817         return false;
1818     }
1819     if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1820       // __declspec(dllimport) must be handled very carefully:
1821       // We must never initialize an expression with the thunk in C++.
1822       // Doing otherwise would allow the same id-expression to yield
1823       // different addresses for the same function in different translation
1824       // units.  However, this means that we must dynamically initialize the
1825       // expression with the contents of the import address table at runtime.
1826       //
1827       // The C language has no notion of ODR; furthermore, it has no notion of
1828       // dynamic initialization.  This means that we are permitted to
1829       // perform initialization with the address of the thunk.
1830       if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1831           FD->hasAttr<DLLImportAttr>())
1832         return false;
1833     }
1834   }
1835 
1836   // Allow address constant expressions to be past-the-end pointers. This is
1837   // an extension: the standard requires them to point to an object.
1838   if (!IsReferenceType)
1839     return true;
1840 
1841   // A reference constant expression must refer to an object.
1842   if (!Base) {
1843     // FIXME: diagnostic
1844     Info.CCEDiag(Loc);
1845     return true;
1846   }
1847 
1848   // Does this refer one past the end of some object?
1849   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1850     const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1851     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
1852       << !Designator.Entries.empty() << !!VD << VD;
1853     NoteLValueLocation(Info, Base);
1854   }
1855 
1856   return true;
1857 }
1858 
1859 /// Member pointers are constant expressions unless they point to a
1860 /// non-virtual dllimport member function.
1861 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1862                                                  SourceLocation Loc,
1863                                                  QualType Type,
1864                                                  const APValue &Value,
1865                                                  Expr::ConstExprUsage Usage) {
1866   const ValueDecl *Member = Value.getMemberPointerDecl();
1867   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1868   if (!FD)
1869     return true;
1870   return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
1871          !FD->hasAttr<DLLImportAttr>();
1872 }
1873 
1874 /// Check that this core constant expression is of literal type, and if not,
1875 /// produce an appropriate diagnostic.
1876 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1877                              const LValue *This = nullptr) {
1878   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1879     return true;
1880 
1881   // C++1y: A constant initializer for an object o [...] may also invoke
1882   // constexpr constructors for o and its subobjects even if those objects
1883   // are of non-literal class types.
1884   //
1885   // C++11 missed this detail for aggregates, so classes like this:
1886   //   struct foo_t { union { int i; volatile int j; } u; };
1887   // are not (obviously) initializable like so:
1888   //   __attribute__((__require_constant_initialization__))
1889   //   static const foo_t x = {{0}};
1890   // because "i" is a subobject with non-literal initialization (due to the
1891   // volatile member of the union). See:
1892   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1893   // Therefore, we use the C++1y behavior.
1894   if (This && Info.EvaluatingDecl == This->getLValueBase())
1895     return true;
1896 
1897   // Prvalue constant expressions must be of literal types.
1898   if (Info.getLangOpts().CPlusPlus11)
1899     Info.FFDiag(E, diag::note_constexpr_nonliteral)
1900       << E->getType();
1901   else
1902     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1903   return false;
1904 }
1905 
1906 /// Check that this core constant expression value is a valid value for a
1907 /// constant expression. If not, report an appropriate diagnostic. Does not
1908 /// check that the expression is of literal type.
1909 static bool
1910 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
1911                         const APValue &Value,
1912                         Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
1913   if (Value.isUninit()) {
1914     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
1915       << true << Type;
1916     return false;
1917   }
1918 
1919   // We allow _Atomic(T) to be initialized from anything that T can be
1920   // initialized from.
1921   if (const AtomicType *AT = Type->getAs<AtomicType>())
1922     Type = AT->getValueType();
1923 
1924   // Core issue 1454: For a literal constant expression of array or class type,
1925   // each subobject of its value shall have been initialized by a constant
1926   // expression.
1927   if (Value.isArray()) {
1928     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1929     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1930       if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1931                                    Value.getArrayInitializedElt(I), Usage))
1932         return false;
1933     }
1934     if (!Value.hasArrayFiller())
1935       return true;
1936     return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
1937                                    Usage);
1938   }
1939   if (Value.isUnion() && Value.getUnionField()) {
1940     return CheckConstantExpression(Info, DiagLoc,
1941                                    Value.getUnionField()->getType(),
1942                                    Value.getUnionValue(), Usage);
1943   }
1944   if (Value.isStruct()) {
1945     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1946     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1947       unsigned BaseIndex = 0;
1948       for (const CXXBaseSpecifier &BS : CD->bases()) {
1949         if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
1950                                      Value.getStructBase(BaseIndex), Usage))
1951           return false;
1952         ++BaseIndex;
1953       }
1954     }
1955     for (const auto *I : RD->fields()) {
1956       if (I->isUnnamedBitfield())
1957         continue;
1958 
1959       if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1960                                    Value.getStructField(I->getFieldIndex()),
1961                                    Usage))
1962         return false;
1963     }
1964   }
1965 
1966   if (Value.isLValue()) {
1967     LValue LVal;
1968     LVal.setFrom(Info.Ctx, Value);
1969     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
1970   }
1971 
1972   if (Value.isMemberPointer())
1973     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
1974 
1975   // Everything else is fine.
1976   return true;
1977 }
1978 
1979 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1980   // A null base expression indicates a null pointer.  These are always
1981   // evaluatable, and they are false unless the offset is zero.
1982   if (!Value.getLValueBase()) {
1983     Result = !Value.getLValueOffset().isZero();
1984     return true;
1985   }
1986 
1987   // We have a non-null base.  These are generally known to be true, but if it's
1988   // a weak declaration it can be null at runtime.
1989   Result = true;
1990   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1991   return !Decl || !Decl->isWeak();
1992 }
1993 
1994 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1995   switch (Val.getKind()) {
1996   case APValue::Uninitialized:
1997     return false;
1998   case APValue::Int:
1999     Result = Val.getInt().getBoolValue();
2000     return true;
2001   case APValue::Float:
2002     Result = !Val.getFloat().isZero();
2003     return true;
2004   case APValue::ComplexInt:
2005     Result = Val.getComplexIntReal().getBoolValue() ||
2006              Val.getComplexIntImag().getBoolValue();
2007     return true;
2008   case APValue::ComplexFloat:
2009     Result = !Val.getComplexFloatReal().isZero() ||
2010              !Val.getComplexFloatImag().isZero();
2011     return true;
2012   case APValue::LValue:
2013     return EvalPointerValueAsBool(Val, Result);
2014   case APValue::MemberPointer:
2015     Result = Val.getMemberPointerDecl();
2016     return true;
2017   case APValue::Vector:
2018   case APValue::Array:
2019   case APValue::Struct:
2020   case APValue::Union:
2021   case APValue::AddrLabelDiff:
2022     return false;
2023   }
2024 
2025   llvm_unreachable("unknown APValue kind");
2026 }
2027 
2028 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2029                                        EvalInfo &Info) {
2030   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2031   APValue Val;
2032   if (!Evaluate(Val, Info, E))
2033     return false;
2034   return HandleConversionToBool(Val, Result);
2035 }
2036 
2037 template<typename T>
2038 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2039                            const T &SrcValue, QualType DestType) {
2040   Info.CCEDiag(E, diag::note_constexpr_overflow)
2041     << SrcValue << DestType;
2042   return Info.noteUndefinedBehavior();
2043 }
2044 
2045 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2046                                  QualType SrcType, const APFloat &Value,
2047                                  QualType DestType, APSInt &Result) {
2048   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2049   // Determine whether we are converting to unsigned or signed.
2050   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2051 
2052   Result = APSInt(DestWidth, !DestSigned);
2053   bool ignored;
2054   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2055       & APFloat::opInvalidOp)
2056     return HandleOverflow(Info, E, Value, DestType);
2057   return true;
2058 }
2059 
2060 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2061                                    QualType SrcType, QualType DestType,
2062                                    APFloat &Result) {
2063   APFloat Value = Result;
2064   bool ignored;
2065   if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2066                      APFloat::rmNearestTiesToEven, &ignored)
2067       & APFloat::opOverflow)
2068     return HandleOverflow(Info, E, Value, DestType);
2069   return true;
2070 }
2071 
2072 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2073                                  QualType DestType, QualType SrcType,
2074                                  const APSInt &Value) {
2075   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2076   APSInt Result = Value;
2077   // Figure out if this is a truncate, extend or noop cast.
2078   // If the input is signed, do a sign extend, noop, or truncate.
2079   Result = Result.extOrTrunc(DestWidth);
2080   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2081   return Result;
2082 }
2083 
2084 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2085                                  QualType SrcType, const APSInt &Value,
2086                                  QualType DestType, APFloat &Result) {
2087   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2088   if (Result.convertFromAPInt(Value, Value.isSigned(),
2089                               APFloat::rmNearestTiesToEven)
2090       & APFloat::opOverflow)
2091     return HandleOverflow(Info, E, Value, DestType);
2092   return true;
2093 }
2094 
2095 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2096                                   APValue &Value, const FieldDecl *FD) {
2097   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2098 
2099   if (!Value.isInt()) {
2100     // Trying to store a pointer-cast-to-integer into a bitfield.
2101     // FIXME: In this case, we should provide the diagnostic for casting
2102     // a pointer to an integer.
2103     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2104     Info.FFDiag(E);
2105     return false;
2106   }
2107 
2108   APSInt &Int = Value.getInt();
2109   unsigned OldBitWidth = Int.getBitWidth();
2110   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2111   if (NewBitWidth < OldBitWidth)
2112     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2113   return true;
2114 }
2115 
2116 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2117                                   llvm::APInt &Res) {
2118   APValue SVal;
2119   if (!Evaluate(SVal, Info, E))
2120     return false;
2121   if (SVal.isInt()) {
2122     Res = SVal.getInt();
2123     return true;
2124   }
2125   if (SVal.isFloat()) {
2126     Res = SVal.getFloat().bitcastToAPInt();
2127     return true;
2128   }
2129   if (SVal.isVector()) {
2130     QualType VecTy = E->getType();
2131     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2132     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2133     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2134     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2135     Res = llvm::APInt::getNullValue(VecSize);
2136     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2137       APValue &Elt = SVal.getVectorElt(i);
2138       llvm::APInt EltAsInt;
2139       if (Elt.isInt()) {
2140         EltAsInt = Elt.getInt();
2141       } else if (Elt.isFloat()) {
2142         EltAsInt = Elt.getFloat().bitcastToAPInt();
2143       } else {
2144         // Don't try to handle vectors of anything other than int or float
2145         // (not sure if it's possible to hit this case).
2146         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2147         return false;
2148       }
2149       unsigned BaseEltSize = EltAsInt.getBitWidth();
2150       if (BigEndian)
2151         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2152       else
2153         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2154     }
2155     return true;
2156   }
2157   // Give up if the input isn't an int, float, or vector.  For example, we
2158   // reject "(v4i16)(intptr_t)&a".
2159   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2160   return false;
2161 }
2162 
2163 /// Perform the given integer operation, which is known to need at most BitWidth
2164 /// bits, and check for overflow in the original type (if that type was not an
2165 /// unsigned type).
2166 template<typename Operation>
2167 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2168                                  const APSInt &LHS, const APSInt &RHS,
2169                                  unsigned BitWidth, Operation Op,
2170                                  APSInt &Result) {
2171   if (LHS.isUnsigned()) {
2172     Result = Op(LHS, RHS);
2173     return true;
2174   }
2175 
2176   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2177   Result = Value.trunc(LHS.getBitWidth());
2178   if (Result.extend(BitWidth) != Value) {
2179     if (Info.checkingForOverflow())
2180       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2181                                        diag::warn_integer_constant_overflow)
2182           << Result.toString(10) << E->getType();
2183     else
2184       return HandleOverflow(Info, E, Value, E->getType());
2185   }
2186   return true;
2187 }
2188 
2189 /// Perform the given binary integer operation.
2190 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2191                               BinaryOperatorKind Opcode, APSInt RHS,
2192                               APSInt &Result) {
2193   switch (Opcode) {
2194   default:
2195     Info.FFDiag(E);
2196     return false;
2197   case BO_Mul:
2198     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2199                                 std::multiplies<APSInt>(), Result);
2200   case BO_Add:
2201     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2202                                 std::plus<APSInt>(), Result);
2203   case BO_Sub:
2204     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2205                                 std::minus<APSInt>(), Result);
2206   case BO_And: Result = LHS & RHS; return true;
2207   case BO_Xor: Result = LHS ^ RHS; return true;
2208   case BO_Or:  Result = LHS | RHS; return true;
2209   case BO_Div:
2210   case BO_Rem:
2211     if (RHS == 0) {
2212       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2213       return false;
2214     }
2215     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2216     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2217     // this operation and gives the two's complement result.
2218     if (RHS.isNegative() && RHS.isAllOnesValue() &&
2219         LHS.isSigned() && LHS.isMinSignedValue())
2220       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2221                             E->getType());
2222     return true;
2223   case BO_Shl: {
2224     if (Info.getLangOpts().OpenCL)
2225       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2226       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2227                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2228                     RHS.isUnsigned());
2229     else if (RHS.isSigned() && RHS.isNegative()) {
2230       // During constant-folding, a negative shift is an opposite shift. Such
2231       // a shift is not a constant expression.
2232       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2233       RHS = -RHS;
2234       goto shift_right;
2235     }
2236   shift_left:
2237     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2238     // the shifted type.
2239     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2240     if (SA != RHS) {
2241       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2242         << RHS << E->getType() << LHS.getBitWidth();
2243     } else if (LHS.isSigned()) {
2244       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2245       // operand, and must not overflow the corresponding unsigned type.
2246       if (LHS.isNegative())
2247         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2248       else if (LHS.countLeadingZeros() < SA)
2249         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2250     }
2251     Result = LHS << SA;
2252     return true;
2253   }
2254   case BO_Shr: {
2255     if (Info.getLangOpts().OpenCL)
2256       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2257       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2258                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2259                     RHS.isUnsigned());
2260     else if (RHS.isSigned() && RHS.isNegative()) {
2261       // During constant-folding, a negative shift is an opposite shift. Such a
2262       // shift is not a constant expression.
2263       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2264       RHS = -RHS;
2265       goto shift_left;
2266     }
2267   shift_right:
2268     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2269     // shifted type.
2270     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2271     if (SA != RHS)
2272       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2273         << RHS << E->getType() << LHS.getBitWidth();
2274     Result = LHS >> SA;
2275     return true;
2276   }
2277 
2278   case BO_LT: Result = LHS < RHS; return true;
2279   case BO_GT: Result = LHS > RHS; return true;
2280   case BO_LE: Result = LHS <= RHS; return true;
2281   case BO_GE: Result = LHS >= RHS; return true;
2282   case BO_EQ: Result = LHS == RHS; return true;
2283   case BO_NE: Result = LHS != RHS; return true;
2284   case BO_Cmp:
2285     llvm_unreachable("BO_Cmp should be handled elsewhere");
2286   }
2287 }
2288 
2289 /// Perform the given binary floating-point operation, in-place, on LHS.
2290 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2291                                   APFloat &LHS, BinaryOperatorKind Opcode,
2292                                   const APFloat &RHS) {
2293   switch (Opcode) {
2294   default:
2295     Info.FFDiag(E);
2296     return false;
2297   case BO_Mul:
2298     LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2299     break;
2300   case BO_Add:
2301     LHS.add(RHS, APFloat::rmNearestTiesToEven);
2302     break;
2303   case BO_Sub:
2304     LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2305     break;
2306   case BO_Div:
2307     LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2308     break;
2309   }
2310 
2311   if (LHS.isInfinity() || 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 /// Update LVal to refer to the given field, which must be a member of the type
2402 /// currently described by LVal.
2403 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2404                                const FieldDecl *FD,
2405                                const ASTRecordLayout *RL = nullptr) {
2406   if (!RL) {
2407     if (FD->getParent()->isInvalidDecl()) return false;
2408     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2409   }
2410 
2411   unsigned I = FD->getFieldIndex();
2412   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2413   LVal.addDecl(Info, E, FD);
2414   return true;
2415 }
2416 
2417 /// Update LVal to refer to the given indirect field.
2418 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2419                                        LValue &LVal,
2420                                        const IndirectFieldDecl *IFD) {
2421   for (const auto *C : IFD->chain())
2422     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2423       return false;
2424   return true;
2425 }
2426 
2427 /// Get the size of the given type in char units.
2428 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2429                          QualType Type, CharUnits &Size) {
2430   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2431   // extension.
2432   if (Type->isVoidType() || Type->isFunctionType()) {
2433     Size = CharUnits::One();
2434     return true;
2435   }
2436 
2437   if (Type->isDependentType()) {
2438     Info.FFDiag(Loc);
2439     return false;
2440   }
2441 
2442   if (!Type->isConstantSizeType()) {
2443     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2444     // FIXME: Better diagnostic.
2445     Info.FFDiag(Loc);
2446     return false;
2447   }
2448 
2449   Size = Info.Ctx.getTypeSizeInChars(Type);
2450   return true;
2451 }
2452 
2453 /// Update a pointer value to model pointer arithmetic.
2454 /// \param Info - Information about the ongoing evaluation.
2455 /// \param E - The expression being evaluated, for diagnostic purposes.
2456 /// \param LVal - The pointer value to be updated.
2457 /// \param EltTy - The pointee type represented by LVal.
2458 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2459 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2460                                         LValue &LVal, QualType EltTy,
2461                                         APSInt Adjustment) {
2462   CharUnits SizeOfPointee;
2463   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2464     return false;
2465 
2466   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2467   return true;
2468 }
2469 
2470 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2471                                         LValue &LVal, QualType EltTy,
2472                                         int64_t Adjustment) {
2473   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2474                                      APSInt::get(Adjustment));
2475 }
2476 
2477 /// Update an lvalue to refer to a component of a complex number.
2478 /// \param Info - Information about the ongoing evaluation.
2479 /// \param LVal - The lvalue to be updated.
2480 /// \param EltTy - The complex number's component type.
2481 /// \param Imag - False for the real component, true for the imaginary.
2482 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2483                                        LValue &LVal, QualType EltTy,
2484                                        bool Imag) {
2485   if (Imag) {
2486     CharUnits SizeOfComponent;
2487     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2488       return false;
2489     LVal.Offset += SizeOfComponent;
2490   }
2491   LVal.addComplex(Info, E, EltTy, Imag);
2492   return true;
2493 }
2494 
2495 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2496                                            QualType Type, const LValue &LVal,
2497                                            APValue &RVal);
2498 
2499 /// Try to evaluate the initializer for a variable declaration.
2500 ///
2501 /// \param Info   Information about the ongoing evaluation.
2502 /// \param E      An expression to be used when printing diagnostics.
2503 /// \param VD     The variable whose initializer should be obtained.
2504 /// \param Frame  The frame in which the variable was created. Must be null
2505 ///               if this variable is not local to the evaluation.
2506 /// \param Result Filled in with a pointer to the value of the variable.
2507 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2508                                 const VarDecl *VD, CallStackFrame *Frame,
2509                                 APValue *&Result, const LValue *LVal) {
2510 
2511   // If this is a parameter to an active constexpr function call, perform
2512   // argument substitution.
2513   if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2514     // Assume arguments of a potential constant expression are unknown
2515     // constant expressions.
2516     if (Info.checkingPotentialConstantExpression())
2517       return false;
2518     if (!Frame || !Frame->Arguments) {
2519       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2520       return false;
2521     }
2522     Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2523     return true;
2524   }
2525 
2526   // If this is a local variable, dig out its value.
2527   if (Frame) {
2528     Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2529                   : Frame->getCurrentTemporary(VD);
2530     if (!Result) {
2531       // Assume variables referenced within a lambda's call operator that were
2532       // not declared within the call operator are captures and during checking
2533       // of a potential constant expression, assume they are unknown constant
2534       // expressions.
2535       assert(isLambdaCallOperator(Frame->Callee) &&
2536              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2537              "missing value for local variable");
2538       if (Info.checkingPotentialConstantExpression())
2539         return false;
2540       // FIXME: implement capture evaluation during constant expr evaluation.
2541       Info.FFDiag(E->getBeginLoc(),
2542                   diag::note_unimplemented_constexpr_lambda_feature_ast)
2543           << "captures not currently allowed";
2544       return false;
2545     }
2546     return true;
2547   }
2548 
2549   // Dig out the initializer, and use the declaration which it's attached to.
2550   const Expr *Init = VD->getAnyInitializer(VD);
2551   if (!Init || Init->isValueDependent()) {
2552     // If we're checking a potential constant expression, the variable could be
2553     // initialized later.
2554     if (!Info.checkingPotentialConstantExpression())
2555       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2556     return false;
2557   }
2558 
2559   // If we're currently evaluating the initializer of this declaration, use that
2560   // in-flight value.
2561   if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2562     Result = Info.EvaluatingDeclValue;
2563     return true;
2564   }
2565 
2566   // Never evaluate the initializer of a weak variable. We can't be sure that
2567   // this is the definition which will be used.
2568   if (VD->isWeak()) {
2569     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2570     return false;
2571   }
2572 
2573   // Check that we can fold the initializer. In C++, we will have already done
2574   // this in the cases where it matters for conformance.
2575   SmallVector<PartialDiagnosticAt, 8> Notes;
2576   if (!VD->evaluateValue(Notes)) {
2577     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2578               Notes.size() + 1) << VD;
2579     Info.Note(VD->getLocation(), diag::note_declared_at);
2580     Info.addNotes(Notes);
2581     return false;
2582   } else if (!VD->checkInitIsICE()) {
2583     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2584                  Notes.size() + 1) << VD;
2585     Info.Note(VD->getLocation(), diag::note_declared_at);
2586     Info.addNotes(Notes);
2587   }
2588 
2589   Result = VD->getEvaluatedValue();
2590   return true;
2591 }
2592 
2593 static bool IsConstNonVolatile(QualType T) {
2594   Qualifiers Quals = T.getQualifiers();
2595   return Quals.hasConst() && !Quals.hasVolatile();
2596 }
2597 
2598 /// Get the base index of the given base class within an APValue representing
2599 /// the given derived class.
2600 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2601                              const CXXRecordDecl *Base) {
2602   Base = Base->getCanonicalDecl();
2603   unsigned Index = 0;
2604   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2605          E = Derived->bases_end(); I != E; ++I, ++Index) {
2606     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2607       return Index;
2608   }
2609 
2610   llvm_unreachable("base class missing from derived class's bases list");
2611 }
2612 
2613 /// Extract the value of a character from a string literal.
2614 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2615                                             uint64_t Index) {
2616   // FIXME: Support MakeStringConstant
2617   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2618     std::string Str;
2619     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2620     assert(Index <= Str.size() && "Index too large");
2621     return APSInt::getUnsigned(Str.c_str()[Index]);
2622   }
2623 
2624   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2625     Lit = PE->getFunctionName();
2626   const StringLiteral *S = cast<StringLiteral>(Lit);
2627   const ConstantArrayType *CAT =
2628       Info.Ctx.getAsConstantArrayType(S->getType());
2629   assert(CAT && "string literal isn't an array");
2630   QualType CharType = CAT->getElementType();
2631   assert(CharType->isIntegerType() && "unexpected character type");
2632 
2633   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2634                CharType->isUnsignedIntegerType());
2635   if (Index < S->getLength())
2636     Value = S->getCodeUnit(Index);
2637   return Value;
2638 }
2639 
2640 // Expand a string literal into an array of characters.
2641 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2642                                 APValue &Result) {
2643   const StringLiteral *S = cast<StringLiteral>(Lit);
2644   const ConstantArrayType *CAT =
2645       Info.Ctx.getAsConstantArrayType(S->getType());
2646   assert(CAT && "string literal isn't an array");
2647   QualType CharType = CAT->getElementType();
2648   assert(CharType->isIntegerType() && "unexpected character type");
2649 
2650   unsigned Elts = CAT->getSize().getZExtValue();
2651   Result = APValue(APValue::UninitArray(),
2652                    std::min(S->getLength(), Elts), Elts);
2653   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2654                CharType->isUnsignedIntegerType());
2655   if (Result.hasArrayFiller())
2656     Result.getArrayFiller() = APValue(Value);
2657   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2658     Value = S->getCodeUnit(I);
2659     Result.getArrayInitializedElt(I) = APValue(Value);
2660   }
2661 }
2662 
2663 // Expand an array so that it has more than Index filled elements.
2664 static void expandArray(APValue &Array, unsigned Index) {
2665   unsigned Size = Array.getArraySize();
2666   assert(Index < Size);
2667 
2668   // Always at least double the number of elements for which we store a value.
2669   unsigned OldElts = Array.getArrayInitializedElts();
2670   unsigned NewElts = std::max(Index+1, OldElts * 2);
2671   NewElts = std::min(Size, std::max(NewElts, 8u));
2672 
2673   // Copy the data across.
2674   APValue NewValue(APValue::UninitArray(), NewElts, Size);
2675   for (unsigned I = 0; I != OldElts; ++I)
2676     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2677   for (unsigned I = OldElts; I != NewElts; ++I)
2678     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2679   if (NewValue.hasArrayFiller())
2680     NewValue.getArrayFiller() = Array.getArrayFiller();
2681   Array.swap(NewValue);
2682 }
2683 
2684 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2685 /// conversion. If it's of class type, we may assume that the copy operation
2686 /// is trivial. Note that this is never true for a union type with fields
2687 /// (because the copy always "reads" the active member) and always true for
2688 /// a non-class type.
2689 static bool isReadByLvalueToRvalueConversion(QualType T) {
2690   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2691   if (!RD || (RD->isUnion() && !RD->field_empty()))
2692     return true;
2693   if (RD->isEmpty())
2694     return false;
2695 
2696   for (auto *Field : RD->fields())
2697     if (isReadByLvalueToRvalueConversion(Field->getType()))
2698       return true;
2699 
2700   for (auto &BaseSpec : RD->bases())
2701     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2702       return true;
2703 
2704   return false;
2705 }
2706 
2707 /// Diagnose an attempt to read from any unreadable field within the specified
2708 /// type, which might be a class type.
2709 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2710                                      QualType T) {
2711   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2712   if (!RD)
2713     return false;
2714 
2715   if (!RD->hasMutableFields())
2716     return false;
2717 
2718   for (auto *Field : RD->fields()) {
2719     // If we're actually going to read this field in some way, then it can't
2720     // be mutable. If we're in a union, then assigning to a mutable field
2721     // (even an empty one) can change the active member, so that's not OK.
2722     // FIXME: Add core issue number for the union case.
2723     if (Field->isMutable() &&
2724         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2725       Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2726       Info.Note(Field->getLocation(), diag::note_declared_at);
2727       return true;
2728     }
2729 
2730     if (diagnoseUnreadableFields(Info, E, Field->getType()))
2731       return true;
2732   }
2733 
2734   for (auto &BaseSpec : RD->bases())
2735     if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2736       return true;
2737 
2738   // All mutable fields were empty, and thus not actually read.
2739   return false;
2740 }
2741 
2742 /// Kinds of access we can perform on an object, for diagnostics.
2743 enum AccessKinds {
2744   AK_Read,
2745   AK_Assign,
2746   AK_Increment,
2747   AK_Decrement
2748 };
2749 
2750 namespace {
2751 /// A handle to a complete object (an object that is not a subobject of
2752 /// another object).
2753 struct CompleteObject {
2754   /// The value of the complete object.
2755   APValue *Value;
2756   /// The type of the complete object.
2757   QualType Type;
2758   bool LifetimeStartedInEvaluation;
2759 
2760   CompleteObject() : Value(nullptr) {}
2761   CompleteObject(APValue *Value, QualType Type,
2762                  bool LifetimeStartedInEvaluation)
2763       : Value(Value), Type(Type),
2764         LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
2765     assert(Value && "missing value for complete object");
2766   }
2767 
2768   explicit operator bool() const { return Value; }
2769 };
2770 } // end anonymous namespace
2771 
2772 /// Find the designated sub-object of an rvalue.
2773 template<typename SubobjectHandler>
2774 typename SubobjectHandler::result_type
2775 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2776               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2777   if (Sub.Invalid)
2778     // A diagnostic will have already been produced.
2779     return handler.failed();
2780   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
2781     if (Info.getLangOpts().CPlusPlus11)
2782       Info.FFDiag(E, Sub.isOnePastTheEnd()
2783                          ? diag::note_constexpr_access_past_end
2784                          : diag::note_constexpr_access_unsized_array)
2785           << handler.AccessKind;
2786     else
2787       Info.FFDiag(E);
2788     return handler.failed();
2789   }
2790 
2791   APValue *O = Obj.Value;
2792   QualType ObjType = Obj.Type;
2793   const FieldDecl *LastField = nullptr;
2794   const bool MayReadMutableMembers =
2795       Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
2796 
2797   // Walk the designator's path to find the subobject.
2798   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2799     if (O->isUninit()) {
2800       if (!Info.checkingPotentialConstantExpression())
2801         Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2802       return handler.failed();
2803     }
2804 
2805     if (I == N) {
2806       // If we are reading an object of class type, there may still be more
2807       // things we need to check: if there are any mutable subobjects, we
2808       // cannot perform this read. (This only happens when performing a trivial
2809       // copy or assignment.)
2810       if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2811           !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
2812         return handler.failed();
2813 
2814       if (!handler.found(*O, ObjType))
2815         return false;
2816 
2817       // If we modified a bit-field, truncate it to the right width.
2818       if (handler.AccessKind != AK_Read &&
2819           LastField && LastField->isBitField() &&
2820           !truncateBitfieldValue(Info, E, *O, LastField))
2821         return false;
2822 
2823       return true;
2824     }
2825 
2826     LastField = nullptr;
2827     if (ObjType->isArrayType()) {
2828       // Next subobject is an array element.
2829       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2830       assert(CAT && "vla in literal type?");
2831       uint64_t Index = Sub.Entries[I].ArrayIndex;
2832       if (CAT->getSize().ule(Index)) {
2833         // Note, it should not be possible to form a pointer with a valid
2834         // designator which points more than one past the end of the array.
2835         if (Info.getLangOpts().CPlusPlus11)
2836           Info.FFDiag(E, diag::note_constexpr_access_past_end)
2837             << handler.AccessKind;
2838         else
2839           Info.FFDiag(E);
2840         return handler.failed();
2841       }
2842 
2843       ObjType = CAT->getElementType();
2844 
2845       // An array object is represented as either an Array APValue or as an
2846       // LValue which refers to a string literal.
2847       if (O->isLValue()) {
2848         assert(I == N - 1 && "extracting subobject of character?");
2849         assert(!O->hasLValuePath() || O->getLValuePath().empty());
2850         if (handler.AccessKind != AK_Read)
2851           expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2852                               *O);
2853         else
2854           return handler.foundString(*O, ObjType, Index);
2855       }
2856 
2857       if (O->getArrayInitializedElts() > Index)
2858         O = &O->getArrayInitializedElt(Index);
2859       else if (handler.AccessKind != AK_Read) {
2860         expandArray(*O, Index);
2861         O = &O->getArrayInitializedElt(Index);
2862       } else
2863         O = &O->getArrayFiller();
2864     } else if (ObjType->isAnyComplexType()) {
2865       // Next subobject is a complex number.
2866       uint64_t Index = Sub.Entries[I].ArrayIndex;
2867       if (Index > 1) {
2868         if (Info.getLangOpts().CPlusPlus11)
2869           Info.FFDiag(E, diag::note_constexpr_access_past_end)
2870             << handler.AccessKind;
2871         else
2872           Info.FFDiag(E);
2873         return handler.failed();
2874       }
2875 
2876       bool WasConstQualified = ObjType.isConstQualified();
2877       ObjType = ObjType->castAs<ComplexType>()->getElementType();
2878       if (WasConstQualified)
2879         ObjType.addConst();
2880 
2881       assert(I == N - 1 && "extracting subobject of scalar?");
2882       if (O->isComplexInt()) {
2883         return handler.found(Index ? O->getComplexIntImag()
2884                                    : O->getComplexIntReal(), ObjType);
2885       } else {
2886         assert(O->isComplexFloat());
2887         return handler.found(Index ? O->getComplexFloatImag()
2888                                    : O->getComplexFloatReal(), ObjType);
2889       }
2890     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2891       // In C++14 onwards, it is permitted to read a mutable member whose
2892       // lifetime began within the evaluation.
2893       // FIXME: Should we also allow this in C++11?
2894       if (Field->isMutable() && handler.AccessKind == AK_Read &&
2895           !MayReadMutableMembers) {
2896         Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
2897           << Field;
2898         Info.Note(Field->getLocation(), diag::note_declared_at);
2899         return handler.failed();
2900       }
2901 
2902       // Next subobject is a class, struct or union field.
2903       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2904       if (RD->isUnion()) {
2905         const FieldDecl *UnionField = O->getUnionField();
2906         if (!UnionField ||
2907             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2908           Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
2909             << handler.AccessKind << Field << !UnionField << UnionField;
2910           return handler.failed();
2911         }
2912         O = &O->getUnionValue();
2913       } else
2914         O = &O->getStructField(Field->getFieldIndex());
2915 
2916       bool WasConstQualified = ObjType.isConstQualified();
2917       ObjType = Field->getType();
2918       if (WasConstQualified && !Field->isMutable())
2919         ObjType.addConst();
2920 
2921       if (ObjType.isVolatileQualified()) {
2922         if (Info.getLangOpts().CPlusPlus) {
2923           // FIXME: Include a description of the path to the volatile subobject.
2924           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2925             << handler.AccessKind << 2 << Field;
2926           Info.Note(Field->getLocation(), diag::note_declared_at);
2927         } else {
2928           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2929         }
2930         return handler.failed();
2931       }
2932 
2933       LastField = Field;
2934     } else {
2935       // Next subobject is a base class.
2936       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2937       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2938       O = &O->getStructBase(getBaseIndex(Derived, Base));
2939 
2940       bool WasConstQualified = ObjType.isConstQualified();
2941       ObjType = Info.Ctx.getRecordType(Base);
2942       if (WasConstQualified)
2943         ObjType.addConst();
2944     }
2945   }
2946 }
2947 
2948 namespace {
2949 struct ExtractSubobjectHandler {
2950   EvalInfo &Info;
2951   APValue &Result;
2952 
2953   static const AccessKinds AccessKind = AK_Read;
2954 
2955   typedef bool result_type;
2956   bool failed() { return false; }
2957   bool found(APValue &Subobj, QualType SubobjType) {
2958     Result = Subobj;
2959     return true;
2960   }
2961   bool found(APSInt &Value, QualType SubobjType) {
2962     Result = APValue(Value);
2963     return true;
2964   }
2965   bool found(APFloat &Value, QualType SubobjType) {
2966     Result = APValue(Value);
2967     return true;
2968   }
2969   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2970     Result = APValue(extractStringLiteralCharacter(
2971         Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2972     return true;
2973   }
2974 };
2975 } // end anonymous namespace
2976 
2977 const AccessKinds ExtractSubobjectHandler::AccessKind;
2978 
2979 /// Extract the designated sub-object of an rvalue.
2980 static bool extractSubobject(EvalInfo &Info, const Expr *E,
2981                              const CompleteObject &Obj,
2982                              const SubobjectDesignator &Sub,
2983                              APValue &Result) {
2984   ExtractSubobjectHandler Handler = { Info, Result };
2985   return findSubobject(Info, E, Obj, Sub, Handler);
2986 }
2987 
2988 namespace {
2989 struct ModifySubobjectHandler {
2990   EvalInfo &Info;
2991   APValue &NewVal;
2992   const Expr *E;
2993 
2994   typedef bool result_type;
2995   static const AccessKinds AccessKind = AK_Assign;
2996 
2997   bool checkConst(QualType QT) {
2998     // Assigning to a const object has undefined behavior.
2999     if (QT.isConstQualified()) {
3000       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3001       return false;
3002     }
3003     return true;
3004   }
3005 
3006   bool failed() { return false; }
3007   bool found(APValue &Subobj, QualType SubobjType) {
3008     if (!checkConst(SubobjType))
3009       return false;
3010     // We've been given ownership of NewVal, so just swap it in.
3011     Subobj.swap(NewVal);
3012     return true;
3013   }
3014   bool found(APSInt &Value, QualType SubobjType) {
3015     if (!checkConst(SubobjType))
3016       return false;
3017     if (!NewVal.isInt()) {
3018       // Maybe trying to write a cast pointer value into a complex?
3019       Info.FFDiag(E);
3020       return false;
3021     }
3022     Value = NewVal.getInt();
3023     return true;
3024   }
3025   bool found(APFloat &Value, QualType SubobjType) {
3026     if (!checkConst(SubobjType))
3027       return false;
3028     Value = NewVal.getFloat();
3029     return true;
3030   }
3031   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3032     llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
3033   }
3034 };
3035 } // end anonymous namespace
3036 
3037 const AccessKinds ModifySubobjectHandler::AccessKind;
3038 
3039 /// Update the designated sub-object of an rvalue to the given value.
3040 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3041                             const CompleteObject &Obj,
3042                             const SubobjectDesignator &Sub,
3043                             APValue &NewVal) {
3044   ModifySubobjectHandler Handler = { Info, NewVal, E };
3045   return findSubobject(Info, E, Obj, Sub, Handler);
3046 }
3047 
3048 /// Find the position where two subobject designators diverge, or equivalently
3049 /// the length of the common initial subsequence.
3050 static unsigned FindDesignatorMismatch(QualType ObjType,
3051                                        const SubobjectDesignator &A,
3052                                        const SubobjectDesignator &B,
3053                                        bool &WasArrayIndex) {
3054   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3055   for (/**/; I != N; ++I) {
3056     if (!ObjType.isNull() &&
3057         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3058       // Next subobject is an array element.
3059       if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
3060         WasArrayIndex = true;
3061         return I;
3062       }
3063       if (ObjType->isAnyComplexType())
3064         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3065       else
3066         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3067     } else {
3068       if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
3069         WasArrayIndex = false;
3070         return I;
3071       }
3072       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3073         // Next subobject is a field.
3074         ObjType = FD->getType();
3075       else
3076         // Next subobject is a base class.
3077         ObjType = QualType();
3078     }
3079   }
3080   WasArrayIndex = false;
3081   return I;
3082 }
3083 
3084 /// Determine whether the given subobject designators refer to elements of the
3085 /// same array object.
3086 static bool AreElementsOfSameArray(QualType ObjType,
3087                                    const SubobjectDesignator &A,
3088                                    const SubobjectDesignator &B) {
3089   if (A.Entries.size() != B.Entries.size())
3090     return false;
3091 
3092   bool IsArray = A.MostDerivedIsArrayElement;
3093   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3094     // A is a subobject of the array element.
3095     return false;
3096 
3097   // If A (and B) designates an array element, the last entry will be the array
3098   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3099   // of length 1' case, and the entire path must match.
3100   bool WasArrayIndex;
3101   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3102   return CommonLength >= A.Entries.size() - IsArray;
3103 }
3104 
3105 /// Find the complete object to which an LValue refers.
3106 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3107                                          AccessKinds AK, const LValue &LVal,
3108                                          QualType LValType) {
3109   if (!LVal.Base) {
3110     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3111     return CompleteObject();
3112   }
3113 
3114   CallStackFrame *Frame = nullptr;
3115   if (LVal.getLValueCallIndex()) {
3116     Frame = Info.getCallFrame(LVal.getLValueCallIndex());
3117     if (!Frame) {
3118       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3119         << AK << LVal.Base.is<const ValueDecl*>();
3120       NoteLValueLocation(Info, LVal.Base);
3121       return CompleteObject();
3122     }
3123   }
3124 
3125   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3126   // is not a constant expression (even if the object is non-volatile). We also
3127   // apply this rule to C++98, in order to conform to the expected 'volatile'
3128   // semantics.
3129   if (LValType.isVolatileQualified()) {
3130     if (Info.getLangOpts().CPlusPlus)
3131       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3132         << AK << LValType;
3133     else
3134       Info.FFDiag(E);
3135     return CompleteObject();
3136   }
3137 
3138   // Compute value storage location and type of base object.
3139   APValue *BaseVal = nullptr;
3140   QualType BaseType = getType(LVal.Base);
3141   bool LifetimeStartedInEvaluation = Frame;
3142 
3143   if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3144     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3145     // In C++11, constexpr, non-volatile variables initialized with constant
3146     // expressions are constant expressions too. Inside constexpr functions,
3147     // parameters are constant expressions even if they're non-const.
3148     // In C++1y, objects local to a constant expression (those with a Frame) are
3149     // both readable and writable inside constant expressions.
3150     // In C, such things can also be folded, although they are not ICEs.
3151     const VarDecl *VD = dyn_cast<VarDecl>(D);
3152     if (VD) {
3153       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3154         VD = VDef;
3155     }
3156     if (!VD || VD->isInvalidDecl()) {
3157       Info.FFDiag(E);
3158       return CompleteObject();
3159     }
3160 
3161     // Accesses of volatile-qualified objects are not allowed.
3162     if (BaseType.isVolatileQualified()) {
3163       if (Info.getLangOpts().CPlusPlus) {
3164         Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3165           << AK << 1 << VD;
3166         Info.Note(VD->getLocation(), diag::note_declared_at);
3167       } else {
3168         Info.FFDiag(E);
3169       }
3170       return CompleteObject();
3171     }
3172 
3173     // Unless we're looking at a local variable or argument in a constexpr call,
3174     // the variable we're reading must be const.
3175     if (!Frame) {
3176       if (Info.getLangOpts().CPlusPlus14 &&
3177           VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3178         // OK, we can read and modify an object if we're in the process of
3179         // evaluating its initializer, because its lifetime began in this
3180         // evaluation.
3181       } else if (AK != AK_Read) {
3182         // All the remaining cases only permit reading.
3183         Info.FFDiag(E, diag::note_constexpr_modify_global);
3184         return CompleteObject();
3185       } else if (VD->isConstexpr()) {
3186         // OK, we can read this variable.
3187       } else if (BaseType->isIntegralOrEnumerationType()) {
3188         // In OpenCL if a variable is in constant address space it is a const value.
3189         if (!(BaseType.isConstQualified() ||
3190               (Info.getLangOpts().OpenCL &&
3191                BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3192           if (Info.getLangOpts().CPlusPlus) {
3193             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3194             Info.Note(VD->getLocation(), diag::note_declared_at);
3195           } else {
3196             Info.FFDiag(E);
3197           }
3198           return CompleteObject();
3199         }
3200       } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3201         // We support folding of const floating-point types, in order to make
3202         // static const data members of such types (supported as an extension)
3203         // more useful.
3204         if (Info.getLangOpts().CPlusPlus11) {
3205           Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3206           Info.Note(VD->getLocation(), diag::note_declared_at);
3207         } else {
3208           Info.CCEDiag(E);
3209         }
3210       } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3211         Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3212         // Keep evaluating to see what we can do.
3213       } else {
3214         // FIXME: Allow folding of values of any literal type in all languages.
3215         if (Info.checkingPotentialConstantExpression() &&
3216             VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3217           // The definition of this variable could be constexpr. We can't
3218           // access it right now, but may be able to in future.
3219         } else if (Info.getLangOpts().CPlusPlus11) {
3220           Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3221           Info.Note(VD->getLocation(), diag::note_declared_at);
3222         } else {
3223           Info.FFDiag(E);
3224         }
3225         return CompleteObject();
3226       }
3227     }
3228 
3229     if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
3230       return CompleteObject();
3231   } else {
3232     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3233 
3234     if (!Frame) {
3235       if (const MaterializeTemporaryExpr *MTE =
3236               dyn_cast<MaterializeTemporaryExpr>(Base)) {
3237         assert(MTE->getStorageDuration() == SD_Static &&
3238                "should have a frame for a non-global materialized temporary");
3239 
3240         // Per C++1y [expr.const]p2:
3241         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3242         //   - a [...] glvalue of integral or enumeration type that refers to
3243         //     a non-volatile const object [...]
3244         //   [...]
3245         //   - a [...] glvalue of literal type that refers to a non-volatile
3246         //     object whose lifetime began within the evaluation of e.
3247         //
3248         // C++11 misses the 'began within the evaluation of e' check and
3249         // instead allows all temporaries, including things like:
3250         //   int &&r = 1;
3251         //   int x = ++r;
3252         //   constexpr int k = r;
3253         // Therefore we use the C++14 rules in C++11 too.
3254         const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3255         const ValueDecl *ED = MTE->getExtendingDecl();
3256         if (!(BaseType.isConstQualified() &&
3257               BaseType->isIntegralOrEnumerationType()) &&
3258             !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
3259           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3260           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3261           return CompleteObject();
3262         }
3263 
3264         BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3265         assert(BaseVal && "got reference to unevaluated temporary");
3266         LifetimeStartedInEvaluation = true;
3267       } else {
3268         Info.FFDiag(E);
3269         return CompleteObject();
3270       }
3271     } else {
3272       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
3273       assert(BaseVal && "missing value for temporary");
3274     }
3275 
3276     // Volatile temporary objects cannot be accessed in constant expressions.
3277     if (BaseType.isVolatileQualified()) {
3278       if (Info.getLangOpts().CPlusPlus) {
3279         Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3280           << AK << 0;
3281         Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3282       } else {
3283         Info.FFDiag(E);
3284       }
3285       return CompleteObject();
3286     }
3287   }
3288 
3289   // During the construction of an object, it is not yet 'const'.
3290   // FIXME: This doesn't do quite the right thing for const subobjects of the
3291   // object under construction.
3292   if (Info.isEvaluatingConstructor(LVal.getLValueBase(),
3293                                    LVal.getLValueCallIndex(),
3294                                    LVal.getLValueVersion())) {
3295     BaseType = Info.Ctx.getCanonicalType(BaseType);
3296     BaseType.removeLocalConst();
3297     LifetimeStartedInEvaluation = true;
3298   }
3299 
3300   // In C++14, we can't safely access any mutable state when we might be
3301   // evaluating after an unmodeled side effect.
3302   //
3303   // FIXME: Not all local state is mutable. Allow local constant subobjects
3304   // to be read here (but take care with 'mutable' fields).
3305   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3306        Info.EvalStatus.HasSideEffects) ||
3307       (AK != AK_Read && Info.IsSpeculativelyEvaluating))
3308     return CompleteObject();
3309 
3310   return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
3311 }
3312 
3313 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
3314 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3315 /// glvalue referred to by an entity of reference type.
3316 ///
3317 /// \param Info - Information about the ongoing evaluation.
3318 /// \param Conv - The expression for which we are performing the conversion.
3319 ///               Used for diagnostics.
3320 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3321 ///               case of a non-class type).
3322 /// \param LVal - The glvalue on which we are attempting to perform this action.
3323 /// \param RVal - The produced value will be placed here.
3324 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
3325                                            QualType Type,
3326                                            const LValue &LVal, APValue &RVal) {
3327   if (LVal.Designator.Invalid)
3328     return false;
3329 
3330   // Check for special cases where there is no existing APValue to look at.
3331   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3332   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
3333     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3334       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3335       // initializer until now for such expressions. Such an expression can't be
3336       // an ICE in C, so this only matters for fold.
3337       if (Type.isVolatileQualified()) {
3338         Info.FFDiag(Conv);
3339         return false;
3340       }
3341       APValue Lit;
3342       if (!Evaluate(Lit, Info, CLE->getInitializer()))
3343         return false;
3344       CompleteObject LitObj(&Lit, Base->getType(), false);
3345       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
3346     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3347       // We represent a string literal array as an lvalue pointing at the
3348       // corresponding expression, rather than building an array of chars.
3349       // FIXME: Support ObjCEncodeExpr, MakeStringConstant
3350       APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3351       CompleteObject StrObj(&Str, Base->getType(), false);
3352       return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
3353     }
3354   }
3355 
3356   CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3357   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
3358 }
3359 
3360 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3361 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3362                              QualType LValType, APValue &Val) {
3363   if (LVal.Designator.Invalid)
3364     return false;
3365 
3366   if (!Info.getLangOpts().CPlusPlus14) {
3367     Info.FFDiag(E);
3368     return false;
3369   }
3370 
3371   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3372   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3373 }
3374 
3375 namespace {
3376 struct CompoundAssignSubobjectHandler {
3377   EvalInfo &Info;
3378   const Expr *E;
3379   QualType PromotedLHSType;
3380   BinaryOperatorKind Opcode;
3381   const APValue &RHS;
3382 
3383   static const AccessKinds AccessKind = AK_Assign;
3384 
3385   typedef bool result_type;
3386 
3387   bool checkConst(QualType QT) {
3388     // Assigning to a const object has undefined behavior.
3389     if (QT.isConstQualified()) {
3390       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3391       return false;
3392     }
3393     return true;
3394   }
3395 
3396   bool failed() { return false; }
3397   bool found(APValue &Subobj, QualType SubobjType) {
3398     switch (Subobj.getKind()) {
3399     case APValue::Int:
3400       return found(Subobj.getInt(), SubobjType);
3401     case APValue::Float:
3402       return found(Subobj.getFloat(), SubobjType);
3403     case APValue::ComplexInt:
3404     case APValue::ComplexFloat:
3405       // FIXME: Implement complex compound assignment.
3406       Info.FFDiag(E);
3407       return false;
3408     case APValue::LValue:
3409       return foundPointer(Subobj, SubobjType);
3410     default:
3411       // FIXME: can this happen?
3412       Info.FFDiag(E);
3413       return false;
3414     }
3415   }
3416   bool found(APSInt &Value, QualType SubobjType) {
3417     if (!checkConst(SubobjType))
3418       return false;
3419 
3420     if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3421       // We don't support compound assignment on integer-cast-to-pointer
3422       // values.
3423       Info.FFDiag(E);
3424       return false;
3425     }
3426 
3427     APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3428                                     SubobjType, Value);
3429     if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3430       return false;
3431     Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3432     return true;
3433   }
3434   bool found(APFloat &Value, QualType SubobjType) {
3435     return checkConst(SubobjType) &&
3436            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3437                                   Value) &&
3438            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3439            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3440   }
3441   bool foundPointer(APValue &Subobj, QualType SubobjType) {
3442     if (!checkConst(SubobjType))
3443       return false;
3444 
3445     QualType PointeeType;
3446     if (const PointerType *PT = SubobjType->getAs<PointerType>())
3447       PointeeType = PT->getPointeeType();
3448 
3449     if (PointeeType.isNull() || !RHS.isInt() ||
3450         (Opcode != BO_Add && Opcode != BO_Sub)) {
3451       Info.FFDiag(E);
3452       return false;
3453     }
3454 
3455     APSInt Offset = RHS.getInt();
3456     if (Opcode == BO_Sub)
3457       negateAsSigned(Offset);
3458 
3459     LValue LVal;
3460     LVal.setFrom(Info.Ctx, Subobj);
3461     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3462       return false;
3463     LVal.moveInto(Subobj);
3464     return true;
3465   }
3466   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3467     llvm_unreachable("shouldn't encounter string elements here");
3468   }
3469 };
3470 } // end anonymous namespace
3471 
3472 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3473 
3474 /// Perform a compound assignment of LVal <op>= RVal.
3475 static bool handleCompoundAssignment(
3476     EvalInfo &Info, const Expr *E,
3477     const LValue &LVal, QualType LValType, QualType PromotedLValType,
3478     BinaryOperatorKind Opcode, const APValue &RVal) {
3479   if (LVal.Designator.Invalid)
3480     return false;
3481 
3482   if (!Info.getLangOpts().CPlusPlus14) {
3483     Info.FFDiag(E);
3484     return false;
3485   }
3486 
3487   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3488   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3489                                              RVal };
3490   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3491 }
3492 
3493 namespace {
3494 struct IncDecSubobjectHandler {
3495   EvalInfo &Info;
3496   const UnaryOperator *E;
3497   AccessKinds AccessKind;
3498   APValue *Old;
3499 
3500   typedef bool result_type;
3501 
3502   bool checkConst(QualType QT) {
3503     // Assigning to a const object has undefined behavior.
3504     if (QT.isConstQualified()) {
3505       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3506       return false;
3507     }
3508     return true;
3509   }
3510 
3511   bool failed() { return false; }
3512   bool found(APValue &Subobj, QualType SubobjType) {
3513     // Stash the old value. Also clear Old, so we don't clobber it later
3514     // if we're post-incrementing a complex.
3515     if (Old) {
3516       *Old = Subobj;
3517       Old = nullptr;
3518     }
3519 
3520     switch (Subobj.getKind()) {
3521     case APValue::Int:
3522       return found(Subobj.getInt(), SubobjType);
3523     case APValue::Float:
3524       return found(Subobj.getFloat(), SubobjType);
3525     case APValue::ComplexInt:
3526       return found(Subobj.getComplexIntReal(),
3527                    SubobjType->castAs<ComplexType>()->getElementType()
3528                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3529     case APValue::ComplexFloat:
3530       return found(Subobj.getComplexFloatReal(),
3531                    SubobjType->castAs<ComplexType>()->getElementType()
3532                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3533     case APValue::LValue:
3534       return foundPointer(Subobj, SubobjType);
3535     default:
3536       // FIXME: can this happen?
3537       Info.FFDiag(E);
3538       return false;
3539     }
3540   }
3541   bool found(APSInt &Value, QualType SubobjType) {
3542     if (!checkConst(SubobjType))
3543       return false;
3544 
3545     if (!SubobjType->isIntegerType()) {
3546       // We don't support increment / decrement on integer-cast-to-pointer
3547       // values.
3548       Info.FFDiag(E);
3549       return false;
3550     }
3551 
3552     if (Old) *Old = APValue(Value);
3553 
3554     // bool arithmetic promotes to int, and the conversion back to bool
3555     // doesn't reduce mod 2^n, so special-case it.
3556     if (SubobjType->isBooleanType()) {
3557       if (AccessKind == AK_Increment)
3558         Value = 1;
3559       else
3560         Value = !Value;
3561       return true;
3562     }
3563 
3564     bool WasNegative = Value.isNegative();
3565     if (AccessKind == AK_Increment) {
3566       ++Value;
3567 
3568       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3569         APSInt ActualValue(Value, /*IsUnsigned*/true);
3570         return HandleOverflow(Info, E, ActualValue, SubobjType);
3571       }
3572     } else {
3573       --Value;
3574 
3575       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3576         unsigned BitWidth = Value.getBitWidth();
3577         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3578         ActualValue.setBit(BitWidth);
3579         return HandleOverflow(Info, E, ActualValue, SubobjType);
3580       }
3581     }
3582     return true;
3583   }
3584   bool found(APFloat &Value, QualType SubobjType) {
3585     if (!checkConst(SubobjType))
3586       return false;
3587 
3588     if (Old) *Old = APValue(Value);
3589 
3590     APFloat One(Value.getSemantics(), 1);
3591     if (AccessKind == AK_Increment)
3592       Value.add(One, APFloat::rmNearestTiesToEven);
3593     else
3594       Value.subtract(One, APFloat::rmNearestTiesToEven);
3595     return true;
3596   }
3597   bool foundPointer(APValue &Subobj, QualType SubobjType) {
3598     if (!checkConst(SubobjType))
3599       return false;
3600 
3601     QualType PointeeType;
3602     if (const PointerType *PT = SubobjType->getAs<PointerType>())
3603       PointeeType = PT->getPointeeType();
3604     else {
3605       Info.FFDiag(E);
3606       return false;
3607     }
3608 
3609     LValue LVal;
3610     LVal.setFrom(Info.Ctx, Subobj);
3611     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3612                                      AccessKind == AK_Increment ? 1 : -1))
3613       return false;
3614     LVal.moveInto(Subobj);
3615     return true;
3616   }
3617   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3618     llvm_unreachable("shouldn't encounter string elements here");
3619   }
3620 };
3621 } // end anonymous namespace
3622 
3623 /// Perform an increment or decrement on LVal.
3624 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3625                          QualType LValType, bool IsIncrement, APValue *Old) {
3626   if (LVal.Designator.Invalid)
3627     return false;
3628 
3629   if (!Info.getLangOpts().CPlusPlus14) {
3630     Info.FFDiag(E);
3631     return false;
3632   }
3633 
3634   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3635   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3636   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3637   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3638 }
3639 
3640 /// Build an lvalue for the object argument of a member function call.
3641 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3642                                    LValue &This) {
3643   if (Object->getType()->isPointerType())
3644     return EvaluatePointer(Object, This, Info);
3645 
3646   if (Object->isGLValue())
3647     return EvaluateLValue(Object, This, Info);
3648 
3649   if (Object->getType()->isLiteralType(Info.Ctx))
3650     return EvaluateTemporary(Object, This, Info);
3651 
3652   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3653   return false;
3654 }
3655 
3656 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3657 /// lvalue referring to the result.
3658 ///
3659 /// \param Info - Information about the ongoing evaluation.
3660 /// \param LV - An lvalue referring to the base of the member pointer.
3661 /// \param RHS - The member pointer expression.
3662 /// \param IncludeMember - Specifies whether the member itself is included in
3663 ///        the resulting LValue subobject designator. This is not possible when
3664 ///        creating a bound member function.
3665 /// \return The field or method declaration to which the member pointer refers,
3666 ///         or 0 if evaluation fails.
3667 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3668                                                   QualType LVType,
3669                                                   LValue &LV,
3670                                                   const Expr *RHS,
3671                                                   bool IncludeMember = true) {
3672   MemberPtr MemPtr;
3673   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3674     return nullptr;
3675 
3676   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3677   // member value, the behavior is undefined.
3678   if (!MemPtr.getDecl()) {
3679     // FIXME: Specific diagnostic.
3680     Info.FFDiag(RHS);
3681     return nullptr;
3682   }
3683 
3684   if (MemPtr.isDerivedMember()) {
3685     // This is a member of some derived class. Truncate LV appropriately.
3686     // The end of the derived-to-base path for the base object must match the
3687     // derived-to-base path for the member pointer.
3688     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3689         LV.Designator.Entries.size()) {
3690       Info.FFDiag(RHS);
3691       return nullptr;
3692     }
3693     unsigned PathLengthToMember =
3694         LV.Designator.Entries.size() - MemPtr.Path.size();
3695     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3696       const CXXRecordDecl *LVDecl = getAsBaseClass(
3697           LV.Designator.Entries[PathLengthToMember + I]);
3698       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3699       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3700         Info.FFDiag(RHS);
3701         return nullptr;
3702       }
3703     }
3704 
3705     // Truncate the lvalue to the appropriate derived class.
3706     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3707                             PathLengthToMember))
3708       return nullptr;
3709   } else if (!MemPtr.Path.empty()) {
3710     // Extend the LValue path with the member pointer's path.
3711     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3712                                   MemPtr.Path.size() + IncludeMember);
3713 
3714     // Walk down to the appropriate base class.
3715     if (const PointerType *PT = LVType->getAs<PointerType>())
3716       LVType = PT->getPointeeType();
3717     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3718     assert(RD && "member pointer access on non-class-type expression");
3719     // The first class in the path is that of the lvalue.
3720     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3721       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3722       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3723         return nullptr;
3724       RD = Base;
3725     }
3726     // Finally cast to the class containing the member.
3727     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3728                                 MemPtr.getContainingRecord()))
3729       return nullptr;
3730   }
3731 
3732   // Add the member. Note that we cannot build bound member functions here.
3733   if (IncludeMember) {
3734     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3735       if (!HandleLValueMember(Info, RHS, LV, FD))
3736         return nullptr;
3737     } else if (const IndirectFieldDecl *IFD =
3738                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3739       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3740         return nullptr;
3741     } else {
3742       llvm_unreachable("can't construct reference to bound member function");
3743     }
3744   }
3745 
3746   return MemPtr.getDecl();
3747 }
3748 
3749 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3750                                                   const BinaryOperator *BO,
3751                                                   LValue &LV,
3752                                                   bool IncludeMember = true) {
3753   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3754 
3755   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3756     if (Info.noteFailure()) {
3757       MemberPtr MemPtr;
3758       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3759     }
3760     return nullptr;
3761   }
3762 
3763   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3764                                    BO->getRHS(), IncludeMember);
3765 }
3766 
3767 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3768 /// the provided lvalue, which currently refers to the base object.
3769 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3770                                     LValue &Result) {
3771   SubobjectDesignator &D = Result.Designator;
3772   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3773     return false;
3774 
3775   QualType TargetQT = E->getType();
3776   if (const PointerType *PT = TargetQT->getAs<PointerType>())
3777     TargetQT = PT->getPointeeType();
3778 
3779   // Check this cast lands within the final derived-to-base subobject path.
3780   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3781     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3782       << D.MostDerivedType << TargetQT;
3783     return false;
3784   }
3785 
3786   // Check the type of the final cast. We don't need to check the path,
3787   // since a cast can only be formed if the path is unique.
3788   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3789   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3790   const CXXRecordDecl *FinalType;
3791   if (NewEntriesSize == D.MostDerivedPathLength)
3792     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3793   else
3794     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3795   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3796     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3797       << D.MostDerivedType << TargetQT;
3798     return false;
3799   }
3800 
3801   // Truncate the lvalue to the appropriate derived class.
3802   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3803 }
3804 
3805 namespace {
3806 enum EvalStmtResult {
3807   /// Evaluation failed.
3808   ESR_Failed,
3809   /// Hit a 'return' statement.
3810   ESR_Returned,
3811   /// Evaluation succeeded.
3812   ESR_Succeeded,
3813   /// Hit a 'continue' statement.
3814   ESR_Continue,
3815   /// Hit a 'break' statement.
3816   ESR_Break,
3817   /// Still scanning for 'case' or 'default' statement.
3818   ESR_CaseNotFound
3819 };
3820 }
3821 
3822 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3823   // We don't need to evaluate the initializer for a static local.
3824   if (!VD->hasLocalStorage())
3825     return true;
3826 
3827   LValue Result;
3828   APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
3829 
3830   const Expr *InitE = VD->getInit();
3831   if (!InitE) {
3832     Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
3833         << false << VD->getType();
3834     Val = APValue();
3835     return false;
3836   }
3837 
3838   if (InitE->isValueDependent())
3839     return false;
3840 
3841   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3842     // Wipe out any partially-computed value, to allow tracking that this
3843     // evaluation failed.
3844     Val = APValue();
3845     return false;
3846   }
3847 
3848   return true;
3849 }
3850 
3851 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3852   bool OK = true;
3853 
3854   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3855     OK &= EvaluateVarDecl(Info, VD);
3856 
3857   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3858     for (auto *BD : DD->bindings())
3859       if (auto *VD = BD->getHoldingVar())
3860         OK &= EvaluateDecl(Info, VD);
3861 
3862   return OK;
3863 }
3864 
3865 
3866 /// Evaluate a condition (either a variable declaration or an expression).
3867 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3868                          const Expr *Cond, bool &Result) {
3869   FullExpressionRAII Scope(Info);
3870   if (CondDecl && !EvaluateDecl(Info, CondDecl))
3871     return false;
3872   return EvaluateAsBooleanCondition(Cond, Result, Info);
3873 }
3874 
3875 namespace {
3876 /// A location where the result (returned value) of evaluating a
3877 /// statement should be stored.
3878 struct StmtResult {
3879   /// The APValue that should be filled in with the returned value.
3880   APValue &Value;
3881   /// The location containing the result, if any (used to support RVO).
3882   const LValue *Slot;
3883 };
3884 
3885 struct TempVersionRAII {
3886   CallStackFrame &Frame;
3887 
3888   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
3889     Frame.pushTempVersion();
3890   }
3891 
3892   ~TempVersionRAII() {
3893     Frame.popTempVersion();
3894   }
3895 };
3896 
3897 }
3898 
3899 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3900                                    const Stmt *S,
3901                                    const SwitchCase *SC = nullptr);
3902 
3903 /// Evaluate the body of a loop, and translate the result as appropriate.
3904 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
3905                                        const Stmt *Body,
3906                                        const SwitchCase *Case = nullptr) {
3907   BlockScopeRAII Scope(Info);
3908   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3909   case ESR_Break:
3910     return ESR_Succeeded;
3911   case ESR_Succeeded:
3912   case ESR_Continue:
3913     return ESR_Continue;
3914   case ESR_Failed:
3915   case ESR_Returned:
3916   case ESR_CaseNotFound:
3917     return ESR;
3918   }
3919   llvm_unreachable("Invalid EvalStmtResult!");
3920 }
3921 
3922 /// Evaluate a switch statement.
3923 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
3924                                      const SwitchStmt *SS) {
3925   BlockScopeRAII Scope(Info);
3926 
3927   // Evaluate the switch condition.
3928   APSInt Value;
3929   {
3930     FullExpressionRAII Scope(Info);
3931     if (const Stmt *Init = SS->getInit()) {
3932       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3933       if (ESR != ESR_Succeeded)
3934         return ESR;
3935     }
3936     if (SS->getConditionVariable() &&
3937         !EvaluateDecl(Info, SS->getConditionVariable()))
3938       return ESR_Failed;
3939     if (!EvaluateInteger(SS->getCond(), Value, Info))
3940       return ESR_Failed;
3941   }
3942 
3943   // Find the switch case corresponding to the value of the condition.
3944   // FIXME: Cache this lookup.
3945   const SwitchCase *Found = nullptr;
3946   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3947        SC = SC->getNextSwitchCase()) {
3948     if (isa<DefaultStmt>(SC)) {
3949       Found = SC;
3950       continue;
3951     }
3952 
3953     const CaseStmt *CS = cast<CaseStmt>(SC);
3954     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3955     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3956                               : LHS;
3957     if (LHS <= Value && Value <= RHS) {
3958       Found = SC;
3959       break;
3960     }
3961   }
3962 
3963   if (!Found)
3964     return ESR_Succeeded;
3965 
3966   // Search the switch body for the switch case and evaluate it from there.
3967   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3968   case ESR_Break:
3969     return ESR_Succeeded;
3970   case ESR_Succeeded:
3971   case ESR_Continue:
3972   case ESR_Failed:
3973   case ESR_Returned:
3974     return ESR;
3975   case ESR_CaseNotFound:
3976     // This can only happen if the switch case is nested within a statement
3977     // expression. We have no intention of supporting that.
3978     Info.FFDiag(Found->getBeginLoc(),
3979                 diag::note_constexpr_stmt_expr_unsupported);
3980     return ESR_Failed;
3981   }
3982   llvm_unreachable("Invalid EvalStmtResult!");
3983 }
3984 
3985 // Evaluate a statement.
3986 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3987                                    const Stmt *S, const SwitchCase *Case) {
3988   if (!Info.nextStep(S))
3989     return ESR_Failed;
3990 
3991   // If we're hunting down a 'case' or 'default' label, recurse through
3992   // substatements until we hit the label.
3993   if (Case) {
3994     // FIXME: We don't start the lifetime of objects whose initialization we
3995     // jump over. However, such objects must be of class type with a trivial
3996     // default constructor that initialize all subobjects, so must be empty,
3997     // so this almost never matters.
3998     switch (S->getStmtClass()) {
3999     case Stmt::CompoundStmtClass:
4000       // FIXME: Precompute which substatement of a compound statement we
4001       // would jump to, and go straight there rather than performing a
4002       // linear scan each time.
4003     case Stmt::LabelStmtClass:
4004     case Stmt::AttributedStmtClass:
4005     case Stmt::DoStmtClass:
4006       break;
4007 
4008     case Stmt::CaseStmtClass:
4009     case Stmt::DefaultStmtClass:
4010       if (Case == S)
4011         Case = nullptr;
4012       break;
4013 
4014     case Stmt::IfStmtClass: {
4015       // FIXME: Precompute which side of an 'if' we would jump to, and go
4016       // straight there rather than scanning both sides.
4017       const IfStmt *IS = cast<IfStmt>(S);
4018 
4019       // Wrap the evaluation in a block scope, in case it's a DeclStmt
4020       // preceded by our switch label.
4021       BlockScopeRAII Scope(Info);
4022 
4023       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4024       if (ESR != ESR_CaseNotFound || !IS->getElse())
4025         return ESR;
4026       return EvaluateStmt(Result, Info, IS->getElse(), Case);
4027     }
4028 
4029     case Stmt::WhileStmtClass: {
4030       EvalStmtResult ESR =
4031           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4032       if (ESR != ESR_Continue)
4033         return ESR;
4034       break;
4035     }
4036 
4037     case Stmt::ForStmtClass: {
4038       const ForStmt *FS = cast<ForStmt>(S);
4039       EvalStmtResult ESR =
4040           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4041       if (ESR != ESR_Continue)
4042         return ESR;
4043       if (FS->getInc()) {
4044         FullExpressionRAII IncScope(Info);
4045         if (!EvaluateIgnoredValue(Info, FS->getInc()))
4046           return ESR_Failed;
4047       }
4048       break;
4049     }
4050 
4051     case Stmt::DeclStmtClass:
4052       // FIXME: If the variable has initialization that can't be jumped over,
4053       // bail out of any immediately-surrounding compound-statement too.
4054     default:
4055       return ESR_CaseNotFound;
4056     }
4057   }
4058 
4059   switch (S->getStmtClass()) {
4060   default:
4061     if (const Expr *E = dyn_cast<Expr>(S)) {
4062       // Don't bother evaluating beyond an expression-statement which couldn't
4063       // be evaluated.
4064       FullExpressionRAII Scope(Info);
4065       if (!EvaluateIgnoredValue(Info, E))
4066         return ESR_Failed;
4067       return ESR_Succeeded;
4068     }
4069 
4070     Info.FFDiag(S->getBeginLoc());
4071     return ESR_Failed;
4072 
4073   case Stmt::NullStmtClass:
4074     return ESR_Succeeded;
4075 
4076   case Stmt::DeclStmtClass: {
4077     const DeclStmt *DS = cast<DeclStmt>(S);
4078     for (const auto *DclIt : DS->decls()) {
4079       // Each declaration initialization is its own full-expression.
4080       // FIXME: This isn't quite right; if we're performing aggregate
4081       // initialization, each braced subexpression is its own full-expression.
4082       FullExpressionRAII Scope(Info);
4083       if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
4084         return ESR_Failed;
4085     }
4086     return ESR_Succeeded;
4087   }
4088 
4089   case Stmt::ReturnStmtClass: {
4090     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
4091     FullExpressionRAII Scope(Info);
4092     if (RetExpr &&
4093         !(Result.Slot
4094               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4095               : Evaluate(Result.Value, Info, RetExpr)))
4096       return ESR_Failed;
4097     return ESR_Returned;
4098   }
4099 
4100   case Stmt::CompoundStmtClass: {
4101     BlockScopeRAII Scope(Info);
4102 
4103     const CompoundStmt *CS = cast<CompoundStmt>(S);
4104     for (const auto *BI : CS->body()) {
4105       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
4106       if (ESR == ESR_Succeeded)
4107         Case = nullptr;
4108       else if (ESR != ESR_CaseNotFound)
4109         return ESR;
4110     }
4111     return Case ? ESR_CaseNotFound : ESR_Succeeded;
4112   }
4113 
4114   case Stmt::IfStmtClass: {
4115     const IfStmt *IS = cast<IfStmt>(S);
4116 
4117     // Evaluate the condition, as either a var decl or as an expression.
4118     BlockScopeRAII Scope(Info);
4119     if (const Stmt *Init = IS->getInit()) {
4120       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4121       if (ESR != ESR_Succeeded)
4122         return ESR;
4123     }
4124     bool Cond;
4125     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4126       return ESR_Failed;
4127 
4128     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4129       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4130       if (ESR != ESR_Succeeded)
4131         return ESR;
4132     }
4133     return ESR_Succeeded;
4134   }
4135 
4136   case Stmt::WhileStmtClass: {
4137     const WhileStmt *WS = cast<WhileStmt>(S);
4138     while (true) {
4139       BlockScopeRAII Scope(Info);
4140       bool Continue;
4141       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4142                         Continue))
4143         return ESR_Failed;
4144       if (!Continue)
4145         break;
4146 
4147       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4148       if (ESR != ESR_Continue)
4149         return ESR;
4150     }
4151     return ESR_Succeeded;
4152   }
4153 
4154   case Stmt::DoStmtClass: {
4155     const DoStmt *DS = cast<DoStmt>(S);
4156     bool Continue;
4157     do {
4158       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4159       if (ESR != ESR_Continue)
4160         return ESR;
4161       Case = nullptr;
4162 
4163       FullExpressionRAII CondScope(Info);
4164       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4165         return ESR_Failed;
4166     } while (Continue);
4167     return ESR_Succeeded;
4168   }
4169 
4170   case Stmt::ForStmtClass: {
4171     const ForStmt *FS = cast<ForStmt>(S);
4172     BlockScopeRAII Scope(Info);
4173     if (FS->getInit()) {
4174       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4175       if (ESR != ESR_Succeeded)
4176         return ESR;
4177     }
4178     while (true) {
4179       BlockScopeRAII Scope(Info);
4180       bool Continue = true;
4181       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4182                                          FS->getCond(), Continue))
4183         return ESR_Failed;
4184       if (!Continue)
4185         break;
4186 
4187       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4188       if (ESR != ESR_Continue)
4189         return ESR;
4190 
4191       if (FS->getInc()) {
4192         FullExpressionRAII IncScope(Info);
4193         if (!EvaluateIgnoredValue(Info, FS->getInc()))
4194           return ESR_Failed;
4195       }
4196     }
4197     return ESR_Succeeded;
4198   }
4199 
4200   case Stmt::CXXForRangeStmtClass: {
4201     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4202     BlockScopeRAII Scope(Info);
4203 
4204     // Evaluate the init-statement if present.
4205     if (FS->getInit()) {
4206       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4207       if (ESR != ESR_Succeeded)
4208         return ESR;
4209     }
4210 
4211     // Initialize the __range variable.
4212     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4213     if (ESR != ESR_Succeeded)
4214       return ESR;
4215 
4216     // Create the __begin and __end iterators.
4217     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4218     if (ESR != ESR_Succeeded)
4219       return ESR;
4220     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4221     if (ESR != ESR_Succeeded)
4222       return ESR;
4223 
4224     while (true) {
4225       // Condition: __begin != __end.
4226       {
4227         bool Continue = true;
4228         FullExpressionRAII CondExpr(Info);
4229         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4230           return ESR_Failed;
4231         if (!Continue)
4232           break;
4233       }
4234 
4235       // User's variable declaration, initialized by *__begin.
4236       BlockScopeRAII InnerScope(Info);
4237       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4238       if (ESR != ESR_Succeeded)
4239         return ESR;
4240 
4241       // Loop body.
4242       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4243       if (ESR != ESR_Continue)
4244         return ESR;
4245 
4246       // Increment: ++__begin
4247       if (!EvaluateIgnoredValue(Info, FS->getInc()))
4248         return ESR_Failed;
4249     }
4250 
4251     return ESR_Succeeded;
4252   }
4253 
4254   case Stmt::SwitchStmtClass:
4255     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4256 
4257   case Stmt::ContinueStmtClass:
4258     return ESR_Continue;
4259 
4260   case Stmt::BreakStmtClass:
4261     return ESR_Break;
4262 
4263   case Stmt::LabelStmtClass:
4264     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4265 
4266   case Stmt::AttributedStmtClass:
4267     // As a general principle, C++11 attributes can be ignored without
4268     // any semantic impact.
4269     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4270                         Case);
4271 
4272   case Stmt::CaseStmtClass:
4273   case Stmt::DefaultStmtClass:
4274     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4275   }
4276 }
4277 
4278 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4279 /// default constructor. If so, we'll fold it whether or not it's marked as
4280 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4281 /// so we need special handling.
4282 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4283                                            const CXXConstructorDecl *CD,
4284                                            bool IsValueInitialization) {
4285   if (!CD->isTrivial() || !CD->isDefaultConstructor())
4286     return false;
4287 
4288   // Value-initialization does not call a trivial default constructor, so such a
4289   // call is a core constant expression whether or not the constructor is
4290   // constexpr.
4291   if (!CD->isConstexpr() && !IsValueInitialization) {
4292     if (Info.getLangOpts().CPlusPlus11) {
4293       // FIXME: If DiagDecl is an implicitly-declared special member function,
4294       // we should be much more explicit about why it's not constexpr.
4295       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4296         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4297       Info.Note(CD->getLocation(), diag::note_declared_at);
4298     } else {
4299       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4300     }
4301   }
4302   return true;
4303 }
4304 
4305 /// CheckConstexprFunction - Check that a function can be called in a constant
4306 /// expression.
4307 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4308                                    const FunctionDecl *Declaration,
4309                                    const FunctionDecl *Definition,
4310                                    const Stmt *Body) {
4311   // Potential constant expressions can contain calls to declared, but not yet
4312   // defined, constexpr functions.
4313   if (Info.checkingPotentialConstantExpression() && !Definition &&
4314       Declaration->isConstexpr())
4315     return false;
4316 
4317   // Bail out if the function declaration itself is invalid.  We will
4318   // have produced a relevant diagnostic while parsing it, so just
4319   // note the problematic sub-expression.
4320   if (Declaration->isInvalidDecl()) {
4321     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4322     return false;
4323   }
4324 
4325   // Can we evaluate this function call?
4326   if (Definition && Definition->isConstexpr() &&
4327       !Definition->isInvalidDecl() && Body)
4328     return true;
4329 
4330   if (Info.getLangOpts().CPlusPlus11) {
4331     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4332 
4333     // If this function is not constexpr because it is an inherited
4334     // non-constexpr constructor, diagnose that directly.
4335     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4336     if (CD && CD->isInheritingConstructor()) {
4337       auto *Inherited = CD->getInheritedConstructor().getConstructor();
4338       if (!Inherited->isConstexpr())
4339         DiagDecl = CD = Inherited;
4340     }
4341 
4342     // FIXME: If DiagDecl is an implicitly-declared special member function
4343     // or an inheriting constructor, we should be much more explicit about why
4344     // it's not constexpr.
4345     if (CD && CD->isInheritingConstructor())
4346       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4347         << CD->getInheritedConstructor().getConstructor()->getParent();
4348     else
4349       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4350         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4351     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4352   } else {
4353     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4354   }
4355   return false;
4356 }
4357 
4358 /// Determine if a class has any fields that might need to be copied by a
4359 /// trivial copy or move operation.
4360 static bool hasFields(const CXXRecordDecl *RD) {
4361   if (!RD || RD->isEmpty())
4362     return false;
4363   for (auto *FD : RD->fields()) {
4364     if (FD->isUnnamedBitfield())
4365       continue;
4366     return true;
4367   }
4368   for (auto &Base : RD->bases())
4369     if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4370       return true;
4371   return false;
4372 }
4373 
4374 namespace {
4375 typedef SmallVector<APValue, 8> ArgVector;
4376 }
4377 
4378 /// EvaluateArgs - Evaluate the arguments to a function call.
4379 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4380                          EvalInfo &Info) {
4381   bool Success = true;
4382   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
4383        I != E; ++I) {
4384     if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4385       // If we're checking for a potential constant expression, evaluate all
4386       // initializers even if some of them fail.
4387       if (!Info.noteFailure())
4388         return false;
4389       Success = false;
4390     }
4391   }
4392   return Success;
4393 }
4394 
4395 /// Evaluate a function call.
4396 static bool HandleFunctionCall(SourceLocation CallLoc,
4397                                const FunctionDecl *Callee, const LValue *This,
4398                                ArrayRef<const Expr*> Args, const Stmt *Body,
4399                                EvalInfo &Info, APValue &Result,
4400                                const LValue *ResultSlot) {
4401   ArgVector ArgValues(Args.size());
4402   if (!EvaluateArgs(Args, ArgValues, Info))
4403     return false;
4404 
4405   if (!Info.CheckCallLimit(CallLoc))
4406     return false;
4407 
4408   CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
4409 
4410   // For a trivial copy or move assignment, perform an APValue copy. This is
4411   // essential for unions, where the operations performed by the assignment
4412   // operator cannot be represented as statements.
4413   //
4414   // Skip this for non-union classes with no fields; in that case, the defaulted
4415   // copy/move does not actually read the object.
4416   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
4417   if (MD && MD->isDefaulted() &&
4418       (MD->getParent()->isUnion() ||
4419        (MD->isTrivial() && hasFields(MD->getParent())))) {
4420     assert(This &&
4421            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4422     LValue RHS;
4423     RHS.setFrom(Info.Ctx, ArgValues[0]);
4424     APValue RHSValue;
4425     if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4426                                         RHS, RHSValue))
4427       return false;
4428     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4429                           RHSValue))
4430       return false;
4431     This->moveInto(Result);
4432     return true;
4433   } else if (MD && isLambdaCallOperator(MD)) {
4434     // We're in a lambda; determine the lambda capture field maps unless we're
4435     // just constexpr checking a lambda's call operator. constexpr checking is
4436     // done before the captures have been added to the closure object (unless
4437     // we're inferring constexpr-ness), so we don't have access to them in this
4438     // case. But since we don't need the captures to constexpr check, we can
4439     // just ignore them.
4440     if (!Info.checkingPotentialConstantExpression())
4441       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4442                                         Frame.LambdaThisCaptureField);
4443   }
4444 
4445   StmtResult Ret = {Result, ResultSlot};
4446   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
4447   if (ESR == ESR_Succeeded) {
4448     if (Callee->getReturnType()->isVoidType())
4449       return true;
4450     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
4451   }
4452   return ESR == ESR_Returned;
4453 }
4454 
4455 /// Evaluate a constructor call.
4456 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4457                                   APValue *ArgValues,
4458                                   const CXXConstructorDecl *Definition,
4459                                   EvalInfo &Info, APValue &Result) {
4460   SourceLocation CallLoc = E->getExprLoc();
4461   if (!Info.CheckCallLimit(CallLoc))
4462     return false;
4463 
4464   const CXXRecordDecl *RD = Definition->getParent();
4465   if (RD->getNumVBases()) {
4466     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
4467     return false;
4468   }
4469 
4470   EvalInfo::EvaluatingConstructorRAII EvalObj(
4471       Info, {This.getLValueBase(),
4472              {This.getLValueCallIndex(), This.getLValueVersion()}});
4473   CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
4474 
4475   // FIXME: Creating an APValue just to hold a nonexistent return value is
4476   // wasteful.
4477   APValue RetVal;
4478   StmtResult Ret = {RetVal, nullptr};
4479 
4480   // If it's a delegating constructor, delegate.
4481   if (Definition->isDelegatingConstructor()) {
4482     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
4483     {
4484       FullExpressionRAII InitScope(Info);
4485       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4486         return false;
4487     }
4488     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4489   }
4490 
4491   // For a trivial copy or move constructor, perform an APValue copy. This is
4492   // essential for unions (or classes with anonymous union members), where the
4493   // operations performed by the constructor cannot be represented by
4494   // ctor-initializers.
4495   //
4496   // Skip this for empty non-union classes; we should not perform an
4497   // lvalue-to-rvalue conversion on them because their copy constructor does not
4498   // actually read them.
4499   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
4500       (Definition->getParent()->isUnion() ||
4501        (Definition->isTrivial() && hasFields(Definition->getParent())))) {
4502     LValue RHS;
4503     RHS.setFrom(Info.Ctx, ArgValues[0]);
4504     return handleLValueToRValueConversion(
4505         Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4506         RHS, Result);
4507   }
4508 
4509   // Reserve space for the struct members.
4510   if (!RD->isUnion() && Result.isUninit())
4511     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4512                      std::distance(RD->field_begin(), RD->field_end()));
4513 
4514   if (RD->isInvalidDecl()) return false;
4515   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4516 
4517   // A scope for temporaries lifetime-extended by reference members.
4518   BlockScopeRAII LifetimeExtendedScope(Info);
4519 
4520   bool Success = true;
4521   unsigned BasesSeen = 0;
4522 #ifndef NDEBUG
4523   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4524 #endif
4525   for (const auto *I : Definition->inits()) {
4526     LValue Subobject = This;
4527     LValue SubobjectParent = This;
4528     APValue *Value = &Result;
4529 
4530     // Determine the subobject to initialize.
4531     FieldDecl *FD = nullptr;
4532     if (I->isBaseInitializer()) {
4533       QualType BaseType(I->getBaseClass(), 0);
4534 #ifndef NDEBUG
4535       // Non-virtual base classes are initialized in the order in the class
4536       // definition. We have already checked for virtual base classes.
4537       assert(!BaseIt->isVirtual() && "virtual base for literal type");
4538       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4539              "base class initializers not in expected order");
4540       ++BaseIt;
4541 #endif
4542       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
4543                                   BaseType->getAsCXXRecordDecl(), &Layout))
4544         return false;
4545       Value = &Result.getStructBase(BasesSeen++);
4546     } else if ((FD = I->getMember())) {
4547       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
4548         return false;
4549       if (RD->isUnion()) {
4550         Result = APValue(FD);
4551         Value = &Result.getUnionValue();
4552       } else {
4553         Value = &Result.getStructField(FD->getFieldIndex());
4554       }
4555     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
4556       // Walk the indirect field decl's chain to find the object to initialize,
4557       // and make sure we've initialized every step along it.
4558       auto IndirectFieldChain = IFD->chain();
4559       for (auto *C : IndirectFieldChain) {
4560         FD = cast<FieldDecl>(C);
4561         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4562         // Switch the union field if it differs. This happens if we had
4563         // preceding zero-initialization, and we're now initializing a union
4564         // subobject other than the first.
4565         // FIXME: In this case, the values of the other subobjects are
4566         // specified, since zero-initialization sets all padding bits to zero.
4567         if (Value->isUninit() ||
4568             (Value->isUnion() && Value->getUnionField() != FD)) {
4569           if (CD->isUnion())
4570             *Value = APValue(FD);
4571           else
4572             *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
4573                              std::distance(CD->field_begin(), CD->field_end()));
4574         }
4575         // Store Subobject as its parent before updating it for the last element
4576         // in the chain.
4577         if (C == IndirectFieldChain.back())
4578           SubobjectParent = Subobject;
4579         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
4580           return false;
4581         if (CD->isUnion())
4582           Value = &Value->getUnionValue();
4583         else
4584           Value = &Value->getStructField(FD->getFieldIndex());
4585       }
4586     } else {
4587       llvm_unreachable("unknown base initializer kind");
4588     }
4589 
4590     // Need to override This for implicit field initializers as in this case
4591     // This refers to innermost anonymous struct/union containing initializer,
4592     // not to currently constructed class.
4593     const Expr *Init = I->getInit();
4594     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
4595                                   isa<CXXDefaultInitExpr>(Init));
4596     FullExpressionRAII InitScope(Info);
4597     if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
4598         (FD && FD->isBitField() &&
4599          !truncateBitfieldValue(Info, Init, *Value, FD))) {
4600       // If we're checking for a potential constant expression, evaluate all
4601       // initializers even if some of them fail.
4602       if (!Info.noteFailure())
4603         return false;
4604       Success = false;
4605     }
4606   }
4607 
4608   return Success &&
4609          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4610 }
4611 
4612 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4613                                   ArrayRef<const Expr*> Args,
4614                                   const CXXConstructorDecl *Definition,
4615                                   EvalInfo &Info, APValue &Result) {
4616   ArgVector ArgValues(Args.size());
4617   if (!EvaluateArgs(Args, ArgValues, Info))
4618     return false;
4619 
4620   return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4621                                Info, Result);
4622 }
4623 
4624 //===----------------------------------------------------------------------===//
4625 // Generic Evaluation
4626 //===----------------------------------------------------------------------===//
4627 namespace {
4628 
4629 template <class Derived>
4630 class ExprEvaluatorBase
4631   : public ConstStmtVisitor<Derived, bool> {
4632 private:
4633   Derived &getDerived() { return static_cast<Derived&>(*this); }
4634   bool DerivedSuccess(const APValue &V, const Expr *E) {
4635     return getDerived().Success(V, E);
4636   }
4637   bool DerivedZeroInitialization(const Expr *E) {
4638     return getDerived().ZeroInitialization(E);
4639   }
4640 
4641   // Check whether a conditional operator with a non-constant condition is a
4642   // potential constant expression. If neither arm is a potential constant
4643   // expression, then the conditional operator is not either.
4644   template<typename ConditionalOperator>
4645   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
4646     assert(Info.checkingPotentialConstantExpression());
4647 
4648     // Speculatively evaluate both arms.
4649     SmallVector<PartialDiagnosticAt, 8> Diag;
4650     {
4651       SpeculativeEvaluationRAII Speculate(Info, &Diag);
4652       StmtVisitorTy::Visit(E->getFalseExpr());
4653       if (Diag.empty())
4654         return;
4655     }
4656 
4657     {
4658       SpeculativeEvaluationRAII Speculate(Info, &Diag);
4659       Diag.clear();
4660       StmtVisitorTy::Visit(E->getTrueExpr());
4661       if (Diag.empty())
4662         return;
4663     }
4664 
4665     Error(E, diag::note_constexpr_conditional_never_const);
4666   }
4667 
4668 
4669   template<typename ConditionalOperator>
4670   bool HandleConditionalOperator(const ConditionalOperator *E) {
4671     bool BoolResult;
4672     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
4673       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
4674         CheckPotentialConstantConditional(E);
4675         return false;
4676       }
4677       if (Info.noteFailure()) {
4678         StmtVisitorTy::Visit(E->getTrueExpr());
4679         StmtVisitorTy::Visit(E->getFalseExpr());
4680       }
4681       return false;
4682     }
4683 
4684     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4685     return StmtVisitorTy::Visit(EvalExpr);
4686   }
4687 
4688 protected:
4689   EvalInfo &Info;
4690   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
4691   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4692 
4693   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4694     return Info.CCEDiag(E, D);
4695   }
4696 
4697   bool ZeroInitialization(const Expr *E) { return Error(E); }
4698 
4699 public:
4700   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4701 
4702   EvalInfo &getEvalInfo() { return Info; }
4703 
4704   /// Report an evaluation error. This should only be called when an error is
4705   /// first discovered. When propagating an error, just return false.
4706   bool Error(const Expr *E, diag::kind D) {
4707     Info.FFDiag(E, D);
4708     return false;
4709   }
4710   bool Error(const Expr *E) {
4711     return Error(E, diag::note_invalid_subexpr_in_const_expr);
4712   }
4713 
4714   bool VisitStmt(const Stmt *) {
4715     llvm_unreachable("Expression evaluator should not be called on stmts");
4716   }
4717   bool VisitExpr(const Expr *E) {
4718     return Error(E);
4719   }
4720 
4721   bool VisitParenExpr(const ParenExpr *E)
4722     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4723   bool VisitUnaryExtension(const UnaryOperator *E)
4724     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4725   bool VisitUnaryPlus(const UnaryOperator *E)
4726     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4727   bool VisitChooseExpr(const ChooseExpr *E)
4728     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
4729   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
4730     { return StmtVisitorTy::Visit(E->getResultExpr()); }
4731   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
4732     { return StmtVisitorTy::Visit(E->getReplacement()); }
4733   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
4734     TempVersionRAII RAII(*Info.CurrentCall);
4735     return StmtVisitorTy::Visit(E->getExpr());
4736   }
4737   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
4738     TempVersionRAII RAII(*Info.CurrentCall);
4739     // The initializer may not have been parsed yet, or might be erroneous.
4740     if (!E->getExpr())
4741       return Error(E);
4742     return StmtVisitorTy::Visit(E->getExpr());
4743   }
4744   // We cannot create any objects for which cleanups are required, so there is
4745   // nothing to do here; all cleanups must come from unevaluated subexpressions.
4746   bool VisitExprWithCleanups(const ExprWithCleanups *E)
4747     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4748 
4749   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
4750     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4751     return static_cast<Derived*>(this)->VisitCastExpr(E);
4752   }
4753   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
4754     CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4755     return static_cast<Derived*>(this)->VisitCastExpr(E);
4756   }
4757 
4758   bool VisitBinaryOperator(const BinaryOperator *E) {
4759     switch (E->getOpcode()) {
4760     default:
4761       return Error(E);
4762 
4763     case BO_Comma:
4764       VisitIgnoredValue(E->getLHS());
4765       return StmtVisitorTy::Visit(E->getRHS());
4766 
4767     case BO_PtrMemD:
4768     case BO_PtrMemI: {
4769       LValue Obj;
4770       if (!HandleMemberPointerAccess(Info, E, Obj))
4771         return false;
4772       APValue Result;
4773       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
4774         return false;
4775       return DerivedSuccess(Result, E);
4776     }
4777     }
4778   }
4779 
4780   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
4781     // Evaluate and cache the common expression. We treat it as a temporary,
4782     // even though it's not quite the same thing.
4783     if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
4784                   Info, E->getCommon()))
4785       return false;
4786 
4787     return HandleConditionalOperator(E);
4788   }
4789 
4790   bool VisitConditionalOperator(const ConditionalOperator *E) {
4791     bool IsBcpCall = false;
4792     // If the condition (ignoring parens) is a __builtin_constant_p call,
4793     // the result is a constant expression if it can be folded without
4794     // side-effects. This is an important GNU extension. See GCC PR38377
4795     // for discussion.
4796     if (const CallExpr *CallCE =
4797           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
4798       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
4799         IsBcpCall = true;
4800 
4801     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4802     // constant expression; we can't check whether it's potentially foldable.
4803     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
4804       return false;
4805 
4806     FoldConstant Fold(Info, IsBcpCall);
4807     if (!HandleConditionalOperator(E)) {
4808       Fold.keepDiagnostics();
4809       return false;
4810     }
4811 
4812     return true;
4813   }
4814 
4815   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
4816     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
4817       return DerivedSuccess(*Value, E);
4818 
4819     const Expr *Source = E->getSourceExpr();
4820     if (!Source)
4821       return Error(E);
4822     if (Source == E) { // sanity checking.
4823       assert(0 && "OpaqueValueExpr recursively refers to itself");
4824       return Error(E);
4825     }
4826     return StmtVisitorTy::Visit(Source);
4827   }
4828 
4829   bool VisitCallExpr(const CallExpr *E) {
4830     APValue Result;
4831     if (!handleCallExpr(E, Result, nullptr))
4832       return false;
4833     return DerivedSuccess(Result, E);
4834   }
4835 
4836   bool handleCallExpr(const CallExpr *E, APValue &Result,
4837                      const LValue *ResultSlot) {
4838     const Expr *Callee = E->getCallee()->IgnoreParens();
4839     QualType CalleeType = Callee->getType();
4840 
4841     const FunctionDecl *FD = nullptr;
4842     LValue *This = nullptr, ThisVal;
4843     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
4844     bool HasQualifier = false;
4845 
4846     // Extract function decl and 'this' pointer from the callee.
4847     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
4848       const ValueDecl *Member = nullptr;
4849       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4850         // Explicit bound member calls, such as x.f() or p->g();
4851         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
4852           return false;
4853         Member = ME->getMemberDecl();
4854         This = &ThisVal;
4855         HasQualifier = ME->hasQualifier();
4856       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4857         // Indirect bound member calls ('.*' or '->*').
4858         Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4859         if (!Member) return false;
4860         This = &ThisVal;
4861       } else
4862         return Error(Callee);
4863 
4864       FD = dyn_cast<FunctionDecl>(Member);
4865       if (!FD)
4866         return Error(Callee);
4867     } else if (CalleeType->isFunctionPointerType()) {
4868       LValue Call;
4869       if (!EvaluatePointer(Callee, Call, Info))
4870         return false;
4871 
4872       if (!Call.getLValueOffset().isZero())
4873         return Error(Callee);
4874       FD = dyn_cast_or_null<FunctionDecl>(
4875                              Call.getLValueBase().dyn_cast<const ValueDecl*>());
4876       if (!FD)
4877         return Error(Callee);
4878       // Don't call function pointers which have been cast to some other type.
4879       // Per DR (no number yet), the caller and callee can differ in noexcept.
4880       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4881         CalleeType->getPointeeType(), FD->getType())) {
4882         return Error(E);
4883       }
4884 
4885       // Overloaded operator calls to member functions are represented as normal
4886       // calls with '*this' as the first argument.
4887       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4888       if (MD && !MD->isStatic()) {
4889         // FIXME: When selecting an implicit conversion for an overloaded
4890         // operator delete, we sometimes try to evaluate calls to conversion
4891         // operators without a 'this' parameter!
4892         if (Args.empty())
4893           return Error(E);
4894 
4895         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4896           return false;
4897         This = &ThisVal;
4898         Args = Args.slice(1);
4899       } else if (MD && MD->isLambdaStaticInvoker()) {
4900         // Map the static invoker for the lambda back to the call operator.
4901         // Conveniently, we don't have to slice out the 'this' argument (as is
4902         // being done for the non-static case), since a static member function
4903         // doesn't have an implicit argument passed in.
4904         const CXXRecordDecl *ClosureClass = MD->getParent();
4905         assert(
4906             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4907             "Number of captures must be zero for conversion to function-ptr");
4908 
4909         const CXXMethodDecl *LambdaCallOp =
4910             ClosureClass->getLambdaCallOperator();
4911 
4912         // Set 'FD', the function that will be called below, to the call
4913         // operator.  If the closure object represents a generic lambda, find
4914         // the corresponding specialization of the call operator.
4915 
4916         if (ClosureClass->isGenericLambda()) {
4917           assert(MD->isFunctionTemplateSpecialization() &&
4918                  "A generic lambda's static-invoker function must be a "
4919                  "template specialization");
4920           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4921           FunctionTemplateDecl *CallOpTemplate =
4922               LambdaCallOp->getDescribedFunctionTemplate();
4923           void *InsertPos = nullptr;
4924           FunctionDecl *CorrespondingCallOpSpecialization =
4925               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4926           assert(CorrespondingCallOpSpecialization &&
4927                  "We must always have a function call operator specialization "
4928                  "that corresponds to our static invoker specialization");
4929           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4930         } else
4931           FD = LambdaCallOp;
4932       }
4933 
4934 
4935     } else
4936       return Error(E);
4937 
4938     if (This && !This->checkSubobject(Info, E, CSK_This))
4939       return false;
4940 
4941     // DR1358 allows virtual constexpr functions in some cases. Don't allow
4942     // calls to such functions in constant expressions.
4943     if (This && !HasQualifier &&
4944         isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4945       return Error(E, diag::note_constexpr_virtual_call);
4946 
4947     const FunctionDecl *Definition = nullptr;
4948     Stmt *Body = FD->getBody(Definition);
4949 
4950     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4951         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4952                             Result, ResultSlot))
4953       return false;
4954 
4955     return true;
4956   }
4957 
4958   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4959     return StmtVisitorTy::Visit(E->getInitializer());
4960   }
4961   bool VisitInitListExpr(const InitListExpr *E) {
4962     if (E->getNumInits() == 0)
4963       return DerivedZeroInitialization(E);
4964     if (E->getNumInits() == 1)
4965       return StmtVisitorTy::Visit(E->getInit(0));
4966     return Error(E);
4967   }
4968   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
4969     return DerivedZeroInitialization(E);
4970   }
4971   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
4972     return DerivedZeroInitialization(E);
4973   }
4974   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
4975     return DerivedZeroInitialization(E);
4976   }
4977 
4978   /// A member expression where the object is a prvalue is itself a prvalue.
4979   bool VisitMemberExpr(const MemberExpr *E) {
4980     assert(!E->isArrow() && "missing call to bound member function?");
4981 
4982     APValue Val;
4983     if (!Evaluate(Val, Info, E->getBase()))
4984       return false;
4985 
4986     QualType BaseTy = E->getBase()->getType();
4987 
4988     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
4989     if (!FD) return Error(E);
4990     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
4991     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4992            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4993 
4994     CompleteObject Obj(&Val, BaseTy, true);
4995     SubobjectDesignator Designator(BaseTy);
4996     Designator.addDeclUnchecked(FD);
4997 
4998     APValue Result;
4999     return extractSubobject(Info, E, Obj, Designator, Result) &&
5000            DerivedSuccess(Result, E);
5001   }
5002 
5003   bool VisitCastExpr(const CastExpr *E) {
5004     switch (E->getCastKind()) {
5005     default:
5006       break;
5007 
5008     case CK_AtomicToNonAtomic: {
5009       APValue AtomicVal;
5010       // This does not need to be done in place even for class/array types:
5011       // atomic-to-non-atomic conversion implies copying the object
5012       // representation.
5013       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
5014         return false;
5015       return DerivedSuccess(AtomicVal, E);
5016     }
5017 
5018     case CK_NoOp:
5019     case CK_UserDefinedConversion:
5020       return StmtVisitorTy::Visit(E->getSubExpr());
5021 
5022     case CK_LValueToRValue: {
5023       LValue LVal;
5024       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
5025         return false;
5026       APValue RVal;
5027       // Note, we use the subexpression's type in order to retain cv-qualifiers.
5028       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5029                                           LVal, RVal))
5030         return false;
5031       return DerivedSuccess(RVal, E);
5032     }
5033     }
5034 
5035     return Error(E);
5036   }
5037 
5038   bool VisitUnaryPostInc(const UnaryOperator *UO) {
5039     return VisitUnaryPostIncDec(UO);
5040   }
5041   bool VisitUnaryPostDec(const UnaryOperator *UO) {
5042     return VisitUnaryPostIncDec(UO);
5043   }
5044   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
5045     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5046       return Error(UO);
5047 
5048     LValue LVal;
5049     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
5050       return false;
5051     APValue RVal;
5052     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
5053                       UO->isIncrementOp(), &RVal))
5054       return false;
5055     return DerivedSuccess(RVal, UO);
5056   }
5057 
5058   bool VisitStmtExpr(const StmtExpr *E) {
5059     // We will have checked the full-expressions inside the statement expression
5060     // when they were completed, and don't need to check them again now.
5061     if (Info.checkingForOverflow())
5062       return Error(E);
5063 
5064     BlockScopeRAII Scope(Info);
5065     const CompoundStmt *CS = E->getSubStmt();
5066     if (CS->body_empty())
5067       return true;
5068 
5069     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
5070                                            BE = CS->body_end();
5071          /**/; ++BI) {
5072       if (BI + 1 == BE) {
5073         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
5074         if (!FinalExpr) {
5075           Info.FFDiag((*BI)->getBeginLoc(),
5076                       diag::note_constexpr_stmt_expr_unsupported);
5077           return false;
5078         }
5079         return this->Visit(FinalExpr);
5080       }
5081 
5082       APValue ReturnValue;
5083       StmtResult Result = { ReturnValue, nullptr };
5084       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
5085       if (ESR != ESR_Succeeded) {
5086         // FIXME: If the statement-expression terminated due to 'return',
5087         // 'break', or 'continue', it would be nice to propagate that to
5088         // the outer statement evaluation rather than bailing out.
5089         if (ESR != ESR_Failed)
5090           Info.FFDiag((*BI)->getBeginLoc(),
5091                       diag::note_constexpr_stmt_expr_unsupported);
5092         return false;
5093       }
5094     }
5095 
5096     llvm_unreachable("Return from function from the loop above.");
5097   }
5098 
5099   /// Visit a value which is evaluated, but whose value is ignored.
5100   void VisitIgnoredValue(const Expr *E) {
5101     EvaluateIgnoredValue(Info, E);
5102   }
5103 
5104   /// Potentially visit a MemberExpr's base expression.
5105   void VisitIgnoredBaseExpression(const Expr *E) {
5106     // While MSVC doesn't evaluate the base expression, it does diagnose the
5107     // presence of side-effecting behavior.
5108     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
5109       return;
5110     VisitIgnoredValue(E);
5111   }
5112 };
5113 
5114 } // namespace
5115 
5116 //===----------------------------------------------------------------------===//
5117 // Common base class for lvalue and temporary evaluation.
5118 //===----------------------------------------------------------------------===//
5119 namespace {
5120 template<class Derived>
5121 class LValueExprEvaluatorBase
5122   : public ExprEvaluatorBase<Derived> {
5123 protected:
5124   LValue &Result;
5125   bool InvalidBaseOK;
5126   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
5127   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
5128 
5129   bool Success(APValue::LValueBase B) {
5130     Result.set(B);
5131     return true;
5132   }
5133 
5134   bool evaluatePointer(const Expr *E, LValue &Result) {
5135     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
5136   }
5137 
5138 public:
5139   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5140       : ExprEvaluatorBaseTy(Info), Result(Result),
5141         InvalidBaseOK(InvalidBaseOK) {}
5142 
5143   bool Success(const APValue &V, const Expr *E) {
5144     Result.setFrom(this->Info.Ctx, V);
5145     return true;
5146   }
5147 
5148   bool VisitMemberExpr(const MemberExpr *E) {
5149     // Handle non-static data members.
5150     QualType BaseTy;
5151     bool EvalOK;
5152     if (E->isArrow()) {
5153       EvalOK = evaluatePointer(E->getBase(), Result);
5154       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
5155     } else if (E->getBase()->isRValue()) {
5156       assert(E->getBase()->getType()->isRecordType());
5157       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
5158       BaseTy = E->getBase()->getType();
5159     } else {
5160       EvalOK = this->Visit(E->getBase());
5161       BaseTy = E->getBase()->getType();
5162     }
5163     if (!EvalOK) {
5164       if (!InvalidBaseOK)
5165         return false;
5166       Result.setInvalid(E);
5167       return true;
5168     }
5169 
5170     const ValueDecl *MD = E->getMemberDecl();
5171     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5172       assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5173              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5174       (void)BaseTy;
5175       if (!HandleLValueMember(this->Info, E, Result, FD))
5176         return false;
5177     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
5178       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5179         return false;
5180     } else
5181       return this->Error(E);
5182 
5183     if (MD->getType()->isReferenceType()) {
5184       APValue RefValue;
5185       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
5186                                           RefValue))
5187         return false;
5188       return Success(RefValue, E);
5189     }
5190     return true;
5191   }
5192 
5193   bool VisitBinaryOperator(const BinaryOperator *E) {
5194     switch (E->getOpcode()) {
5195     default:
5196       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5197 
5198     case BO_PtrMemD:
5199     case BO_PtrMemI:
5200       return HandleMemberPointerAccess(this->Info, E, Result);
5201     }
5202   }
5203 
5204   bool VisitCastExpr(const CastExpr *E) {
5205     switch (E->getCastKind()) {
5206     default:
5207       return ExprEvaluatorBaseTy::VisitCastExpr(E);
5208 
5209     case CK_DerivedToBase:
5210     case CK_UncheckedDerivedToBase:
5211       if (!this->Visit(E->getSubExpr()))
5212         return false;
5213 
5214       // Now figure out the necessary offset to add to the base LV to get from
5215       // the derived class to the base class.
5216       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5217                                   Result);
5218     }
5219   }
5220 };
5221 }
5222 
5223 //===----------------------------------------------------------------------===//
5224 // LValue Evaluation
5225 //
5226 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5227 // function designators (in C), decl references to void objects (in C), and
5228 // temporaries (if building with -Wno-address-of-temporary).
5229 //
5230 // LValue evaluation produces values comprising a base expression of one of the
5231 // following types:
5232 // - Declarations
5233 //  * VarDecl
5234 //  * FunctionDecl
5235 // - Literals
5236 //  * CompoundLiteralExpr in C (and in global scope in C++)
5237 //  * StringLiteral
5238 //  * CXXTypeidExpr
5239 //  * PredefinedExpr
5240 //  * ObjCStringLiteralExpr
5241 //  * ObjCEncodeExpr
5242 //  * AddrLabelExpr
5243 //  * BlockExpr
5244 //  * CallExpr for a MakeStringConstant builtin
5245 // - Locals and temporaries
5246 //  * MaterializeTemporaryExpr
5247 //  * Any Expr, with a CallIndex indicating the function in which the temporary
5248 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
5249 //    from the AST (FIXME).
5250 //  * A MaterializeTemporaryExpr that has static storage duration, with no
5251 //    CallIndex, for a lifetime-extended temporary.
5252 // plus an offset in bytes.
5253 //===----------------------------------------------------------------------===//
5254 namespace {
5255 class LValueExprEvaluator
5256   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
5257 public:
5258   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5259     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
5260 
5261   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
5262   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
5263 
5264   bool VisitDeclRefExpr(const DeclRefExpr *E);
5265   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
5266   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
5267   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5268   bool VisitMemberExpr(const MemberExpr *E);
5269   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5270   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
5271   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
5272   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
5273   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5274   bool VisitUnaryDeref(const UnaryOperator *E);
5275   bool VisitUnaryReal(const UnaryOperator *E);
5276   bool VisitUnaryImag(const UnaryOperator *E);
5277   bool VisitUnaryPreInc(const UnaryOperator *UO) {
5278     return VisitUnaryPreIncDec(UO);
5279   }
5280   bool VisitUnaryPreDec(const UnaryOperator *UO) {
5281     return VisitUnaryPreIncDec(UO);
5282   }
5283   bool VisitBinAssign(const BinaryOperator *BO);
5284   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
5285 
5286   bool VisitCastExpr(const CastExpr *E) {
5287     switch (E->getCastKind()) {
5288     default:
5289       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5290 
5291     case CK_LValueBitCast:
5292       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5293       if (!Visit(E->getSubExpr()))
5294         return false;
5295       Result.Designator.setInvalid();
5296       return true;
5297 
5298     case CK_BaseToDerived:
5299       if (!Visit(E->getSubExpr()))
5300         return false;
5301       return HandleBaseToDerivedCast(Info, E, Result);
5302     }
5303   }
5304 };
5305 } // end anonymous namespace
5306 
5307 /// Evaluate an expression as an lvalue. This can be legitimately called on
5308 /// expressions which are not glvalues, in three cases:
5309 ///  * function designators in C, and
5310 ///  * "extern void" objects
5311 ///  * @selector() expressions in Objective-C
5312 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5313                            bool InvalidBaseOK) {
5314   assert(E->isGLValue() || E->getType()->isFunctionType() ||
5315          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
5316   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5317 }
5318 
5319 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
5320   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
5321     return Success(FD);
5322   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
5323     return VisitVarDecl(E, VD);
5324   if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
5325     return Visit(BD->getBinding());
5326   return Error(E);
5327 }
5328 
5329 
5330 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
5331 
5332   // If we are within a lambda's call operator, check whether the 'VD' referred
5333   // to within 'E' actually represents a lambda-capture that maps to a
5334   // data-member/field within the closure object, and if so, evaluate to the
5335   // field or what the field refers to.
5336   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
5337       isa<DeclRefExpr>(E) &&
5338       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
5339     // We don't always have a complete capture-map when checking or inferring if
5340     // the function call operator meets the requirements of a constexpr function
5341     // - but we don't need to evaluate the captures to determine constexprness
5342     // (dcl.constexpr C++17).
5343     if (Info.checkingPotentialConstantExpression())
5344       return false;
5345 
5346     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5347       // Start with 'Result' referring to the complete closure object...
5348       Result = *Info.CurrentCall->This;
5349       // ... then update it to refer to the field of the closure object
5350       // that represents the capture.
5351       if (!HandleLValueMember(Info, E, Result, FD))
5352         return false;
5353       // And if the field is of reference type, update 'Result' to refer to what
5354       // the field refers to.
5355       if (FD->getType()->isReferenceType()) {
5356         APValue RVal;
5357         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5358                                             RVal))
5359           return false;
5360         Result.setFrom(Info.Ctx, RVal);
5361       }
5362       return true;
5363     }
5364   }
5365   CallStackFrame *Frame = nullptr;
5366   if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5367     // Only if a local variable was declared in the function currently being
5368     // evaluated, do we expect to be able to find its value in the current
5369     // frame. (Otherwise it was likely declared in an enclosing context and
5370     // could either have a valid evaluatable value (for e.g. a constexpr
5371     // variable) or be ill-formed (and trigger an appropriate evaluation
5372     // diagnostic)).
5373     if (Info.CurrentCall->Callee &&
5374         Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5375       Frame = Info.CurrentCall;
5376     }
5377   }
5378 
5379   if (!VD->getType()->isReferenceType()) {
5380     if (Frame) {
5381       Result.set({VD, Frame->Index,
5382                   Info.CurrentCall->getCurrentTemporaryVersion(VD)});
5383       return true;
5384     }
5385     return Success(VD);
5386   }
5387 
5388   APValue *V;
5389   if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
5390     return false;
5391   if (V->isUninit()) {
5392     if (!Info.checkingPotentialConstantExpression())
5393       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
5394     return false;
5395   }
5396   return Success(*V, E);
5397 }
5398 
5399 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5400     const MaterializeTemporaryExpr *E) {
5401   // Walk through the expression to find the materialized temporary itself.
5402   SmallVector<const Expr *, 2> CommaLHSs;
5403   SmallVector<SubobjectAdjustment, 2> Adjustments;
5404   const Expr *Inner = E->GetTemporaryExpr()->
5405       skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
5406 
5407   // If we passed any comma operators, evaluate their LHSs.
5408   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5409     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5410       return false;
5411 
5412   // A materialized temporary with static storage duration can appear within the
5413   // result of a constant expression evaluation, so we need to preserve its
5414   // value for use outside this evaluation.
5415   APValue *Value;
5416   if (E->getStorageDuration() == SD_Static) {
5417     Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
5418     *Value = APValue();
5419     Result.set(E);
5420   } else {
5421     Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
5422                              *Info.CurrentCall);
5423   }
5424 
5425   QualType Type = Inner->getType();
5426 
5427   // Materialize the temporary itself.
5428   if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5429       (E->getStorageDuration() == SD_Static &&
5430        !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5431     *Value = APValue();
5432     return false;
5433   }
5434 
5435   // Adjust our lvalue to refer to the desired subobject.
5436   for (unsigned I = Adjustments.size(); I != 0; /**/) {
5437     --I;
5438     switch (Adjustments[I].Kind) {
5439     case SubobjectAdjustment::DerivedToBaseAdjustment:
5440       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5441                                 Type, Result))
5442         return false;
5443       Type = Adjustments[I].DerivedToBase.BasePath->getType();
5444       break;
5445 
5446     case SubobjectAdjustment::FieldAdjustment:
5447       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5448         return false;
5449       Type = Adjustments[I].Field->getType();
5450       break;
5451 
5452     case SubobjectAdjustment::MemberPointerAdjustment:
5453       if (!HandleMemberPointerAccess(this->Info, Type, Result,
5454                                      Adjustments[I].Ptr.RHS))
5455         return false;
5456       Type = Adjustments[I].Ptr.MPT->getPointeeType();
5457       break;
5458     }
5459   }
5460 
5461   return true;
5462 }
5463 
5464 bool
5465 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
5466   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5467          "lvalue compound literal in c++?");
5468   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5469   // only see this when folding in C, so there's no standard to follow here.
5470   return Success(E);
5471 }
5472 
5473 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
5474   if (!E->isPotentiallyEvaluated())
5475     return Success(E);
5476 
5477   Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
5478     << E->getExprOperand()->getType()
5479     << E->getExprOperand()->getSourceRange();
5480   return false;
5481 }
5482 
5483 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5484   return Success(E);
5485 }
5486 
5487 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
5488   // Handle static data members.
5489   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
5490     VisitIgnoredBaseExpression(E->getBase());
5491     return VisitVarDecl(E, VD);
5492   }
5493 
5494   // Handle static member functions.
5495   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5496     if (MD->isStatic()) {
5497       VisitIgnoredBaseExpression(E->getBase());
5498       return Success(MD);
5499     }
5500   }
5501 
5502   // Handle non-static data members.
5503   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
5504 }
5505 
5506 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
5507   // FIXME: Deal with vectors as array subscript bases.
5508   if (E->getBase()->getType()->isVectorType())
5509     return Error(E);
5510 
5511   bool Success = true;
5512   if (!evaluatePointer(E->getBase(), Result)) {
5513     if (!Info.noteFailure())
5514       return false;
5515     Success = false;
5516   }
5517 
5518   APSInt Index;
5519   if (!EvaluateInteger(E->getIdx(), Index, Info))
5520     return false;
5521 
5522   return Success &&
5523          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
5524 }
5525 
5526 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
5527   return evaluatePointer(E->getSubExpr(), Result);
5528 }
5529 
5530 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5531   if (!Visit(E->getSubExpr()))
5532     return false;
5533   // __real is a no-op on scalar lvalues.
5534   if (E->getSubExpr()->getType()->isAnyComplexType())
5535     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5536   return true;
5537 }
5538 
5539 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5540   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5541          "lvalue __imag__ on scalar?");
5542   if (!Visit(E->getSubExpr()))
5543     return false;
5544   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5545   return true;
5546 }
5547 
5548 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
5549   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5550     return Error(UO);
5551 
5552   if (!this->Visit(UO->getSubExpr()))
5553     return false;
5554 
5555   return handleIncDec(
5556       this->Info, UO, Result, UO->getSubExpr()->getType(),
5557       UO->isIncrementOp(), nullptr);
5558 }
5559 
5560 bool LValueExprEvaluator::VisitCompoundAssignOperator(
5561     const CompoundAssignOperator *CAO) {
5562   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5563     return Error(CAO);
5564 
5565   APValue RHS;
5566 
5567   // The overall lvalue result is the result of evaluating the LHS.
5568   if (!this->Visit(CAO->getLHS())) {
5569     if (Info.noteFailure())
5570       Evaluate(RHS, this->Info, CAO->getRHS());
5571     return false;
5572   }
5573 
5574   if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5575     return false;
5576 
5577   return handleCompoundAssignment(
5578       this->Info, CAO,
5579       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5580       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
5581 }
5582 
5583 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
5584   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5585     return Error(E);
5586 
5587   APValue NewVal;
5588 
5589   if (!this->Visit(E->getLHS())) {
5590     if (Info.noteFailure())
5591       Evaluate(NewVal, this->Info, E->getRHS());
5592     return false;
5593   }
5594 
5595   if (!Evaluate(NewVal, this->Info, E->getRHS()))
5596     return false;
5597 
5598   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
5599                           NewVal);
5600 }
5601 
5602 //===----------------------------------------------------------------------===//
5603 // Pointer Evaluation
5604 //===----------------------------------------------------------------------===//
5605 
5606 /// Attempts to compute the number of bytes available at the pointer
5607 /// returned by a function with the alloc_size attribute. Returns true if we
5608 /// were successful. Places an unsigned number into `Result`.
5609 ///
5610 /// This expects the given CallExpr to be a call to a function with an
5611 /// alloc_size attribute.
5612 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5613                                             const CallExpr *Call,
5614                                             llvm::APInt &Result) {
5615   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5616 
5617   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
5618   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
5619   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5620   if (Call->getNumArgs() <= SizeArgNo)
5621     return false;
5622 
5623   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5624     if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5625       return false;
5626     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5627       return false;
5628     Into = Into.zextOrSelf(BitsInSizeT);
5629     return true;
5630   };
5631 
5632   APSInt SizeOfElem;
5633   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5634     return false;
5635 
5636   if (!AllocSize->getNumElemsParam().isValid()) {
5637     Result = std::move(SizeOfElem);
5638     return true;
5639   }
5640 
5641   APSInt NumberOfElems;
5642   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
5643   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5644     return false;
5645 
5646   bool Overflow;
5647   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5648   if (Overflow)
5649     return false;
5650 
5651   Result = std::move(BytesAvailable);
5652   return true;
5653 }
5654 
5655 /// Convenience function. LVal's base must be a call to an alloc_size
5656 /// function.
5657 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5658                                             const LValue &LVal,
5659                                             llvm::APInt &Result) {
5660   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5661          "Can't get the size of a non alloc_size function");
5662   const auto *Base = LVal.getLValueBase().get<const Expr *>();
5663   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5664   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5665 }
5666 
5667 /// Attempts to evaluate the given LValueBase as the result of a call to
5668 /// a function with the alloc_size attribute. If it was possible to do so, this
5669 /// function will return true, make Result's Base point to said function call,
5670 /// and mark Result's Base as invalid.
5671 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5672                                       LValue &Result) {
5673   if (Base.isNull())
5674     return false;
5675 
5676   // Because we do no form of static analysis, we only support const variables.
5677   //
5678   // Additionally, we can't support parameters, nor can we support static
5679   // variables (in the latter case, use-before-assign isn't UB; in the former,
5680   // we have no clue what they'll be assigned to).
5681   const auto *VD =
5682       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5683   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5684     return false;
5685 
5686   const Expr *Init = VD->getAnyInitializer();
5687   if (!Init)
5688     return false;
5689 
5690   const Expr *E = Init->IgnoreParens();
5691   if (!tryUnwrapAllocSizeCall(E))
5692     return false;
5693 
5694   // Store E instead of E unwrapped so that the type of the LValue's base is
5695   // what the user wanted.
5696   Result.setInvalid(E);
5697 
5698   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5699   Result.addUnsizedArray(Info, E, Pointee);
5700   return true;
5701 }
5702 
5703 namespace {
5704 class PointerExprEvaluator
5705   : public ExprEvaluatorBase<PointerExprEvaluator> {
5706   LValue &Result;
5707   bool InvalidBaseOK;
5708 
5709   bool Success(const Expr *E) {
5710     Result.set(E);
5711     return true;
5712   }
5713 
5714   bool evaluateLValue(const Expr *E, LValue &Result) {
5715     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5716   }
5717 
5718   bool evaluatePointer(const Expr *E, LValue &Result) {
5719     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5720   }
5721 
5722   bool visitNonBuiltinCallExpr(const CallExpr *E);
5723 public:
5724 
5725   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5726       : ExprEvaluatorBaseTy(info), Result(Result),
5727         InvalidBaseOK(InvalidBaseOK) {}
5728 
5729   bool Success(const APValue &V, const Expr *E) {
5730     Result.setFrom(Info.Ctx, V);
5731     return true;
5732   }
5733   bool ZeroInitialization(const Expr *E) {
5734     auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5735     Result.setNull(E->getType(), TargetVal);
5736     return true;
5737   }
5738 
5739   bool VisitBinaryOperator(const BinaryOperator *E);
5740   bool VisitCastExpr(const CastExpr* E);
5741   bool VisitUnaryAddrOf(const UnaryOperator *E);
5742   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
5743       { return Success(E); }
5744   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5745     if (Info.noteFailure())
5746       EvaluateIgnoredValue(Info, E->getSubExpr());
5747     return Error(E);
5748   }
5749   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
5750       { return Success(E); }
5751   bool VisitCallExpr(const CallExpr *E);
5752   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
5753   bool VisitBlockExpr(const BlockExpr *E) {
5754     if (!E->getBlockDecl()->hasCaptures())
5755       return Success(E);
5756     return Error(E);
5757   }
5758   bool VisitCXXThisExpr(const CXXThisExpr *E) {
5759     // Can't look at 'this' when checking a potential constant expression.
5760     if (Info.checkingPotentialConstantExpression())
5761       return false;
5762     if (!Info.CurrentCall->This) {
5763       if (Info.getLangOpts().CPlusPlus11)
5764         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
5765       else
5766         Info.FFDiag(E);
5767       return false;
5768     }
5769     Result = *Info.CurrentCall->This;
5770     // If we are inside a lambda's call operator, the 'this' expression refers
5771     // to the enclosing '*this' object (either by value or reference) which is
5772     // either copied into the closure object's field that represents the '*this'
5773     // or refers to '*this'.
5774     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5775       // Update 'Result' to refer to the data member/field of the closure object
5776       // that represents the '*this' capture.
5777       if (!HandleLValueMember(Info, E, Result,
5778                              Info.CurrentCall->LambdaThisCaptureField))
5779         return false;
5780       // If we captured '*this' by reference, replace the field with its referent.
5781       if (Info.CurrentCall->LambdaThisCaptureField->getType()
5782               ->isPointerType()) {
5783         APValue RVal;
5784         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5785                                             RVal))
5786           return false;
5787 
5788         Result.setFrom(Info.Ctx, RVal);
5789       }
5790     }
5791     return true;
5792   }
5793 
5794   // FIXME: Missing: @protocol, @selector
5795 };
5796 } // end anonymous namespace
5797 
5798 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5799                             bool InvalidBaseOK) {
5800   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
5801   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5802 }
5803 
5804 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5805   if (E->getOpcode() != BO_Add &&
5806       E->getOpcode() != BO_Sub)
5807     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5808 
5809   const Expr *PExp = E->getLHS();
5810   const Expr *IExp = E->getRHS();
5811   if (IExp->getType()->isPointerType())
5812     std::swap(PExp, IExp);
5813 
5814   bool EvalPtrOK = evaluatePointer(PExp, Result);
5815   if (!EvalPtrOK && !Info.noteFailure())
5816     return false;
5817 
5818   llvm::APSInt Offset;
5819   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
5820     return false;
5821 
5822   if (E->getOpcode() == BO_Sub)
5823     negateAsSigned(Offset);
5824 
5825   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
5826   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
5827 }
5828 
5829 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5830   return evaluateLValue(E->getSubExpr(), Result);
5831 }
5832 
5833 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5834   const Expr *SubExpr = E->getSubExpr();
5835 
5836   switch (E->getCastKind()) {
5837   default:
5838     break;
5839 
5840   case CK_BitCast:
5841   case CK_CPointerToObjCPointerCast:
5842   case CK_BlockPointerToObjCPointerCast:
5843   case CK_AnyPointerToBlockPointerCast:
5844   case CK_AddressSpaceConversion:
5845     if (!Visit(SubExpr))
5846       return false;
5847     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5848     // permitted in constant expressions in C++11. Bitcasts from cv void* are
5849     // also static_casts, but we disallow them as a resolution to DR1312.
5850     if (!E->getType()->isVoidPointerType()) {
5851       Result.Designator.setInvalid();
5852       if (SubExpr->getType()->isVoidPointerType())
5853         CCEDiag(E, diag::note_constexpr_invalid_cast)
5854           << 3 << SubExpr->getType();
5855       else
5856         CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5857     }
5858     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5859       ZeroInitialization(E);
5860     return true;
5861 
5862   case CK_DerivedToBase:
5863   case CK_UncheckedDerivedToBase:
5864     if (!evaluatePointer(E->getSubExpr(), Result))
5865       return false;
5866     if (!Result.Base && Result.Offset.isZero())
5867       return true;
5868 
5869     // Now figure out the necessary offset to add to the base LV to get from
5870     // the derived class to the base class.
5871     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5872                                   castAs<PointerType>()->getPointeeType(),
5873                                 Result);
5874 
5875   case CK_BaseToDerived:
5876     if (!Visit(E->getSubExpr()))
5877       return false;
5878     if (!Result.Base && Result.Offset.isZero())
5879       return true;
5880     return HandleBaseToDerivedCast(Info, E, Result);
5881 
5882   case CK_NullToPointer:
5883     VisitIgnoredValue(E->getSubExpr());
5884     return ZeroInitialization(E);
5885 
5886   case CK_IntegralToPointer: {
5887     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5888 
5889     APValue Value;
5890     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
5891       break;
5892 
5893     if (Value.isInt()) {
5894       unsigned Size = Info.Ctx.getTypeSize(E->getType());
5895       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
5896       Result.Base = (Expr*)nullptr;
5897       Result.InvalidBase = false;
5898       Result.Offset = CharUnits::fromQuantity(N);
5899       Result.Designator.setInvalid();
5900       Result.IsNullPtr = false;
5901       return true;
5902     } else {
5903       // Cast is of an lvalue, no need to change value.
5904       Result.setFrom(Info.Ctx, Value);
5905       return true;
5906     }
5907   }
5908 
5909   case CK_ArrayToPointerDecay: {
5910     if (SubExpr->isGLValue()) {
5911       if (!evaluateLValue(SubExpr, Result))
5912         return false;
5913     } else {
5914       APValue &Value = createTemporary(SubExpr, false, Result,
5915                                        *Info.CurrentCall);
5916       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
5917         return false;
5918     }
5919     // The result is a pointer to the first element of the array.
5920     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5921     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
5922       Result.addArray(Info, E, CAT);
5923     else
5924       Result.addUnsizedArray(Info, E, AT->getElementType());
5925     return true;
5926   }
5927 
5928   case CK_FunctionToPointerDecay:
5929     return evaluateLValue(SubExpr, Result);
5930 
5931   case CK_LValueToRValue: {
5932     LValue LVal;
5933     if (!evaluateLValue(E->getSubExpr(), LVal))
5934       return false;
5935 
5936     APValue RVal;
5937     // Note, we use the subexpression's type in order to retain cv-qualifiers.
5938     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5939                                         LVal, RVal))
5940       return InvalidBaseOK &&
5941              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
5942     return Success(RVal, E);
5943   }
5944   }
5945 
5946   return ExprEvaluatorBaseTy::VisitCastExpr(E);
5947 }
5948 
5949 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5950   // C++ [expr.alignof]p3:
5951   //     When alignof is applied to a reference type, the result is the
5952   //     alignment of the referenced type.
5953   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5954     T = Ref->getPointeeType();
5955 
5956   // __alignof is defined to return the preferred alignment.
5957   if (T.getQualifiers().hasUnaligned())
5958     return CharUnits::One();
5959   return Info.Ctx.toCharUnitsFromBits(
5960     Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5961 }
5962 
5963 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5964   E = E->IgnoreParens();
5965 
5966   // The kinds of expressions that we have special-case logic here for
5967   // should be kept up to date with the special checks for those
5968   // expressions in Sema.
5969 
5970   // alignof decl is always accepted, even if it doesn't make sense: we default
5971   // to 1 in those cases.
5972   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5973     return Info.Ctx.getDeclAlign(DRE->getDecl(),
5974                                  /*RefAsPointee*/true);
5975 
5976   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5977     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5978                                  /*RefAsPointee*/true);
5979 
5980   return GetAlignOfType(Info, E->getType());
5981 }
5982 
5983 // To be clear: this happily visits unsupported builtins. Better name welcomed.
5984 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5985   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5986     return true;
5987 
5988   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
5989     return false;
5990 
5991   Result.setInvalid(E);
5992   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
5993   Result.addUnsizedArray(Info, E, PointeeTy);
5994   return true;
5995 }
5996 
5997 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
5998   if (IsStringLiteralCall(E))
5999     return Success(E);
6000 
6001   if (unsigned BuiltinOp = E->getBuiltinCallee())
6002     return VisitBuiltinCallExpr(E, BuiltinOp);
6003 
6004   return visitNonBuiltinCallExpr(E);
6005 }
6006 
6007 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
6008                                                 unsigned BuiltinOp) {
6009   switch (BuiltinOp) {
6010   case Builtin::BI__builtin_addressof:
6011     return evaluateLValue(E->getArg(0), Result);
6012   case Builtin::BI__builtin_assume_aligned: {
6013     // We need to be very careful here because: if the pointer does not have the
6014     // asserted alignment, then the behavior is undefined, and undefined
6015     // behavior is non-constant.
6016     if (!evaluatePointer(E->getArg(0), Result))
6017       return false;
6018 
6019     LValue OffsetResult(Result);
6020     APSInt Alignment;
6021     if (!EvaluateInteger(E->getArg(1), Alignment, Info))
6022       return false;
6023     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
6024 
6025     if (E->getNumArgs() > 2) {
6026       APSInt Offset;
6027       if (!EvaluateInteger(E->getArg(2), Offset, Info))
6028         return false;
6029 
6030       int64_t AdditionalOffset = -Offset.getZExtValue();
6031       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
6032     }
6033 
6034     // If there is a base object, then it must have the correct alignment.
6035     if (OffsetResult.Base) {
6036       CharUnits BaseAlignment;
6037       if (const ValueDecl *VD =
6038           OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
6039         BaseAlignment = Info.Ctx.getDeclAlign(VD);
6040       } else {
6041         BaseAlignment =
6042           GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
6043       }
6044 
6045       if (BaseAlignment < Align) {
6046         Result.Designator.setInvalid();
6047         // FIXME: Add support to Diagnostic for long / long long.
6048         CCEDiag(E->getArg(0),
6049                 diag::note_constexpr_baa_insufficient_alignment) << 0
6050           << (unsigned)BaseAlignment.getQuantity()
6051           << (unsigned)Align.getQuantity();
6052         return false;
6053       }
6054     }
6055 
6056     // The offset must also have the correct alignment.
6057     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
6058       Result.Designator.setInvalid();
6059 
6060       (OffsetResult.Base
6061            ? CCEDiag(E->getArg(0),
6062                      diag::note_constexpr_baa_insufficient_alignment) << 1
6063            : CCEDiag(E->getArg(0),
6064                      diag::note_constexpr_baa_value_insufficient_alignment))
6065         << (int)OffsetResult.Offset.getQuantity()
6066         << (unsigned)Align.getQuantity();
6067       return false;
6068     }
6069 
6070     return true;
6071   }
6072 
6073   case Builtin::BIstrchr:
6074   case Builtin::BIwcschr:
6075   case Builtin::BImemchr:
6076   case Builtin::BIwmemchr:
6077     if (Info.getLangOpts().CPlusPlus11)
6078       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6079         << /*isConstexpr*/0 << /*isConstructor*/0
6080         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
6081     else
6082       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6083     LLVM_FALLTHROUGH;
6084   case Builtin::BI__builtin_strchr:
6085   case Builtin::BI__builtin_wcschr:
6086   case Builtin::BI__builtin_memchr:
6087   case Builtin::BI__builtin_char_memchr:
6088   case Builtin::BI__builtin_wmemchr: {
6089     if (!Visit(E->getArg(0)))
6090       return false;
6091     APSInt Desired;
6092     if (!EvaluateInteger(E->getArg(1), Desired, Info))
6093       return false;
6094     uint64_t MaxLength = uint64_t(-1);
6095     if (BuiltinOp != Builtin::BIstrchr &&
6096         BuiltinOp != Builtin::BIwcschr &&
6097         BuiltinOp != Builtin::BI__builtin_strchr &&
6098         BuiltinOp != Builtin::BI__builtin_wcschr) {
6099       APSInt N;
6100       if (!EvaluateInteger(E->getArg(2), N, Info))
6101         return false;
6102       MaxLength = N.getExtValue();
6103     }
6104 
6105     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6106 
6107     // Figure out what value we're actually looking for (after converting to
6108     // the corresponding unsigned type if necessary).
6109     uint64_t DesiredVal;
6110     bool StopAtNull = false;
6111     switch (BuiltinOp) {
6112     case Builtin::BIstrchr:
6113     case Builtin::BI__builtin_strchr:
6114       // strchr compares directly to the passed integer, and therefore
6115       // always fails if given an int that is not a char.
6116       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
6117                                                   E->getArg(1)->getType(),
6118                                                   Desired),
6119                                Desired))
6120         return ZeroInitialization(E);
6121       StopAtNull = true;
6122       LLVM_FALLTHROUGH;
6123     case Builtin::BImemchr:
6124     case Builtin::BI__builtin_memchr:
6125     case Builtin::BI__builtin_char_memchr:
6126       // memchr compares by converting both sides to unsigned char. That's also
6127       // correct for strchr if we get this far (to cope with plain char being
6128       // unsigned in the strchr case).
6129       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
6130       break;
6131 
6132     case Builtin::BIwcschr:
6133     case Builtin::BI__builtin_wcschr:
6134       StopAtNull = true;
6135       LLVM_FALLTHROUGH;
6136     case Builtin::BIwmemchr:
6137     case Builtin::BI__builtin_wmemchr:
6138       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
6139       DesiredVal = Desired.getZExtValue();
6140       break;
6141     }
6142 
6143     for (; MaxLength; --MaxLength) {
6144       APValue Char;
6145       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
6146           !Char.isInt())
6147         return false;
6148       if (Char.getInt().getZExtValue() == DesiredVal)
6149         return true;
6150       if (StopAtNull && !Char.getInt())
6151         break;
6152       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
6153         return false;
6154     }
6155     // Not found: return nullptr.
6156     return ZeroInitialization(E);
6157   }
6158 
6159   case Builtin::BImemcpy:
6160   case Builtin::BImemmove:
6161   case Builtin::BIwmemcpy:
6162   case Builtin::BIwmemmove:
6163     if (Info.getLangOpts().CPlusPlus11)
6164       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6165         << /*isConstexpr*/0 << /*isConstructor*/0
6166         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
6167     else
6168       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6169     LLVM_FALLTHROUGH;
6170   case Builtin::BI__builtin_memcpy:
6171   case Builtin::BI__builtin_memmove:
6172   case Builtin::BI__builtin_wmemcpy:
6173   case Builtin::BI__builtin_wmemmove: {
6174     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
6175                  BuiltinOp == Builtin::BIwmemmove ||
6176                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
6177                  BuiltinOp == Builtin::BI__builtin_wmemmove;
6178     bool Move = BuiltinOp == Builtin::BImemmove ||
6179                 BuiltinOp == Builtin::BIwmemmove ||
6180                 BuiltinOp == Builtin::BI__builtin_memmove ||
6181                 BuiltinOp == Builtin::BI__builtin_wmemmove;
6182 
6183     // The result of mem* is the first argument.
6184     if (!Visit(E->getArg(0)))
6185       return false;
6186     LValue Dest = Result;
6187 
6188     LValue Src;
6189     if (!EvaluatePointer(E->getArg(1), Src, Info))
6190       return false;
6191 
6192     APSInt N;
6193     if (!EvaluateInteger(E->getArg(2), N, Info))
6194       return false;
6195     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
6196 
6197     // If the size is zero, we treat this as always being a valid no-op.
6198     // (Even if one of the src and dest pointers is null.)
6199     if (!N)
6200       return true;
6201 
6202     // Otherwise, if either of the operands is null, we can't proceed. Don't
6203     // try to determine the type of the copied objects, because there aren't
6204     // any.
6205     if (!Src.Base || !Dest.Base) {
6206       APValue Val;
6207       (!Src.Base ? Src : Dest).moveInto(Val);
6208       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
6209           << Move << WChar << !!Src.Base
6210           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
6211       return false;
6212     }
6213     if (Src.Designator.Invalid || Dest.Designator.Invalid)
6214       return false;
6215 
6216     // We require that Src and Dest are both pointers to arrays of
6217     // trivially-copyable type. (For the wide version, the designator will be
6218     // invalid if the designated object is not a wchar_t.)
6219     QualType T = Dest.Designator.getType(Info.Ctx);
6220     QualType SrcT = Src.Designator.getType(Info.Ctx);
6221     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
6222       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
6223       return false;
6224     }
6225     if (T->isIncompleteType()) {
6226       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
6227       return false;
6228     }
6229     if (!T.isTriviallyCopyableType(Info.Ctx)) {
6230       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
6231       return false;
6232     }
6233 
6234     // Figure out how many T's we're copying.
6235     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
6236     if (!WChar) {
6237       uint64_t Remainder;
6238       llvm::APInt OrigN = N;
6239       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
6240       if (Remainder) {
6241         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6242             << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
6243             << (unsigned)TSize;
6244         return false;
6245       }
6246     }
6247 
6248     // Check that the copying will remain within the arrays, just so that we
6249     // can give a more meaningful diagnostic. This implicitly also checks that
6250     // N fits into 64 bits.
6251     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
6252     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
6253     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
6254       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6255           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
6256           << N.toString(10, /*Signed*/false);
6257       return false;
6258     }
6259     uint64_t NElems = N.getZExtValue();
6260     uint64_t NBytes = NElems * TSize;
6261 
6262     // Check for overlap.
6263     int Direction = 1;
6264     if (HasSameBase(Src, Dest)) {
6265       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
6266       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
6267       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
6268         // Dest is inside the source region.
6269         if (!Move) {
6270           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6271           return false;
6272         }
6273         // For memmove and friends, copy backwards.
6274         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
6275             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
6276           return false;
6277         Direction = -1;
6278       } else if (!Move && SrcOffset >= DestOffset &&
6279                  SrcOffset - DestOffset < NBytes) {
6280         // Src is inside the destination region for memcpy: invalid.
6281         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6282         return false;
6283       }
6284     }
6285 
6286     while (true) {
6287       APValue Val;
6288       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
6289           !handleAssignment(Info, E, Dest, T, Val))
6290         return false;
6291       // Do not iterate past the last element; if we're copying backwards, that
6292       // might take us off the start of the array.
6293       if (--NElems == 0)
6294         return true;
6295       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
6296           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
6297         return false;
6298     }
6299   }
6300 
6301   default:
6302     return visitNonBuiltinCallExpr(E);
6303   }
6304 }
6305 
6306 //===----------------------------------------------------------------------===//
6307 // Member Pointer Evaluation
6308 //===----------------------------------------------------------------------===//
6309 
6310 namespace {
6311 class MemberPointerExprEvaluator
6312   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
6313   MemberPtr &Result;
6314 
6315   bool Success(const ValueDecl *D) {
6316     Result = MemberPtr(D);
6317     return true;
6318   }
6319 public:
6320 
6321   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6322     : ExprEvaluatorBaseTy(Info), Result(Result) {}
6323 
6324   bool Success(const APValue &V, const Expr *E) {
6325     Result.setFrom(V);
6326     return true;
6327   }
6328   bool ZeroInitialization(const Expr *E) {
6329     return Success((const ValueDecl*)nullptr);
6330   }
6331 
6332   bool VisitCastExpr(const CastExpr *E);
6333   bool VisitUnaryAddrOf(const UnaryOperator *E);
6334 };
6335 } // end anonymous namespace
6336 
6337 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6338                                   EvalInfo &Info) {
6339   assert(E->isRValue() && E->getType()->isMemberPointerType());
6340   return MemberPointerExprEvaluator(Info, Result).Visit(E);
6341 }
6342 
6343 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6344   switch (E->getCastKind()) {
6345   default:
6346     return ExprEvaluatorBaseTy::VisitCastExpr(E);
6347 
6348   case CK_NullToMemberPointer:
6349     VisitIgnoredValue(E->getSubExpr());
6350     return ZeroInitialization(E);
6351 
6352   case CK_BaseToDerivedMemberPointer: {
6353     if (!Visit(E->getSubExpr()))
6354       return false;
6355     if (E->path_empty())
6356       return true;
6357     // Base-to-derived member pointer casts store the path in derived-to-base
6358     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6359     // the wrong end of the derived->base arc, so stagger the path by one class.
6360     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6361     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6362          PathI != PathE; ++PathI) {
6363       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6364       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6365       if (!Result.castToDerived(Derived))
6366         return Error(E);
6367     }
6368     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6369     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
6370       return Error(E);
6371     return true;
6372   }
6373 
6374   case CK_DerivedToBaseMemberPointer:
6375     if (!Visit(E->getSubExpr()))
6376       return false;
6377     for (CastExpr::path_const_iterator PathI = E->path_begin(),
6378          PathE = E->path_end(); PathI != PathE; ++PathI) {
6379       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6380       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6381       if (!Result.castToBase(Base))
6382         return Error(E);
6383     }
6384     return true;
6385   }
6386 }
6387 
6388 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6389   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6390   // member can be formed.
6391   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6392 }
6393 
6394 //===----------------------------------------------------------------------===//
6395 // Record Evaluation
6396 //===----------------------------------------------------------------------===//
6397 
6398 namespace {
6399   class RecordExprEvaluator
6400   : public ExprEvaluatorBase<RecordExprEvaluator> {
6401     const LValue &This;
6402     APValue &Result;
6403   public:
6404 
6405     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6406       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6407 
6408     bool Success(const APValue &V, const Expr *E) {
6409       Result = V;
6410       return true;
6411     }
6412     bool ZeroInitialization(const Expr *E) {
6413       return ZeroInitialization(E, E->getType());
6414     }
6415     bool ZeroInitialization(const Expr *E, QualType T);
6416 
6417     bool VisitCallExpr(const CallExpr *E) {
6418       return handleCallExpr(E, Result, &This);
6419     }
6420     bool VisitCastExpr(const CastExpr *E);
6421     bool VisitInitListExpr(const InitListExpr *E);
6422     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6423       return VisitCXXConstructExpr(E, E->getType());
6424     }
6425     bool VisitLambdaExpr(const LambdaExpr *E);
6426     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
6427     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
6428     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
6429 
6430     bool VisitBinCmp(const BinaryOperator *E);
6431   };
6432 }
6433 
6434 /// Perform zero-initialization on an object of non-union class type.
6435 /// C++11 [dcl.init]p5:
6436 ///  To zero-initialize an object or reference of type T means:
6437 ///    [...]
6438 ///    -- if T is a (possibly cv-qualified) non-union class type,
6439 ///       each non-static data member and each base-class subobject is
6440 ///       zero-initialized
6441 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6442                                           const RecordDecl *RD,
6443                                           const LValue &This, APValue &Result) {
6444   assert(!RD->isUnion() && "Expected non-union class type");
6445   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6446   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
6447                    std::distance(RD->field_begin(), RD->field_end()));
6448 
6449   if (RD->isInvalidDecl()) return false;
6450   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6451 
6452   if (CD) {
6453     unsigned Index = 0;
6454     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
6455            End = CD->bases_end(); I != End; ++I, ++Index) {
6456       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6457       LValue Subobject = This;
6458       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6459         return false;
6460       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
6461                                          Result.getStructBase(Index)))
6462         return false;
6463     }
6464   }
6465 
6466   for (const auto *I : RD->fields()) {
6467     // -- if T is a reference type, no initialization is performed.
6468     if (I->getType()->isReferenceType())
6469       continue;
6470 
6471     LValue Subobject = This;
6472     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
6473       return false;
6474 
6475     ImplicitValueInitExpr VIE(I->getType());
6476     if (!EvaluateInPlace(
6477           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
6478       return false;
6479   }
6480 
6481   return true;
6482 }
6483 
6484 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6485   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
6486   if (RD->isInvalidDecl()) return false;
6487   if (RD->isUnion()) {
6488     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6489     // object's first non-static named data member is zero-initialized
6490     RecordDecl::field_iterator I = RD->field_begin();
6491     if (I == RD->field_end()) {
6492       Result = APValue((const FieldDecl*)nullptr);
6493       return true;
6494     }
6495 
6496     LValue Subobject = This;
6497     if (!HandleLValueMember(Info, E, Subobject, *I))
6498       return false;
6499     Result = APValue(*I);
6500     ImplicitValueInitExpr VIE(I->getType());
6501     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
6502   }
6503 
6504   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
6505     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
6506     return false;
6507   }
6508 
6509   return HandleClassZeroInitialization(Info, E, RD, This, Result);
6510 }
6511 
6512 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6513   switch (E->getCastKind()) {
6514   default:
6515     return ExprEvaluatorBaseTy::VisitCastExpr(E);
6516 
6517   case CK_ConstructorConversion:
6518     return Visit(E->getSubExpr());
6519 
6520   case CK_DerivedToBase:
6521   case CK_UncheckedDerivedToBase: {
6522     APValue DerivedObject;
6523     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
6524       return false;
6525     if (!DerivedObject.isStruct())
6526       return Error(E->getSubExpr());
6527 
6528     // Derived-to-base rvalue conversion: just slice off the derived part.
6529     APValue *Value = &DerivedObject;
6530     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6531     for (CastExpr::path_const_iterator PathI = E->path_begin(),
6532          PathE = E->path_end(); PathI != PathE; ++PathI) {
6533       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6534       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6535       Value = &Value->getStructBase(getBaseIndex(RD, Base));
6536       RD = Base;
6537     }
6538     Result = *Value;
6539     return true;
6540   }
6541   }
6542 }
6543 
6544 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6545   if (E->isTransparent())
6546     return Visit(E->getInit(0));
6547 
6548   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
6549   if (RD->isInvalidDecl()) return false;
6550   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6551 
6552   if (RD->isUnion()) {
6553     const FieldDecl *Field = E->getInitializedFieldInUnion();
6554     Result = APValue(Field);
6555     if (!Field)
6556       return true;
6557 
6558     // If the initializer list for a union does not contain any elements, the
6559     // first element of the union is value-initialized.
6560     // FIXME: The element should be initialized from an initializer list.
6561     //        Is this difference ever observable for initializer lists which
6562     //        we don't build?
6563     ImplicitValueInitExpr VIE(Field->getType());
6564     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6565 
6566     LValue Subobject = This;
6567     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6568       return false;
6569 
6570     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6571     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6572                                   isa<CXXDefaultInitExpr>(InitExpr));
6573 
6574     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
6575   }
6576 
6577   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
6578   if (Result.isUninit())
6579     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6580                      std::distance(RD->field_begin(), RD->field_end()));
6581   unsigned ElementNo = 0;
6582   bool Success = true;
6583 
6584   // Initialize base classes.
6585   if (CXXRD) {
6586     for (const auto &Base : CXXRD->bases()) {
6587       assert(ElementNo < E->getNumInits() && "missing init for base class");
6588       const Expr *Init = E->getInit(ElementNo);
6589 
6590       LValue Subobject = This;
6591       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6592         return false;
6593 
6594       APValue &FieldVal = Result.getStructBase(ElementNo);
6595       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
6596         if (!Info.noteFailure())
6597           return false;
6598         Success = false;
6599       }
6600       ++ElementNo;
6601     }
6602   }
6603 
6604   // Initialize members.
6605   for (const auto *Field : RD->fields()) {
6606     // Anonymous bit-fields are not considered members of the class for
6607     // purposes of aggregate initialization.
6608     if (Field->isUnnamedBitfield())
6609       continue;
6610 
6611     LValue Subobject = This;
6612 
6613     bool HaveInit = ElementNo < E->getNumInits();
6614 
6615     // FIXME: Diagnostics here should point to the end of the initializer
6616     // list, not the start.
6617     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
6618                             Subobject, Field, &Layout))
6619       return false;
6620 
6621     // Perform an implicit value-initialization for members beyond the end of
6622     // the initializer list.
6623     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
6624     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
6625 
6626     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6627     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6628                                   isa<CXXDefaultInitExpr>(Init));
6629 
6630     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6631     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6632         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
6633                                                        FieldVal, Field))) {
6634       if (!Info.noteFailure())
6635         return false;
6636       Success = false;
6637     }
6638   }
6639 
6640   return Success;
6641 }
6642 
6643 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6644                                                 QualType T) {
6645   // Note that E's type is not necessarily the type of our class here; we might
6646   // be initializing an array element instead.
6647   const CXXConstructorDecl *FD = E->getConstructor();
6648   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6649 
6650   bool ZeroInit = E->requiresZeroInitialization();
6651   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
6652     // If we've already performed zero-initialization, we're already done.
6653     if (!Result.isUninit())
6654       return true;
6655 
6656     // We can get here in two different ways:
6657     //  1) We're performing value-initialization, and should zero-initialize
6658     //     the object, or
6659     //  2) We're performing default-initialization of an object with a trivial
6660     //     constexpr default constructor, in which case we should start the
6661     //     lifetimes of all the base subobjects (there can be no data member
6662     //     subobjects in this case) per [basic.life]p1.
6663     // Either way, ZeroInitialization is appropriate.
6664     return ZeroInitialization(E, T);
6665   }
6666 
6667   const FunctionDecl *Definition = nullptr;
6668   auto Body = FD->getBody(Definition);
6669 
6670   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6671     return false;
6672 
6673   // Avoid materializing a temporary for an elidable copy/move constructor.
6674   if (E->isElidable() && !ZeroInit)
6675     if (const MaterializeTemporaryExpr *ME
6676           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6677       return Visit(ME->GetTemporaryExpr());
6678 
6679   if (ZeroInit && !ZeroInitialization(E, T))
6680     return false;
6681 
6682   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
6683   return HandleConstructorCall(E, This, Args,
6684                                cast<CXXConstructorDecl>(Definition), Info,
6685                                Result);
6686 }
6687 
6688 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6689     const CXXInheritedCtorInitExpr *E) {
6690   if (!Info.CurrentCall) {
6691     assert(Info.checkingPotentialConstantExpression());
6692     return false;
6693   }
6694 
6695   const CXXConstructorDecl *FD = E->getConstructor();
6696   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6697     return false;
6698 
6699   const FunctionDecl *Definition = nullptr;
6700   auto Body = FD->getBody(Definition);
6701 
6702   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6703     return false;
6704 
6705   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
6706                                cast<CXXConstructorDecl>(Definition), Info,
6707                                Result);
6708 }
6709 
6710 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6711     const CXXStdInitializerListExpr *E) {
6712   const ConstantArrayType *ArrayType =
6713       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6714 
6715   LValue Array;
6716   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6717     return false;
6718 
6719   // Get a pointer to the first element of the array.
6720   Array.addArray(Info, E, ArrayType);
6721 
6722   // FIXME: Perform the checks on the field types in SemaInit.
6723   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6724   RecordDecl::field_iterator Field = Record->field_begin();
6725   if (Field == Record->field_end())
6726     return Error(E);
6727 
6728   // Start pointer.
6729   if (!Field->getType()->isPointerType() ||
6730       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6731                             ArrayType->getElementType()))
6732     return Error(E);
6733 
6734   // FIXME: What if the initializer_list type has base classes, etc?
6735   Result = APValue(APValue::UninitStruct(), 0, 2);
6736   Array.moveInto(Result.getStructField(0));
6737 
6738   if (++Field == Record->field_end())
6739     return Error(E);
6740 
6741   if (Field->getType()->isPointerType() &&
6742       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6743                            ArrayType->getElementType())) {
6744     // End pointer.
6745     if (!HandleLValueArrayAdjustment(Info, E, Array,
6746                                      ArrayType->getElementType(),
6747                                      ArrayType->getSize().getZExtValue()))
6748       return false;
6749     Array.moveInto(Result.getStructField(1));
6750   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6751     // Length.
6752     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6753   else
6754     return Error(E);
6755 
6756   if (++Field != Record->field_end())
6757     return Error(E);
6758 
6759   return true;
6760 }
6761 
6762 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6763   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6764   if (ClosureClass->isInvalidDecl()) return false;
6765 
6766   if (Info.checkingPotentialConstantExpression()) return true;
6767 
6768   const size_t NumFields =
6769       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
6770 
6771   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6772                                             E->capture_init_end()) &&
6773          "The number of lambda capture initializers should equal the number of "
6774          "fields within the closure type");
6775 
6776   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6777   // Iterate through all the lambda's closure object's fields and initialize
6778   // them.
6779   auto *CaptureInitIt = E->capture_init_begin();
6780   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6781   bool Success = true;
6782   for (const auto *Field : ClosureClass->fields()) {
6783     assert(CaptureInitIt != E->capture_init_end());
6784     // Get the initializer for this field
6785     Expr *const CurFieldInit = *CaptureInitIt++;
6786 
6787     // If there is no initializer, either this is a VLA or an error has
6788     // occurred.
6789     if (!CurFieldInit)
6790       return Error(E);
6791 
6792     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6793     if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6794       if (!Info.keepEvaluatingAfterFailure())
6795         return false;
6796       Success = false;
6797     }
6798     ++CaptureIt;
6799   }
6800   return Success;
6801 }
6802 
6803 static bool EvaluateRecord(const Expr *E, const LValue &This,
6804                            APValue &Result, EvalInfo &Info) {
6805   assert(E->isRValue() && E->getType()->isRecordType() &&
6806          "can't evaluate expression as a record rvalue");
6807   return RecordExprEvaluator(Info, This, Result).Visit(E);
6808 }
6809 
6810 //===----------------------------------------------------------------------===//
6811 // Temporary Evaluation
6812 //
6813 // Temporaries are represented in the AST as rvalues, but generally behave like
6814 // lvalues. The full-object of which the temporary is a subobject is implicitly
6815 // materialized so that a reference can bind to it.
6816 //===----------------------------------------------------------------------===//
6817 namespace {
6818 class TemporaryExprEvaluator
6819   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6820 public:
6821   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
6822     LValueExprEvaluatorBaseTy(Info, Result, false) {}
6823 
6824   /// Visit an expression which constructs the value of this temporary.
6825   bool VisitConstructExpr(const Expr *E) {
6826     APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
6827     return EvaluateInPlace(Value, Info, Result, E);
6828   }
6829 
6830   bool VisitCastExpr(const CastExpr *E) {
6831     switch (E->getCastKind()) {
6832     default:
6833       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6834 
6835     case CK_ConstructorConversion:
6836       return VisitConstructExpr(E->getSubExpr());
6837     }
6838   }
6839   bool VisitInitListExpr(const InitListExpr *E) {
6840     return VisitConstructExpr(E);
6841   }
6842   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6843     return VisitConstructExpr(E);
6844   }
6845   bool VisitCallExpr(const CallExpr *E) {
6846     return VisitConstructExpr(E);
6847   }
6848   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6849     return VisitConstructExpr(E);
6850   }
6851   bool VisitLambdaExpr(const LambdaExpr *E) {
6852     return VisitConstructExpr(E);
6853   }
6854 };
6855 } // end anonymous namespace
6856 
6857 /// Evaluate an expression of record type as a temporary.
6858 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
6859   assert(E->isRValue() && E->getType()->isRecordType());
6860   return TemporaryExprEvaluator(Info, Result).Visit(E);
6861 }
6862 
6863 //===----------------------------------------------------------------------===//
6864 // Vector Evaluation
6865 //===----------------------------------------------------------------------===//
6866 
6867 namespace {
6868   class VectorExprEvaluator
6869   : public ExprEvaluatorBase<VectorExprEvaluator> {
6870     APValue &Result;
6871   public:
6872 
6873     VectorExprEvaluator(EvalInfo &info, APValue &Result)
6874       : ExprEvaluatorBaseTy(info), Result(Result) {}
6875 
6876     bool Success(ArrayRef<APValue> V, const Expr *E) {
6877       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6878       // FIXME: remove this APValue copy.
6879       Result = APValue(V.data(), V.size());
6880       return true;
6881     }
6882     bool Success(const APValue &V, const Expr *E) {
6883       assert(V.isVector());
6884       Result = V;
6885       return true;
6886     }
6887     bool ZeroInitialization(const Expr *E);
6888 
6889     bool VisitUnaryReal(const UnaryOperator *E)
6890       { return Visit(E->getSubExpr()); }
6891     bool VisitCastExpr(const CastExpr* E);
6892     bool VisitInitListExpr(const InitListExpr *E);
6893     bool VisitUnaryImag(const UnaryOperator *E);
6894     // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
6895     //                 binary comparisons, binary and/or/xor,
6896     //                 shufflevector, ExtVectorElementExpr
6897   };
6898 } // end anonymous namespace
6899 
6900 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
6901   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
6902   return VectorExprEvaluator(Info, Result).Visit(E);
6903 }
6904 
6905 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
6906   const VectorType *VTy = E->getType()->castAs<VectorType>();
6907   unsigned NElts = VTy->getNumElements();
6908 
6909   const Expr *SE = E->getSubExpr();
6910   QualType SETy = SE->getType();
6911 
6912   switch (E->getCastKind()) {
6913   case CK_VectorSplat: {
6914     APValue Val = APValue();
6915     if (SETy->isIntegerType()) {
6916       APSInt IntResult;
6917       if (!EvaluateInteger(SE, IntResult, Info))
6918         return false;
6919       Val = APValue(std::move(IntResult));
6920     } else if (SETy->isRealFloatingType()) {
6921       APFloat FloatResult(0.0);
6922       if (!EvaluateFloat(SE, FloatResult, Info))
6923         return false;
6924       Val = APValue(std::move(FloatResult));
6925     } else {
6926       return Error(E);
6927     }
6928 
6929     // Splat and create vector APValue.
6930     SmallVector<APValue, 4> Elts(NElts, Val);
6931     return Success(Elts, E);
6932   }
6933   case CK_BitCast: {
6934     // Evaluate the operand into an APInt we can extract from.
6935     llvm::APInt SValInt;
6936     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6937       return false;
6938     // Extract the elements
6939     QualType EltTy = VTy->getElementType();
6940     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6941     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6942     SmallVector<APValue, 4> Elts;
6943     if (EltTy->isRealFloatingType()) {
6944       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
6945       unsigned FloatEltSize = EltSize;
6946       if (&Sem == &APFloat::x87DoubleExtended())
6947         FloatEltSize = 80;
6948       for (unsigned i = 0; i < NElts; i++) {
6949         llvm::APInt Elt;
6950         if (BigEndian)
6951           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6952         else
6953           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
6954         Elts.push_back(APValue(APFloat(Sem, Elt)));
6955       }
6956     } else if (EltTy->isIntegerType()) {
6957       for (unsigned i = 0; i < NElts; i++) {
6958         llvm::APInt Elt;
6959         if (BigEndian)
6960           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6961         else
6962           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6963         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6964       }
6965     } else {
6966       return Error(E);
6967     }
6968     return Success(Elts, E);
6969   }
6970   default:
6971     return ExprEvaluatorBaseTy::VisitCastExpr(E);
6972   }
6973 }
6974 
6975 bool
6976 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6977   const VectorType *VT = E->getType()->castAs<VectorType>();
6978   unsigned NumInits = E->getNumInits();
6979   unsigned NumElements = VT->getNumElements();
6980 
6981   QualType EltTy = VT->getElementType();
6982   SmallVector<APValue, 4> Elements;
6983 
6984   // The number of initializers can be less than the number of
6985   // vector elements. For OpenCL, this can be due to nested vector
6986   // initialization. For GCC compatibility, missing trailing elements
6987   // should be initialized with zeroes.
6988   unsigned CountInits = 0, CountElts = 0;
6989   while (CountElts < NumElements) {
6990     // Handle nested vector initialization.
6991     if (CountInits < NumInits
6992         && E->getInit(CountInits)->getType()->isVectorType()) {
6993       APValue v;
6994       if (!EvaluateVector(E->getInit(CountInits), v, Info))
6995         return Error(E);
6996       unsigned vlen = v.getVectorLength();
6997       for (unsigned j = 0; j < vlen; j++)
6998         Elements.push_back(v.getVectorElt(j));
6999       CountElts += vlen;
7000     } else if (EltTy->isIntegerType()) {
7001       llvm::APSInt sInt(32);
7002       if (CountInits < NumInits) {
7003         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
7004           return false;
7005       } else // trailing integer zero.
7006         sInt = Info.Ctx.MakeIntValue(0, EltTy);
7007       Elements.push_back(APValue(sInt));
7008       CountElts++;
7009     } else {
7010       llvm::APFloat f(0.0);
7011       if (CountInits < NumInits) {
7012         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
7013           return false;
7014       } else // trailing float zero.
7015         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
7016       Elements.push_back(APValue(f));
7017       CountElts++;
7018     }
7019     CountInits++;
7020   }
7021   return Success(Elements, E);
7022 }
7023 
7024 bool
7025 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
7026   const VectorType *VT = E->getType()->getAs<VectorType>();
7027   QualType EltTy = VT->getElementType();
7028   APValue ZeroElement;
7029   if (EltTy->isIntegerType())
7030     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
7031   else
7032     ZeroElement =
7033         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
7034 
7035   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
7036   return Success(Elements, E);
7037 }
7038 
7039 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7040   VisitIgnoredValue(E->getSubExpr());
7041   return ZeroInitialization(E);
7042 }
7043 
7044 //===----------------------------------------------------------------------===//
7045 // Array Evaluation
7046 //===----------------------------------------------------------------------===//
7047 
7048 namespace {
7049   class ArrayExprEvaluator
7050   : public ExprEvaluatorBase<ArrayExprEvaluator> {
7051     const LValue &This;
7052     APValue &Result;
7053   public:
7054 
7055     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
7056       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
7057 
7058     bool Success(const APValue &V, const Expr *E) {
7059       assert((V.isArray() || V.isLValue()) &&
7060              "expected array or string literal");
7061       Result = V;
7062       return true;
7063     }
7064 
7065     bool ZeroInitialization(const Expr *E) {
7066       const ConstantArrayType *CAT =
7067           Info.Ctx.getAsConstantArrayType(E->getType());
7068       if (!CAT)
7069         return Error(E);
7070 
7071       Result = APValue(APValue::UninitArray(), 0,
7072                        CAT->getSize().getZExtValue());
7073       if (!Result.hasArrayFiller()) return true;
7074 
7075       // Zero-initialize all elements.
7076       LValue Subobject = This;
7077       Subobject.addArray(Info, E, CAT);
7078       ImplicitValueInitExpr VIE(CAT->getElementType());
7079       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
7080     }
7081 
7082     bool VisitCallExpr(const CallExpr *E) {
7083       return handleCallExpr(E, Result, &This);
7084     }
7085     bool VisitInitListExpr(const InitListExpr *E);
7086     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
7087     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
7088     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
7089                                const LValue &Subobject,
7090                                APValue *Value, QualType Type);
7091   };
7092 } // end anonymous namespace
7093 
7094 static bool EvaluateArray(const Expr *E, const LValue &This,
7095                           APValue &Result, EvalInfo &Info) {
7096   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
7097   return ArrayExprEvaluator(Info, This, Result).Visit(E);
7098 }
7099 
7100 // Return true iff the given array filler may depend on the element index.
7101 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
7102   // For now, just whitelist non-class value-initialization and initialization
7103   // lists comprised of them.
7104   if (isa<ImplicitValueInitExpr>(FillerExpr))
7105     return false;
7106   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
7107     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
7108       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
7109         return true;
7110     }
7111     return false;
7112   }
7113   return true;
7114 }
7115 
7116 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7117   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
7118   if (!CAT)
7119     return Error(E);
7120 
7121   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
7122   // an appropriately-typed string literal enclosed in braces.
7123   if (E->isStringLiteralInit()) {
7124     LValue LV;
7125     if (!EvaluateLValue(E->getInit(0), LV, Info))
7126       return false;
7127     APValue Val;
7128     LV.moveInto(Val);
7129     return Success(Val, E);
7130   }
7131 
7132   bool Success = true;
7133 
7134   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
7135          "zero-initialized array shouldn't have any initialized elts");
7136   APValue Filler;
7137   if (Result.isArray() && Result.hasArrayFiller())
7138     Filler = Result.getArrayFiller();
7139 
7140   unsigned NumEltsToInit = E->getNumInits();
7141   unsigned NumElts = CAT->getSize().getZExtValue();
7142   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
7143 
7144   // If the initializer might depend on the array index, run it for each
7145   // array element.
7146   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
7147     NumEltsToInit = NumElts;
7148 
7149   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
7150                           << NumEltsToInit << ".\n");
7151 
7152   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
7153 
7154   // If the array was previously zero-initialized, preserve the
7155   // zero-initialized values.
7156   if (!Filler.isUninit()) {
7157     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
7158       Result.getArrayInitializedElt(I) = Filler;
7159     if (Result.hasArrayFiller())
7160       Result.getArrayFiller() = Filler;
7161   }
7162 
7163   LValue Subobject = This;
7164   Subobject.addArray(Info, E, CAT);
7165   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
7166     const Expr *Init =
7167         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
7168     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
7169                          Info, Subobject, Init) ||
7170         !HandleLValueArrayAdjustment(Info, Init, Subobject,
7171                                      CAT->getElementType(), 1)) {
7172       if (!Info.noteFailure())
7173         return false;
7174       Success = false;
7175     }
7176   }
7177 
7178   if (!Result.hasArrayFiller())
7179     return Success;
7180 
7181   // If we get here, we have a trivial filler, which we can just evaluate
7182   // once and splat over the rest of the array elements.
7183   assert(FillerExpr && "no array filler for incomplete init list");
7184   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
7185                          FillerExpr) && Success;
7186 }
7187 
7188 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
7189   if (E->getCommonExpr() &&
7190       !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
7191                 Info, E->getCommonExpr()->getSourceExpr()))
7192     return false;
7193 
7194   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
7195 
7196   uint64_t Elements = CAT->getSize().getZExtValue();
7197   Result = APValue(APValue::UninitArray(), Elements, Elements);
7198 
7199   LValue Subobject = This;
7200   Subobject.addArray(Info, E, CAT);
7201 
7202   bool Success = true;
7203   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
7204     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
7205                          Info, Subobject, E->getSubExpr()) ||
7206         !HandleLValueArrayAdjustment(Info, E, Subobject,
7207                                      CAT->getElementType(), 1)) {
7208       if (!Info.noteFailure())
7209         return false;
7210       Success = false;
7211     }
7212   }
7213 
7214   return Success;
7215 }
7216 
7217 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
7218   return VisitCXXConstructExpr(E, This, &Result, E->getType());
7219 }
7220 
7221 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7222                                                const LValue &Subobject,
7223                                                APValue *Value,
7224                                                QualType Type) {
7225   bool HadZeroInit = !Value->isUninit();
7226 
7227   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
7228     unsigned N = CAT->getSize().getZExtValue();
7229 
7230     // Preserve the array filler if we had prior zero-initialization.
7231     APValue Filler =
7232       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
7233                                              : APValue();
7234 
7235     *Value = APValue(APValue::UninitArray(), N, N);
7236 
7237     if (HadZeroInit)
7238       for (unsigned I = 0; I != N; ++I)
7239         Value->getArrayInitializedElt(I) = Filler;
7240 
7241     // Initialize the elements.
7242     LValue ArrayElt = Subobject;
7243     ArrayElt.addArray(Info, E, CAT);
7244     for (unsigned I = 0; I != N; ++I)
7245       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
7246                                  CAT->getElementType()) ||
7247           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
7248                                        CAT->getElementType(), 1))
7249         return false;
7250 
7251     return true;
7252   }
7253 
7254   if (!Type->isRecordType())
7255     return Error(E);
7256 
7257   return RecordExprEvaluator(Info, Subobject, *Value)
7258              .VisitCXXConstructExpr(E, Type);
7259 }
7260 
7261 //===----------------------------------------------------------------------===//
7262 // Integer Evaluation
7263 //
7264 // As a GNU extension, we support casting pointers to sufficiently-wide integer
7265 // types and back in constant folding. Integer values are thus represented
7266 // either as an integer-valued APValue, or as an lvalue-valued APValue.
7267 //===----------------------------------------------------------------------===//
7268 
7269 namespace {
7270 class IntExprEvaluator
7271         : public ExprEvaluatorBase<IntExprEvaluator> {
7272   APValue &Result;
7273 public:
7274   IntExprEvaluator(EvalInfo &info, APValue &result)
7275       : ExprEvaluatorBaseTy(info), Result(result) {}
7276 
7277   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
7278     assert(E->getType()->isIntegralOrEnumerationType() &&
7279            "Invalid evaluation result.");
7280     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
7281            "Invalid evaluation result.");
7282     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7283            "Invalid evaluation result.");
7284     Result = APValue(SI);
7285     return true;
7286   }
7287   bool Success(const llvm::APSInt &SI, const Expr *E) {
7288     return Success(SI, E, Result);
7289   }
7290 
7291   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
7292     assert(E->getType()->isIntegralOrEnumerationType() &&
7293            "Invalid evaluation result.");
7294     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7295            "Invalid evaluation result.");
7296     Result = APValue(APSInt(I));
7297     Result.getInt().setIsUnsigned(
7298                             E->getType()->isUnsignedIntegerOrEnumerationType());
7299     return true;
7300   }
7301   bool Success(const llvm::APInt &I, const Expr *E) {
7302     return Success(I, E, Result);
7303   }
7304 
7305   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7306     assert(E->getType()->isIntegralOrEnumerationType() &&
7307            "Invalid evaluation result.");
7308     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
7309     return true;
7310   }
7311   bool Success(uint64_t Value, const Expr *E) {
7312     return Success(Value, E, Result);
7313   }
7314 
7315   bool Success(CharUnits Size, const Expr *E) {
7316     return Success(Size.getQuantity(), E);
7317   }
7318 
7319   bool Success(const APValue &V, const Expr *E) {
7320     if (V.isLValue() || V.isAddrLabelDiff()) {
7321       Result = V;
7322       return true;
7323     }
7324     return Success(V.getInt(), E);
7325   }
7326 
7327   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
7328 
7329   //===--------------------------------------------------------------------===//
7330   //                            Visitor Methods
7331   //===--------------------------------------------------------------------===//
7332 
7333   bool VisitIntegerLiteral(const IntegerLiteral *E) {
7334     return Success(E->getValue(), E);
7335   }
7336   bool VisitCharacterLiteral(const CharacterLiteral *E) {
7337     return Success(E->getValue(), E);
7338   }
7339 
7340   bool CheckReferencedDecl(const Expr *E, const Decl *D);
7341   bool VisitDeclRefExpr(const DeclRefExpr *E) {
7342     if (CheckReferencedDecl(E, E->getDecl()))
7343       return true;
7344 
7345     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
7346   }
7347   bool VisitMemberExpr(const MemberExpr *E) {
7348     if (CheckReferencedDecl(E, E->getMemberDecl())) {
7349       VisitIgnoredBaseExpression(E->getBase());
7350       return true;
7351     }
7352 
7353     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
7354   }
7355 
7356   bool VisitCallExpr(const CallExpr *E);
7357   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
7358   bool VisitBinaryOperator(const BinaryOperator *E);
7359   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
7360   bool VisitUnaryOperator(const UnaryOperator *E);
7361 
7362   bool VisitCastExpr(const CastExpr* E);
7363   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
7364 
7365   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
7366     return Success(E->getValue(), E);
7367   }
7368 
7369   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7370     return Success(E->getValue(), E);
7371   }
7372 
7373   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7374     if (Info.ArrayInitIndex == uint64_t(-1)) {
7375       // We were asked to evaluate this subexpression independent of the
7376       // enclosing ArrayInitLoopExpr. We can't do that.
7377       Info.FFDiag(E);
7378       return false;
7379     }
7380     return Success(Info.ArrayInitIndex, E);
7381   }
7382 
7383   // Note, GNU defines __null as an integer, not a pointer.
7384   bool VisitGNUNullExpr(const GNUNullExpr *E) {
7385     return ZeroInitialization(E);
7386   }
7387 
7388   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7389     return Success(E->getValue(), E);
7390   }
7391 
7392   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7393     return Success(E->getValue(), E);
7394   }
7395 
7396   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7397     return Success(E->getValue(), E);
7398   }
7399 
7400   bool VisitUnaryReal(const UnaryOperator *E);
7401   bool VisitUnaryImag(const UnaryOperator *E);
7402 
7403   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
7404   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
7405 
7406   // FIXME: Missing: array subscript of vector, member of vector
7407 };
7408 
7409 class FixedPointExprEvaluator
7410     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
7411   APValue &Result;
7412 
7413  public:
7414   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
7415       : ExprEvaluatorBaseTy(info), Result(result) {}
7416 
7417   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
7418     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7419     assert(SI.isSigned() == E->getType()->isSignedFixedPointType() &&
7420            "Invalid evaluation result.");
7421     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7422            "Invalid evaluation result.");
7423     Result = APValue(SI);
7424     return true;
7425   }
7426   bool Success(const llvm::APSInt &SI, const Expr *E) {
7427     return Success(SI, E, Result);
7428   }
7429 
7430   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
7431     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7432     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7433            "Invalid evaluation result.");
7434     Result = APValue(APSInt(I));
7435     Result.getInt().setIsUnsigned(E->getType()->isUnsignedFixedPointType());
7436     return true;
7437   }
7438   bool Success(const llvm::APInt &I, const Expr *E) {
7439     return Success(I, E, Result);
7440   }
7441 
7442   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7443     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7444     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
7445     return true;
7446   }
7447   bool Success(uint64_t Value, const Expr *E) {
7448     return Success(Value, E, Result);
7449   }
7450 
7451   bool Success(CharUnits Size, const Expr *E) {
7452     return Success(Size.getQuantity(), E);
7453   }
7454 
7455   bool Success(const APValue &V, const Expr *E) {
7456     if (V.isLValue() || V.isAddrLabelDiff()) {
7457       Result = V;
7458       return true;
7459     }
7460     return Success(V.getInt(), E);
7461   }
7462 
7463   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
7464 
7465   //===--------------------------------------------------------------------===//
7466   //                            Visitor Methods
7467   //===--------------------------------------------------------------------===//
7468 
7469   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
7470     return Success(E->getValue(), E);
7471   }
7472 
7473   bool VisitUnaryOperator(const UnaryOperator *E);
7474 };
7475 } // end anonymous namespace
7476 
7477 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7478 /// produce either the integer value or a pointer.
7479 ///
7480 /// GCC has a heinous extension which folds casts between pointer types and
7481 /// pointer-sized integral types. We support this by allowing the evaluation of
7482 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7483 /// Some simple arithmetic on such values is supported (they are treated much
7484 /// like char*).
7485 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
7486                                     EvalInfo &Info) {
7487   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
7488   return IntExprEvaluator(Info, Result).Visit(E);
7489 }
7490 
7491 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
7492   APValue Val;
7493   if (!EvaluateIntegerOrLValue(E, Val, Info))
7494     return false;
7495   if (!Val.isInt()) {
7496     // FIXME: It would be better to produce the diagnostic for casting
7497     //        a pointer to an integer.
7498     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
7499     return false;
7500   }
7501   Result = Val.getInt();
7502   return true;
7503 }
7504 
7505 /// Check whether the given declaration can be directly converted to an integral
7506 /// rvalue. If not, no diagnostic is produced; there are other things we can
7507 /// try.
7508 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
7509   // Enums are integer constant exprs.
7510   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
7511     // Check for signedness/width mismatches between E type and ECD value.
7512     bool SameSign = (ECD->getInitVal().isSigned()
7513                      == E->getType()->isSignedIntegerOrEnumerationType());
7514     bool SameWidth = (ECD->getInitVal().getBitWidth()
7515                       == Info.Ctx.getIntWidth(E->getType()));
7516     if (SameSign && SameWidth)
7517       return Success(ECD->getInitVal(), E);
7518     else {
7519       // Get rid of mismatch (otherwise Success assertions will fail)
7520       // by computing a new value matching the type of E.
7521       llvm::APSInt Val = ECD->getInitVal();
7522       if (!SameSign)
7523         Val.setIsSigned(!ECD->getInitVal().isSigned());
7524       if (!SameWidth)
7525         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7526       return Success(Val, E);
7527     }
7528   }
7529   return false;
7530 }
7531 
7532 /// Values returned by __builtin_classify_type, chosen to match the values
7533 /// produced by GCC's builtin.
7534 enum class GCCTypeClass {
7535   None = -1,
7536   Void = 0,
7537   Integer = 1,
7538   // GCC reserves 2 for character types, but instead classifies them as
7539   // integers.
7540   Enum = 3,
7541   Bool = 4,
7542   Pointer = 5,
7543   // GCC reserves 6 for references, but appears to never use it (because
7544   // expressions never have reference type, presumably).
7545   PointerToDataMember = 7,
7546   RealFloat = 8,
7547   Complex = 9,
7548   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
7549   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
7550   // GCC claims to reserve 11 for pointers to member functions, but *actually*
7551   // uses 12 for that purpose, same as for a class or struct. Maybe it
7552   // internally implements a pointer to member as a struct?  Who knows.
7553   PointerToMemberFunction = 12, // Not a bug, see above.
7554   ClassOrStruct = 12,
7555   Union = 13,
7556   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
7557   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
7558   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
7559   // literals.
7560 };
7561 
7562 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7563 /// as GCC.
7564 static GCCTypeClass
7565 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
7566   assert(!T->isDependentType() && "unexpected dependent type");
7567 
7568   QualType CanTy = T.getCanonicalType();
7569   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7570 
7571   switch (CanTy->getTypeClass()) {
7572 #define TYPE(ID, BASE)
7573 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7574 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7575 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7576 #include "clang/AST/TypeNodes.def"
7577   case Type::Auto:
7578   case Type::DeducedTemplateSpecialization:
7579       llvm_unreachable("unexpected non-canonical or dependent type");
7580 
7581   case Type::Builtin:
7582     switch (BT->getKind()) {
7583 #define BUILTIN_TYPE(ID, SINGLETON_ID)
7584 #define SIGNED_TYPE(ID, SINGLETON_ID) \
7585     case BuiltinType::ID: return GCCTypeClass::Integer;
7586 #define FLOATING_TYPE(ID, SINGLETON_ID) \
7587     case BuiltinType::ID: return GCCTypeClass::RealFloat;
7588 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
7589     case BuiltinType::ID: break;
7590 #include "clang/AST/BuiltinTypes.def"
7591     case BuiltinType::Void:
7592       return GCCTypeClass::Void;
7593 
7594     case BuiltinType::Bool:
7595       return GCCTypeClass::Bool;
7596 
7597     case BuiltinType::Char_U:
7598     case BuiltinType::UChar:
7599     case BuiltinType::WChar_U:
7600     case BuiltinType::Char8:
7601     case BuiltinType::Char16:
7602     case BuiltinType::Char32:
7603     case BuiltinType::UShort:
7604     case BuiltinType::UInt:
7605     case BuiltinType::ULong:
7606     case BuiltinType::ULongLong:
7607     case BuiltinType::UInt128:
7608       return GCCTypeClass::Integer;
7609 
7610     case BuiltinType::UShortAccum:
7611     case BuiltinType::UAccum:
7612     case BuiltinType::ULongAccum:
7613     case BuiltinType::UShortFract:
7614     case BuiltinType::UFract:
7615     case BuiltinType::ULongFract:
7616     case BuiltinType::SatUShortAccum:
7617     case BuiltinType::SatUAccum:
7618     case BuiltinType::SatULongAccum:
7619     case BuiltinType::SatUShortFract:
7620     case BuiltinType::SatUFract:
7621     case BuiltinType::SatULongFract:
7622       return GCCTypeClass::None;
7623 
7624     case BuiltinType::NullPtr:
7625 
7626     case BuiltinType::ObjCId:
7627     case BuiltinType::ObjCClass:
7628     case BuiltinType::ObjCSel:
7629 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7630     case BuiltinType::Id:
7631 #include "clang/Basic/OpenCLImageTypes.def"
7632     case BuiltinType::OCLSampler:
7633     case BuiltinType::OCLEvent:
7634     case BuiltinType::OCLClkEvent:
7635     case BuiltinType::OCLQueue:
7636     case BuiltinType::OCLReserveID:
7637       return GCCTypeClass::None;
7638 
7639     case BuiltinType::Dependent:
7640       llvm_unreachable("unexpected dependent type");
7641     };
7642     llvm_unreachable("unexpected placeholder type");
7643 
7644   case Type::Enum:
7645     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
7646 
7647   case Type::Pointer:
7648   case Type::ConstantArray:
7649   case Type::VariableArray:
7650   case Type::IncompleteArray:
7651   case Type::FunctionNoProto:
7652   case Type::FunctionProto:
7653     return GCCTypeClass::Pointer;
7654 
7655   case Type::MemberPointer:
7656     return CanTy->isMemberDataPointerType()
7657                ? GCCTypeClass::PointerToDataMember
7658                : GCCTypeClass::PointerToMemberFunction;
7659 
7660   case Type::Complex:
7661     return GCCTypeClass::Complex;
7662 
7663   case Type::Record:
7664     return CanTy->isUnionType() ? GCCTypeClass::Union
7665                                 : GCCTypeClass::ClassOrStruct;
7666 
7667   case Type::Atomic:
7668     // GCC classifies _Atomic T the same as T.
7669     return EvaluateBuiltinClassifyType(
7670         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
7671 
7672   case Type::BlockPointer:
7673   case Type::Vector:
7674   case Type::ExtVector:
7675   case Type::ObjCObject:
7676   case Type::ObjCInterface:
7677   case Type::ObjCObjectPointer:
7678   case Type::Pipe:
7679     // GCC classifies vectors as None. We follow its lead and classify all
7680     // other types that don't fit into the regular classification the same way.
7681     return GCCTypeClass::None;
7682 
7683   case Type::LValueReference:
7684   case Type::RValueReference:
7685     llvm_unreachable("invalid type for expression");
7686   }
7687 
7688   llvm_unreachable("unexpected type class");
7689 }
7690 
7691 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7692 /// as GCC.
7693 static GCCTypeClass
7694 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
7695   // If no argument was supplied, default to None. This isn't
7696   // ideal, however it is what gcc does.
7697   if (E->getNumArgs() == 0)
7698     return GCCTypeClass::None;
7699 
7700   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
7701   // being an ICE, but still folds it to a constant using the type of the first
7702   // argument.
7703   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
7704 }
7705 
7706 /// EvaluateBuiltinConstantPForLValue - Determine the result of
7707 /// __builtin_constant_p when applied to the given lvalue.
7708 ///
7709 /// An lvalue is only "constant" if it is a pointer or reference to the first
7710 /// character of a string literal.
7711 template<typename LValue>
7712 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
7713   const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
7714   return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7715 }
7716 
7717 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7718 /// GCC as we can manage.
7719 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7720   QualType ArgType = Arg->getType();
7721 
7722   // __builtin_constant_p always has one operand. The rules which gcc follows
7723   // are not precisely documented, but are as follows:
7724   //
7725   //  - If the operand is of integral, floating, complex or enumeration type,
7726   //    and can be folded to a known value of that type, it returns 1.
7727   //  - If the operand and can be folded to a pointer to the first character
7728   //    of a string literal (or such a pointer cast to an integral type), it
7729   //    returns 1.
7730   //
7731   // Otherwise, it returns 0.
7732   //
7733   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7734   // its support for this does not currently work.
7735   if (ArgType->isIntegralOrEnumerationType()) {
7736     Expr::EvalResult Result;
7737     if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7738       return false;
7739 
7740     APValue &V = Result.Val;
7741     if (V.getKind() == APValue::Int)
7742       return true;
7743     if (V.getKind() == APValue::LValue)
7744       return EvaluateBuiltinConstantPForLValue(V);
7745   } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7746     return Arg->isEvaluatable(Ctx);
7747   } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7748     LValue LV;
7749     Expr::EvalStatus Status;
7750     EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
7751     if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7752                           : EvaluatePointer(Arg, LV, Info)) &&
7753         !Status.HasSideEffects)
7754       return EvaluateBuiltinConstantPForLValue(LV);
7755   }
7756 
7757   // Anything else isn't considered to be sufficiently constant.
7758   return false;
7759 }
7760 
7761 /// Retrieves the "underlying object type" of the given expression,
7762 /// as used by __builtin_object_size.
7763 static QualType getObjectType(APValue::LValueBase B) {
7764   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7765     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
7766       return VD->getType();
7767   } else if (const Expr *E = B.get<const Expr*>()) {
7768     if (isa<CompoundLiteralExpr>(E))
7769       return E->getType();
7770   }
7771 
7772   return QualType();
7773 }
7774 
7775 /// A more selective version of E->IgnoreParenCasts for
7776 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
7777 /// to change the type of E.
7778 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7779 ///
7780 /// Always returns an RValue with a pointer representation.
7781 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7782   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7783 
7784   auto *NoParens = E->IgnoreParens();
7785   auto *Cast = dyn_cast<CastExpr>(NoParens);
7786   if (Cast == nullptr)
7787     return NoParens;
7788 
7789   // We only conservatively allow a few kinds of casts, because this code is
7790   // inherently a simple solution that seeks to support the common case.
7791   auto CastKind = Cast->getCastKind();
7792   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7793       CastKind != CK_AddressSpaceConversion)
7794     return NoParens;
7795 
7796   auto *SubExpr = Cast->getSubExpr();
7797   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7798     return NoParens;
7799   return ignorePointerCastsAndParens(SubExpr);
7800 }
7801 
7802 /// Checks to see if the given LValue's Designator is at the end of the LValue's
7803 /// record layout. e.g.
7804 ///   struct { struct { int a, b; } fst, snd; } obj;
7805 ///   obj.fst   // no
7806 ///   obj.snd   // yes
7807 ///   obj.fst.a // no
7808 ///   obj.fst.b // no
7809 ///   obj.snd.a // no
7810 ///   obj.snd.b // yes
7811 ///
7812 /// Please note: this function is specialized for how __builtin_object_size
7813 /// views "objects".
7814 ///
7815 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
7816 /// correct result, it will always return true.
7817 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7818   assert(!LVal.Designator.Invalid);
7819 
7820   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7821     const RecordDecl *Parent = FD->getParent();
7822     Invalid = Parent->isInvalidDecl();
7823     if (Invalid || Parent->isUnion())
7824       return true;
7825     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
7826     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7827   };
7828 
7829   auto &Base = LVal.getLValueBase();
7830   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7831     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
7832       bool Invalid;
7833       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7834         return Invalid;
7835     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
7836       for (auto *FD : IFD->chain()) {
7837         bool Invalid;
7838         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7839           return Invalid;
7840       }
7841     }
7842   }
7843 
7844   unsigned I = 0;
7845   QualType BaseType = getType(Base);
7846   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7847     // If we don't know the array bound, conservatively assume we're looking at
7848     // the final array element.
7849     ++I;
7850     if (BaseType->isIncompleteArrayType())
7851       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
7852     else
7853       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7854   }
7855 
7856   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7857     const auto &Entry = LVal.Designator.Entries[I];
7858     if (BaseType->isArrayType()) {
7859       // Because __builtin_object_size treats arrays as objects, we can ignore
7860       // the index iff this is the last array in the Designator.
7861       if (I + 1 == E)
7862         return true;
7863       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7864       uint64_t Index = Entry.ArrayIndex;
7865       if (Index + 1 != CAT->getSize())
7866         return false;
7867       BaseType = CAT->getElementType();
7868     } else if (BaseType->isAnyComplexType()) {
7869       const auto *CT = BaseType->castAs<ComplexType>();
7870       uint64_t Index = Entry.ArrayIndex;
7871       if (Index != 1)
7872         return false;
7873       BaseType = CT->getElementType();
7874     } else if (auto *FD = getAsField(Entry)) {
7875       bool Invalid;
7876       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7877         return Invalid;
7878       BaseType = FD->getType();
7879     } else {
7880       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
7881       return false;
7882     }
7883   }
7884   return true;
7885 }
7886 
7887 /// Tests to see if the LValue has a user-specified designator (that isn't
7888 /// necessarily valid). Note that this always returns 'true' if the LValue has
7889 /// an unsized array as its first designator entry, because there's currently no
7890 /// way to tell if the user typed *foo or foo[0].
7891 static bool refersToCompleteObject(const LValue &LVal) {
7892   if (LVal.Designator.Invalid)
7893     return false;
7894 
7895   if (!LVal.Designator.Entries.empty())
7896     return LVal.Designator.isMostDerivedAnUnsizedArray();
7897 
7898   if (!LVal.InvalidBase)
7899     return true;
7900 
7901   // If `E` is a MemberExpr, then the first part of the designator is hiding in
7902   // the LValueBase.
7903   const auto *E = LVal.Base.dyn_cast<const Expr *>();
7904   return !E || !isa<MemberExpr>(E);
7905 }
7906 
7907 /// Attempts to detect a user writing into a piece of memory that's impossible
7908 /// to figure out the size of by just using types.
7909 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7910   const SubobjectDesignator &Designator = LVal.Designator;
7911   // Notes:
7912   // - Users can only write off of the end when we have an invalid base. Invalid
7913   //   bases imply we don't know where the memory came from.
7914   // - We used to be a bit more aggressive here; we'd only be conservative if
7915   //   the array at the end was flexible, or if it had 0 or 1 elements. This
7916   //   broke some common standard library extensions (PR30346), but was
7917   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
7918   //   with some sort of whitelist. OTOH, it seems that GCC is always
7919   //   conservative with the last element in structs (if it's an array), so our
7920   //   current behavior is more compatible than a whitelisting approach would
7921   //   be.
7922   return LVal.InvalidBase &&
7923          Designator.Entries.size() == Designator.MostDerivedPathLength &&
7924          Designator.MostDerivedIsArrayElement &&
7925          isDesignatorAtObjectEnd(Ctx, LVal);
7926 }
7927 
7928 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7929 /// Fails if the conversion would cause loss of precision.
7930 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7931                                             CharUnits &Result) {
7932   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7933   if (Int.ugt(CharUnitsMax))
7934     return false;
7935   Result = CharUnits::fromQuantity(Int.getZExtValue());
7936   return true;
7937 }
7938 
7939 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7940 /// determine how many bytes exist from the beginning of the object to either
7941 /// the end of the current subobject, or the end of the object itself, depending
7942 /// on what the LValue looks like + the value of Type.
7943 ///
7944 /// If this returns false, the value of Result is undefined.
7945 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7946                                unsigned Type, const LValue &LVal,
7947                                CharUnits &EndOffset) {
7948   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
7949 
7950   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7951     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7952       return false;
7953     return HandleSizeof(Info, ExprLoc, Ty, Result);
7954   };
7955 
7956   // We want to evaluate the size of the entire object. This is a valid fallback
7957   // for when Type=1 and the designator is invalid, because we're asked for an
7958   // upper-bound.
7959   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7960     // Type=3 wants a lower bound, so we can't fall back to this.
7961     if (Type == 3 && !DetermineForCompleteObject)
7962       return false;
7963 
7964     llvm::APInt APEndOffset;
7965     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7966         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7967       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7968 
7969     if (LVal.InvalidBase)
7970       return false;
7971 
7972     QualType BaseTy = getObjectType(LVal.getLValueBase());
7973     return CheckedHandleSizeof(BaseTy, EndOffset);
7974   }
7975 
7976   // We want to evaluate the size of a subobject.
7977   const SubobjectDesignator &Designator = LVal.Designator;
7978 
7979   // The following is a moderately common idiom in C:
7980   //
7981   // struct Foo { int a; char c[1]; };
7982   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7983   // strcpy(&F->c[0], Bar);
7984   //
7985   // In order to not break too much legacy code, we need to support it.
7986   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7987     // If we can resolve this to an alloc_size call, we can hand that back,
7988     // because we know for certain how many bytes there are to write to.
7989     llvm::APInt APEndOffset;
7990     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7991         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7992       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7993 
7994     // If we cannot determine the size of the initial allocation, then we can't
7995     // given an accurate upper-bound. However, we are still able to give
7996     // conservative lower-bounds for Type=3.
7997     if (Type == 1)
7998       return false;
7999   }
8000 
8001   CharUnits BytesPerElem;
8002   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
8003     return false;
8004 
8005   // According to the GCC documentation, we want the size of the subobject
8006   // denoted by the pointer. But that's not quite right -- what we actually
8007   // want is the size of the immediately-enclosing array, if there is one.
8008   int64_t ElemsRemaining;
8009   if (Designator.MostDerivedIsArrayElement &&
8010       Designator.Entries.size() == Designator.MostDerivedPathLength) {
8011     uint64_t ArraySize = Designator.getMostDerivedArraySize();
8012     uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
8013     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
8014   } else {
8015     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
8016   }
8017 
8018   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
8019   return true;
8020 }
8021 
8022 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
8023 /// returns true and stores the result in @p Size.
8024 ///
8025 /// If @p WasError is non-null, this will report whether the failure to evaluate
8026 /// is to be treated as an Error in IntExprEvaluator.
8027 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
8028                                          EvalInfo &Info, uint64_t &Size) {
8029   // Determine the denoted object.
8030   LValue LVal;
8031   {
8032     // The operand of __builtin_object_size is never evaluated for side-effects.
8033     // If there are any, but we can determine the pointed-to object anyway, then
8034     // ignore the side-effects.
8035     SpeculativeEvaluationRAII SpeculativeEval(Info);
8036     IgnoreSideEffectsRAII Fold(Info);
8037 
8038     if (E->isGLValue()) {
8039       // It's possible for us to be given GLValues if we're called via
8040       // Expr::tryEvaluateObjectSize.
8041       APValue RVal;
8042       if (!EvaluateAsRValue(Info, E, RVal))
8043         return false;
8044       LVal.setFrom(Info.Ctx, RVal);
8045     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
8046                                 /*InvalidBaseOK=*/true))
8047       return false;
8048   }
8049 
8050   // If we point to before the start of the object, there are no accessible
8051   // bytes.
8052   if (LVal.getLValueOffset().isNegative()) {
8053     Size = 0;
8054     return true;
8055   }
8056 
8057   CharUnits EndOffset;
8058   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
8059     return false;
8060 
8061   // If we've fallen outside of the end offset, just pretend there's nothing to
8062   // write to/read from.
8063   if (EndOffset <= LVal.getLValueOffset())
8064     Size = 0;
8065   else
8066     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
8067   return true;
8068 }
8069 
8070 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
8071   if (unsigned BuiltinOp = E->getBuiltinCallee())
8072     return VisitBuiltinCallExpr(E, BuiltinOp);
8073 
8074   return ExprEvaluatorBaseTy::VisitCallExpr(E);
8075 }
8076 
8077 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8078                                             unsigned BuiltinOp) {
8079   switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
8080   default:
8081     return ExprEvaluatorBaseTy::VisitCallExpr(E);
8082 
8083   case Builtin::BI__builtin_object_size: {
8084     // The type was checked when we built the expression.
8085     unsigned Type =
8086         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8087     assert(Type <= 3 && "unexpected type");
8088 
8089     uint64_t Size;
8090     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
8091       return Success(Size, E);
8092 
8093     if (E->getArg(0)->HasSideEffects(Info.Ctx))
8094       return Success((Type & 2) ? 0 : -1, E);
8095 
8096     // Expression had no side effects, but we couldn't statically determine the
8097     // size of the referenced object.
8098     switch (Info.EvalMode) {
8099     case EvalInfo::EM_ConstantExpression:
8100     case EvalInfo::EM_PotentialConstantExpression:
8101     case EvalInfo::EM_ConstantFold:
8102     case EvalInfo::EM_EvaluateForOverflow:
8103     case EvalInfo::EM_IgnoreSideEffects:
8104       // Leave it to IR generation.
8105       return Error(E);
8106     case EvalInfo::EM_ConstantExpressionUnevaluated:
8107     case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
8108       // Reduce it to a constant now.
8109       return Success((Type & 2) ? 0 : -1, E);
8110     }
8111 
8112     llvm_unreachable("unexpected EvalMode");
8113   }
8114 
8115   case Builtin::BI__builtin_bswap16:
8116   case Builtin::BI__builtin_bswap32:
8117   case Builtin::BI__builtin_bswap64: {
8118     APSInt Val;
8119     if (!EvaluateInteger(E->getArg(0), Val, Info))
8120       return false;
8121 
8122     return Success(Val.byteSwap(), E);
8123   }
8124 
8125   case Builtin::BI__builtin_classify_type:
8126     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
8127 
8128   case Builtin::BI__builtin_clrsb:
8129   case Builtin::BI__builtin_clrsbl:
8130   case Builtin::BI__builtin_clrsbll: {
8131     APSInt Val;
8132     if (!EvaluateInteger(E->getArg(0), Val, Info))
8133       return false;
8134 
8135     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
8136   }
8137 
8138   case Builtin::BI__builtin_clz:
8139   case Builtin::BI__builtin_clzl:
8140   case Builtin::BI__builtin_clzll:
8141   case Builtin::BI__builtin_clzs: {
8142     APSInt Val;
8143     if (!EvaluateInteger(E->getArg(0), Val, Info))
8144       return false;
8145     if (!Val)
8146       return Error(E);
8147 
8148     return Success(Val.countLeadingZeros(), E);
8149   }
8150 
8151   case Builtin::BI__builtin_constant_p:
8152     return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
8153 
8154   case Builtin::BI__builtin_ctz:
8155   case Builtin::BI__builtin_ctzl:
8156   case Builtin::BI__builtin_ctzll:
8157   case Builtin::BI__builtin_ctzs: {
8158     APSInt Val;
8159     if (!EvaluateInteger(E->getArg(0), Val, Info))
8160       return false;
8161     if (!Val)
8162       return Error(E);
8163 
8164     return Success(Val.countTrailingZeros(), E);
8165   }
8166 
8167   case Builtin::BI__builtin_eh_return_data_regno: {
8168     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8169     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
8170     return Success(Operand, E);
8171   }
8172 
8173   case Builtin::BI__builtin_expect:
8174     return Visit(E->getArg(0));
8175 
8176   case Builtin::BI__builtin_ffs:
8177   case Builtin::BI__builtin_ffsl:
8178   case Builtin::BI__builtin_ffsll: {
8179     APSInt Val;
8180     if (!EvaluateInteger(E->getArg(0), Val, Info))
8181       return false;
8182 
8183     unsigned N = Val.countTrailingZeros();
8184     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
8185   }
8186 
8187   case Builtin::BI__builtin_fpclassify: {
8188     APFloat Val(0.0);
8189     if (!EvaluateFloat(E->getArg(5), Val, Info))
8190       return false;
8191     unsigned Arg;
8192     switch (Val.getCategory()) {
8193     case APFloat::fcNaN: Arg = 0; break;
8194     case APFloat::fcInfinity: Arg = 1; break;
8195     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
8196     case APFloat::fcZero: Arg = 4; break;
8197     }
8198     return Visit(E->getArg(Arg));
8199   }
8200 
8201   case Builtin::BI__builtin_isinf_sign: {
8202     APFloat Val(0.0);
8203     return EvaluateFloat(E->getArg(0), Val, Info) &&
8204            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
8205   }
8206 
8207   case Builtin::BI__builtin_isinf: {
8208     APFloat Val(0.0);
8209     return EvaluateFloat(E->getArg(0), Val, Info) &&
8210            Success(Val.isInfinity() ? 1 : 0, E);
8211   }
8212 
8213   case Builtin::BI__builtin_isfinite: {
8214     APFloat Val(0.0);
8215     return EvaluateFloat(E->getArg(0), Val, Info) &&
8216            Success(Val.isFinite() ? 1 : 0, E);
8217   }
8218 
8219   case Builtin::BI__builtin_isnan: {
8220     APFloat Val(0.0);
8221     return EvaluateFloat(E->getArg(0), Val, Info) &&
8222            Success(Val.isNaN() ? 1 : 0, E);
8223   }
8224 
8225   case Builtin::BI__builtin_isnormal: {
8226     APFloat Val(0.0);
8227     return EvaluateFloat(E->getArg(0), Val, Info) &&
8228            Success(Val.isNormal() ? 1 : 0, E);
8229   }
8230 
8231   case Builtin::BI__builtin_parity:
8232   case Builtin::BI__builtin_parityl:
8233   case Builtin::BI__builtin_parityll: {
8234     APSInt Val;
8235     if (!EvaluateInteger(E->getArg(0), Val, Info))
8236       return false;
8237 
8238     return Success(Val.countPopulation() % 2, E);
8239   }
8240 
8241   case Builtin::BI__builtin_popcount:
8242   case Builtin::BI__builtin_popcountl:
8243   case Builtin::BI__builtin_popcountll: {
8244     APSInt Val;
8245     if (!EvaluateInteger(E->getArg(0), Val, Info))
8246       return false;
8247 
8248     return Success(Val.countPopulation(), E);
8249   }
8250 
8251   case Builtin::BIstrlen:
8252   case Builtin::BIwcslen:
8253     // A call to strlen is not a constant expression.
8254     if (Info.getLangOpts().CPlusPlus11)
8255       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8256         << /*isConstexpr*/0 << /*isConstructor*/0
8257         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8258     else
8259       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8260     LLVM_FALLTHROUGH;
8261   case Builtin::BI__builtin_strlen:
8262   case Builtin::BI__builtin_wcslen: {
8263     // As an extension, we support __builtin_strlen() as a constant expression,
8264     // and support folding strlen() to a constant.
8265     LValue String;
8266     if (!EvaluatePointer(E->getArg(0), String, Info))
8267       return false;
8268 
8269     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
8270 
8271     // Fast path: if it's a string literal, search the string value.
8272     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
8273             String.getLValueBase().dyn_cast<const Expr *>())) {
8274       // The string literal may have embedded null characters. Find the first
8275       // one and truncate there.
8276       StringRef Str = S->getBytes();
8277       int64_t Off = String.Offset.getQuantity();
8278       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
8279           S->getCharByteWidth() == 1 &&
8280           // FIXME: Add fast-path for wchar_t too.
8281           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
8282         Str = Str.substr(Off);
8283 
8284         StringRef::size_type Pos = Str.find(0);
8285         if (Pos != StringRef::npos)
8286           Str = Str.substr(0, Pos);
8287 
8288         return Success(Str.size(), E);
8289       }
8290 
8291       // Fall through to slow path to issue appropriate diagnostic.
8292     }
8293 
8294     // Slow path: scan the bytes of the string looking for the terminating 0.
8295     for (uint64_t Strlen = 0; /**/; ++Strlen) {
8296       APValue Char;
8297       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
8298           !Char.isInt())
8299         return false;
8300       if (!Char.getInt())
8301         return Success(Strlen, E);
8302       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
8303         return false;
8304     }
8305   }
8306 
8307   case Builtin::BIstrcmp:
8308   case Builtin::BIwcscmp:
8309   case Builtin::BIstrncmp:
8310   case Builtin::BIwcsncmp:
8311   case Builtin::BImemcmp:
8312   case Builtin::BIwmemcmp:
8313     // A call to strlen is not a constant expression.
8314     if (Info.getLangOpts().CPlusPlus11)
8315       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8316         << /*isConstexpr*/0 << /*isConstructor*/0
8317         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8318     else
8319       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8320     LLVM_FALLTHROUGH;
8321   case Builtin::BI__builtin_strcmp:
8322   case Builtin::BI__builtin_wcscmp:
8323   case Builtin::BI__builtin_strncmp:
8324   case Builtin::BI__builtin_wcsncmp:
8325   case Builtin::BI__builtin_memcmp:
8326   case Builtin::BI__builtin_wmemcmp: {
8327     LValue String1, String2;
8328     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
8329         !EvaluatePointer(E->getArg(1), String2, Info))
8330       return false;
8331 
8332     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
8333 
8334     uint64_t MaxLength = uint64_t(-1);
8335     if (BuiltinOp != Builtin::BIstrcmp &&
8336         BuiltinOp != Builtin::BIwcscmp &&
8337         BuiltinOp != Builtin::BI__builtin_strcmp &&
8338         BuiltinOp != Builtin::BI__builtin_wcscmp) {
8339       APSInt N;
8340       if (!EvaluateInteger(E->getArg(2), N, Info))
8341         return false;
8342       MaxLength = N.getExtValue();
8343     }
8344     bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
8345                        BuiltinOp != Builtin::BIwmemcmp &&
8346                        BuiltinOp != Builtin::BI__builtin_memcmp &&
8347                        BuiltinOp != Builtin::BI__builtin_wmemcmp);
8348     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
8349                   BuiltinOp == Builtin::BIwcsncmp ||
8350                   BuiltinOp == Builtin::BIwmemcmp ||
8351                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
8352                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
8353                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
8354     for (; MaxLength; --MaxLength) {
8355       APValue Char1, Char2;
8356       if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
8357           !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
8358           !Char1.isInt() || !Char2.isInt())
8359         return false;
8360       if (Char1.getInt() != Char2.getInt()) {
8361         if (IsWide) // wmemcmp compares with wchar_t signedness.
8362           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
8363         // memcmp always compares unsigned chars.
8364         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
8365       }
8366       if (StopAtNull && !Char1.getInt())
8367         return Success(0, E);
8368       assert(!(StopAtNull && !Char2.getInt()));
8369       if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
8370           !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
8371         return false;
8372     }
8373     // We hit the strncmp / memcmp limit.
8374     return Success(0, E);
8375   }
8376 
8377   case Builtin::BI__atomic_always_lock_free:
8378   case Builtin::BI__atomic_is_lock_free:
8379   case Builtin::BI__c11_atomic_is_lock_free: {
8380     APSInt SizeVal;
8381     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
8382       return false;
8383 
8384     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
8385     // of two less than the maximum inline atomic width, we know it is
8386     // lock-free.  If the size isn't a power of two, or greater than the
8387     // maximum alignment where we promote atomics, we know it is not lock-free
8388     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
8389     // the answer can only be determined at runtime; for example, 16-byte
8390     // atomics have lock-free implementations on some, but not all,
8391     // x86-64 processors.
8392 
8393     // Check power-of-two.
8394     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
8395     if (Size.isPowerOfTwo()) {
8396       // Check against inlining width.
8397       unsigned InlineWidthBits =
8398           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
8399       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
8400         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
8401             Size == CharUnits::One() ||
8402             E->getArg(1)->isNullPointerConstant(Info.Ctx,
8403                                                 Expr::NPC_NeverValueDependent))
8404           // OK, we will inline appropriately-aligned operations of this size,
8405           // and _Atomic(T) is appropriately-aligned.
8406           return Success(1, E);
8407 
8408         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
8409           castAs<PointerType>()->getPointeeType();
8410         if (!PointeeType->isIncompleteType() &&
8411             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
8412           // OK, we will inline operations on this object.
8413           return Success(1, E);
8414         }
8415       }
8416     }
8417 
8418     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
8419         Success(0, E) : Error(E);
8420   }
8421   case Builtin::BIomp_is_initial_device:
8422     // We can decide statically which value the runtime would return if called.
8423     return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
8424   case Builtin::BI__builtin_add_overflow:
8425   case Builtin::BI__builtin_sub_overflow:
8426   case Builtin::BI__builtin_mul_overflow:
8427   case Builtin::BI__builtin_sadd_overflow:
8428   case Builtin::BI__builtin_uadd_overflow:
8429   case Builtin::BI__builtin_uaddl_overflow:
8430   case Builtin::BI__builtin_uaddll_overflow:
8431   case Builtin::BI__builtin_usub_overflow:
8432   case Builtin::BI__builtin_usubl_overflow:
8433   case Builtin::BI__builtin_usubll_overflow:
8434   case Builtin::BI__builtin_umul_overflow:
8435   case Builtin::BI__builtin_umull_overflow:
8436   case Builtin::BI__builtin_umulll_overflow:
8437   case Builtin::BI__builtin_saddl_overflow:
8438   case Builtin::BI__builtin_saddll_overflow:
8439   case Builtin::BI__builtin_ssub_overflow:
8440   case Builtin::BI__builtin_ssubl_overflow:
8441   case Builtin::BI__builtin_ssubll_overflow:
8442   case Builtin::BI__builtin_smul_overflow:
8443   case Builtin::BI__builtin_smull_overflow:
8444   case Builtin::BI__builtin_smulll_overflow: {
8445     LValue ResultLValue;
8446     APSInt LHS, RHS;
8447 
8448     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
8449     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
8450         !EvaluateInteger(E->getArg(1), RHS, Info) ||
8451         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
8452       return false;
8453 
8454     APSInt Result;
8455     bool DidOverflow = false;
8456 
8457     // If the types don't have to match, enlarge all 3 to the largest of them.
8458     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8459         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8460         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8461       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
8462                       ResultType->isSignedIntegerOrEnumerationType();
8463       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
8464                       ResultType->isSignedIntegerOrEnumerationType();
8465       uint64_t LHSSize = LHS.getBitWidth();
8466       uint64_t RHSSize = RHS.getBitWidth();
8467       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
8468       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
8469 
8470       // Add an additional bit if the signedness isn't uniformly agreed to. We
8471       // could do this ONLY if there is a signed and an unsigned that both have
8472       // MaxBits, but the code to check that is pretty nasty.  The issue will be
8473       // caught in the shrink-to-result later anyway.
8474       if (IsSigned && !AllSigned)
8475         ++MaxBits;
8476 
8477       LHS = APSInt(IsSigned ? LHS.sextOrSelf(MaxBits) : LHS.zextOrSelf(MaxBits),
8478                    !IsSigned);
8479       RHS = APSInt(IsSigned ? RHS.sextOrSelf(MaxBits) : RHS.zextOrSelf(MaxBits),
8480                    !IsSigned);
8481       Result = APSInt(MaxBits, !IsSigned);
8482     }
8483 
8484     // Find largest int.
8485     switch (BuiltinOp) {
8486     default:
8487       llvm_unreachable("Invalid value for BuiltinOp");
8488     case Builtin::BI__builtin_add_overflow:
8489     case Builtin::BI__builtin_sadd_overflow:
8490     case Builtin::BI__builtin_saddl_overflow:
8491     case Builtin::BI__builtin_saddll_overflow:
8492     case Builtin::BI__builtin_uadd_overflow:
8493     case Builtin::BI__builtin_uaddl_overflow:
8494     case Builtin::BI__builtin_uaddll_overflow:
8495       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
8496                               : LHS.uadd_ov(RHS, DidOverflow);
8497       break;
8498     case Builtin::BI__builtin_sub_overflow:
8499     case Builtin::BI__builtin_ssub_overflow:
8500     case Builtin::BI__builtin_ssubl_overflow:
8501     case Builtin::BI__builtin_ssubll_overflow:
8502     case Builtin::BI__builtin_usub_overflow:
8503     case Builtin::BI__builtin_usubl_overflow:
8504     case Builtin::BI__builtin_usubll_overflow:
8505       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
8506                               : LHS.usub_ov(RHS, DidOverflow);
8507       break;
8508     case Builtin::BI__builtin_mul_overflow:
8509     case Builtin::BI__builtin_smul_overflow:
8510     case Builtin::BI__builtin_smull_overflow:
8511     case Builtin::BI__builtin_smulll_overflow:
8512     case Builtin::BI__builtin_umul_overflow:
8513     case Builtin::BI__builtin_umull_overflow:
8514     case Builtin::BI__builtin_umulll_overflow:
8515       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
8516                               : LHS.umul_ov(RHS, DidOverflow);
8517       break;
8518     }
8519 
8520     // In the case where multiple sizes are allowed, truncate and see if
8521     // the values are the same.
8522     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8523         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8524         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8525       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
8526       // since it will give us the behavior of a TruncOrSelf in the case where
8527       // its parameter <= its size.  We previously set Result to be at least the
8528       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
8529       // will work exactly like TruncOrSelf.
8530       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
8531       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
8532 
8533       if (!APSInt::isSameValue(Temp, Result))
8534         DidOverflow = true;
8535       Result = Temp;
8536     }
8537 
8538     APValue APV{Result};
8539     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
8540       return false;
8541     return Success(DidOverflow, E);
8542   }
8543   }
8544 }
8545 
8546 /// Determine whether this is a pointer past the end of the complete
8547 /// object referred to by the lvalue.
8548 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
8549                                             const LValue &LV) {
8550   // A null pointer can be viewed as being "past the end" but we don't
8551   // choose to look at it that way here.
8552   if (!LV.getLValueBase())
8553     return false;
8554 
8555   // If the designator is valid and refers to a subobject, we're not pointing
8556   // past the end.
8557   if (!LV.getLValueDesignator().Invalid &&
8558       !LV.getLValueDesignator().isOnePastTheEnd())
8559     return false;
8560 
8561   // A pointer to an incomplete type might be past-the-end if the type's size is
8562   // zero.  We cannot tell because the type is incomplete.
8563   QualType Ty = getType(LV.getLValueBase());
8564   if (Ty->isIncompleteType())
8565     return true;
8566 
8567   // We're a past-the-end pointer if we point to the byte after the object,
8568   // no matter what our type or path is.
8569   auto Size = Ctx.getTypeSizeInChars(Ty);
8570   return LV.getLValueOffset() == Size;
8571 }
8572 
8573 namespace {
8574 
8575 /// Data recursive integer evaluator of certain binary operators.
8576 ///
8577 /// We use a data recursive algorithm for binary operators so that we are able
8578 /// to handle extreme cases of chained binary operators without causing stack
8579 /// overflow.
8580 class DataRecursiveIntBinOpEvaluator {
8581   struct EvalResult {
8582     APValue Val;
8583     bool Failed;
8584 
8585     EvalResult() : Failed(false) { }
8586 
8587     void swap(EvalResult &RHS) {
8588       Val.swap(RHS.Val);
8589       Failed = RHS.Failed;
8590       RHS.Failed = false;
8591     }
8592   };
8593 
8594   struct Job {
8595     const Expr *E;
8596     EvalResult LHSResult; // meaningful only for binary operator expression.
8597     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
8598 
8599     Job() = default;
8600     Job(Job &&) = default;
8601 
8602     void startSpeculativeEval(EvalInfo &Info) {
8603       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
8604     }
8605 
8606   private:
8607     SpeculativeEvaluationRAII SpecEvalRAII;
8608   };
8609 
8610   SmallVector<Job, 16> Queue;
8611 
8612   IntExprEvaluator &IntEval;
8613   EvalInfo &Info;
8614   APValue &FinalResult;
8615 
8616 public:
8617   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8618     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8619 
8620   /// True if \param E is a binary operator that we are going to handle
8621   /// data recursively.
8622   /// We handle binary operators that are comma, logical, or that have operands
8623   /// with integral or enumeration type.
8624   static bool shouldEnqueue(const BinaryOperator *E) {
8625     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
8626            (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
8627             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8628             E->getRHS()->getType()->isIntegralOrEnumerationType());
8629   }
8630 
8631   bool Traverse(const BinaryOperator *E) {
8632     enqueue(E);
8633     EvalResult PrevResult;
8634     while (!Queue.empty())
8635       process(PrevResult);
8636 
8637     if (PrevResult.Failed) return false;
8638 
8639     FinalResult.swap(PrevResult.Val);
8640     return true;
8641   }
8642 
8643 private:
8644   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8645     return IntEval.Success(Value, E, Result);
8646   }
8647   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8648     return IntEval.Success(Value, E, Result);
8649   }
8650   bool Error(const Expr *E) {
8651     return IntEval.Error(E);
8652   }
8653   bool Error(const Expr *E, diag::kind D) {
8654     return IntEval.Error(E, D);
8655   }
8656 
8657   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8658     return Info.CCEDiag(E, D);
8659   }
8660 
8661   // Returns true if visiting the RHS is necessary, false otherwise.
8662   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
8663                          bool &SuppressRHSDiags);
8664 
8665   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8666                   const BinaryOperator *E, APValue &Result);
8667 
8668   void EvaluateExpr(const Expr *E, EvalResult &Result) {
8669     Result.Failed = !Evaluate(Result.Val, Info, E);
8670     if (Result.Failed)
8671       Result.Val = APValue();
8672   }
8673 
8674   void process(EvalResult &Result);
8675 
8676   void enqueue(const Expr *E) {
8677     E = E->IgnoreParens();
8678     Queue.resize(Queue.size()+1);
8679     Queue.back().E = E;
8680     Queue.back().Kind = Job::AnyExprKind;
8681   }
8682 };
8683 
8684 }
8685 
8686 bool DataRecursiveIntBinOpEvaluator::
8687        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
8688                          bool &SuppressRHSDiags) {
8689   if (E->getOpcode() == BO_Comma) {
8690     // Ignore LHS but note if we could not evaluate it.
8691     if (LHSResult.Failed)
8692       return Info.noteSideEffect();
8693     return true;
8694   }
8695 
8696   if (E->isLogicalOp()) {
8697     bool LHSAsBool;
8698     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
8699       // We were able to evaluate the LHS, see if we can get away with not
8700       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
8701       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8702         Success(LHSAsBool, E, LHSResult.Val);
8703         return false; // Ignore RHS
8704       }
8705     } else {
8706       LHSResult.Failed = true;
8707 
8708       // Since we weren't able to evaluate the left hand side, it
8709       // might have had side effects.
8710       if (!Info.noteSideEffect())
8711         return false;
8712 
8713       // We can't evaluate the LHS; however, sometimes the result
8714       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8715       // Don't ignore RHS and suppress diagnostics from this arm.
8716       SuppressRHSDiags = true;
8717     }
8718 
8719     return true;
8720   }
8721 
8722   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8723          E->getRHS()->getType()->isIntegralOrEnumerationType());
8724 
8725   if (LHSResult.Failed && !Info.noteFailure())
8726     return false; // Ignore RHS;
8727 
8728   return true;
8729 }
8730 
8731 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8732                                     bool IsSub) {
8733   // Compute the new offset in the appropriate width, wrapping at 64 bits.
8734   // FIXME: When compiling for a 32-bit target, we should use 32-bit
8735   // offsets.
8736   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8737   CharUnits &Offset = LVal.getLValueOffset();
8738   uint64_t Offset64 = Offset.getQuantity();
8739   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8740   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8741                                          : Offset64 + Index64);
8742 }
8743 
8744 bool DataRecursiveIntBinOpEvaluator::
8745        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8746                   const BinaryOperator *E, APValue &Result) {
8747   if (E->getOpcode() == BO_Comma) {
8748     if (RHSResult.Failed)
8749       return false;
8750     Result = RHSResult.Val;
8751     return true;
8752   }
8753 
8754   if (E->isLogicalOp()) {
8755     bool lhsResult, rhsResult;
8756     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8757     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
8758 
8759     if (LHSIsOK) {
8760       if (RHSIsOK) {
8761         if (E->getOpcode() == BO_LOr)
8762           return Success(lhsResult || rhsResult, E, Result);
8763         else
8764           return Success(lhsResult && rhsResult, E, Result);
8765       }
8766     } else {
8767       if (RHSIsOK) {
8768         // We can't evaluate the LHS; however, sometimes the result
8769         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8770         if (rhsResult == (E->getOpcode() == BO_LOr))
8771           return Success(rhsResult, E, Result);
8772       }
8773     }
8774 
8775     return false;
8776   }
8777 
8778   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8779          E->getRHS()->getType()->isIntegralOrEnumerationType());
8780 
8781   if (LHSResult.Failed || RHSResult.Failed)
8782     return false;
8783 
8784   const APValue &LHSVal = LHSResult.Val;
8785   const APValue &RHSVal = RHSResult.Val;
8786 
8787   // Handle cases like (unsigned long)&a + 4.
8788   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8789     Result = LHSVal;
8790     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
8791     return true;
8792   }
8793 
8794   // Handle cases like 4 + (unsigned long)&a
8795   if (E->getOpcode() == BO_Add &&
8796       RHSVal.isLValue() && LHSVal.isInt()) {
8797     Result = RHSVal;
8798     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
8799     return true;
8800   }
8801 
8802   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8803     // Handle (intptr_t)&&A - (intptr_t)&&B.
8804     if (!LHSVal.getLValueOffset().isZero() ||
8805         !RHSVal.getLValueOffset().isZero())
8806       return false;
8807     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8808     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8809     if (!LHSExpr || !RHSExpr)
8810       return false;
8811     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8812     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8813     if (!LHSAddrExpr || !RHSAddrExpr)
8814       return false;
8815     // Make sure both labels come from the same function.
8816     if (LHSAddrExpr->getLabel()->getDeclContext() !=
8817         RHSAddrExpr->getLabel()->getDeclContext())
8818       return false;
8819     Result = APValue(LHSAddrExpr, RHSAddrExpr);
8820     return true;
8821   }
8822 
8823   // All the remaining cases expect both operands to be an integer
8824   if (!LHSVal.isInt() || !RHSVal.isInt())
8825     return Error(E);
8826 
8827   // Set up the width and signedness manually, in case it can't be deduced
8828   // from the operation we're performing.
8829   // FIXME: Don't do this in the cases where we can deduce it.
8830   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8831                E->getType()->isUnsignedIntegerOrEnumerationType());
8832   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8833                          RHSVal.getInt(), Value))
8834     return false;
8835   return Success(Value, E, Result);
8836 }
8837 
8838 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
8839   Job &job = Queue.back();
8840 
8841   switch (job.Kind) {
8842     case Job::AnyExprKind: {
8843       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8844         if (shouldEnqueue(Bop)) {
8845           job.Kind = Job::BinOpKind;
8846           enqueue(Bop->getLHS());
8847           return;
8848         }
8849       }
8850 
8851       EvaluateExpr(job.E, Result);
8852       Queue.pop_back();
8853       return;
8854     }
8855 
8856     case Job::BinOpKind: {
8857       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8858       bool SuppressRHSDiags = false;
8859       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
8860         Queue.pop_back();
8861         return;
8862       }
8863       if (SuppressRHSDiags)
8864         job.startSpeculativeEval(Info);
8865       job.LHSResult.swap(Result);
8866       job.Kind = Job::BinOpVisitedLHSKind;
8867       enqueue(Bop->getRHS());
8868       return;
8869     }
8870 
8871     case Job::BinOpVisitedLHSKind: {
8872       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8873       EvalResult RHS;
8874       RHS.swap(Result);
8875       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
8876       Queue.pop_back();
8877       return;
8878     }
8879   }
8880 
8881   llvm_unreachable("Invalid Job::Kind!");
8882 }
8883 
8884 namespace {
8885 /// Used when we determine that we should fail, but can keep evaluating prior to
8886 /// noting that we had a failure.
8887 class DelayedNoteFailureRAII {
8888   EvalInfo &Info;
8889   bool NoteFailure;
8890 
8891 public:
8892   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8893       : Info(Info), NoteFailure(NoteFailure) {}
8894   ~DelayedNoteFailureRAII() {
8895     if (NoteFailure) {
8896       bool ContinueAfterFailure = Info.noteFailure();
8897       (void)ContinueAfterFailure;
8898       assert(ContinueAfterFailure &&
8899              "Shouldn't have kept evaluating on failure.");
8900     }
8901   }
8902 };
8903 }
8904 
8905 template <class SuccessCB, class AfterCB>
8906 static bool
8907 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
8908                                  SuccessCB &&Success, AfterCB &&DoAfter) {
8909   assert(E->isComparisonOp() && "expected comparison operator");
8910   assert((E->getOpcode() == BO_Cmp ||
8911           E->getType()->isIntegralOrEnumerationType()) &&
8912          "unsupported binary expression evaluation");
8913   auto Error = [&](const Expr *E) {
8914     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
8915     return false;
8916   };
8917 
8918   using CCR = ComparisonCategoryResult;
8919   bool IsRelational = E->isRelationalOp();
8920   bool IsEquality = E->isEqualityOp();
8921   if (E->getOpcode() == BO_Cmp) {
8922     const ComparisonCategoryInfo &CmpInfo =
8923         Info.Ctx.CompCategories.getInfoForType(E->getType());
8924     IsRelational = CmpInfo.isOrdered();
8925     IsEquality = CmpInfo.isEquality();
8926   }
8927 
8928   QualType LHSTy = E->getLHS()->getType();
8929   QualType RHSTy = E->getRHS()->getType();
8930 
8931   if (LHSTy->isIntegralOrEnumerationType() &&
8932       RHSTy->isIntegralOrEnumerationType()) {
8933     APSInt LHS, RHS;
8934     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
8935     if (!LHSOK && !Info.noteFailure())
8936       return false;
8937     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
8938       return false;
8939     if (LHS < RHS)
8940       return Success(CCR::Less, E);
8941     if (LHS > RHS)
8942       return Success(CCR::Greater, E);
8943     return Success(CCR::Equal, E);
8944   }
8945 
8946   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
8947     ComplexValue LHS, RHS;
8948     bool LHSOK;
8949     if (E->isAssignmentOp()) {
8950       LValue LV;
8951       EvaluateLValue(E->getLHS(), LV, Info);
8952       LHSOK = false;
8953     } else if (LHSTy->isRealFloatingType()) {
8954       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8955       if (LHSOK) {
8956         LHS.makeComplexFloat();
8957         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8958       }
8959     } else {
8960       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8961     }
8962     if (!LHSOK && !Info.noteFailure())
8963       return false;
8964 
8965     if (E->getRHS()->getType()->isRealFloatingType()) {
8966       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8967         return false;
8968       RHS.makeComplexFloat();
8969       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8970     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
8971       return false;
8972 
8973     if (LHS.isComplexFloat()) {
8974       APFloat::cmpResult CR_r =
8975         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
8976       APFloat::cmpResult CR_i =
8977         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8978       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
8979       return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
8980     } else {
8981       assert(IsEquality && "invalid complex comparison");
8982       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8983                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
8984       return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
8985     }
8986   }
8987 
8988   if (LHSTy->isRealFloatingType() &&
8989       RHSTy->isRealFloatingType()) {
8990     APFloat RHS(0.0), LHS(0.0);
8991 
8992     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
8993     if (!LHSOK && !Info.noteFailure())
8994       return false;
8995 
8996     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
8997       return false;
8998 
8999     assert(E->isComparisonOp() && "Invalid binary operator!");
9000     auto GetCmpRes = [&]() {
9001       switch (LHS.compare(RHS)) {
9002       case APFloat::cmpEqual:
9003         return CCR::Equal;
9004       case APFloat::cmpLessThan:
9005         return CCR::Less;
9006       case APFloat::cmpGreaterThan:
9007         return CCR::Greater;
9008       case APFloat::cmpUnordered:
9009         return CCR::Unordered;
9010       }
9011       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
9012     };
9013     return Success(GetCmpRes(), E);
9014   }
9015 
9016   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
9017     LValue LHSValue, RHSValue;
9018 
9019     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9020     if (!LHSOK && !Info.noteFailure())
9021       return false;
9022 
9023     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9024       return false;
9025 
9026     // Reject differing bases from the normal codepath; we special-case
9027     // comparisons to null.
9028     if (!HasSameBase(LHSValue, RHSValue)) {
9029       // Inequalities and subtractions between unrelated pointers have
9030       // unspecified or undefined behavior.
9031       if (!IsEquality)
9032         return Error(E);
9033       // A constant address may compare equal to the address of a symbol.
9034       // The one exception is that address of an object cannot compare equal
9035       // to a null pointer constant.
9036       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
9037           (!RHSValue.Base && !RHSValue.Offset.isZero()))
9038         return Error(E);
9039       // It's implementation-defined whether distinct literals will have
9040       // distinct addresses. In clang, the result of such a comparison is
9041       // unspecified, so it is not a constant expression. However, we do know
9042       // that the address of a literal will be non-null.
9043       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
9044           LHSValue.Base && RHSValue.Base)
9045         return Error(E);
9046       // We can't tell whether weak symbols will end up pointing to the same
9047       // object.
9048       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
9049         return Error(E);
9050       // We can't compare the address of the start of one object with the
9051       // past-the-end address of another object, per C++ DR1652.
9052       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
9053            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
9054           (RHSValue.Base && RHSValue.Offset.isZero() &&
9055            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
9056         return Error(E);
9057       // We can't tell whether an object is at the same address as another
9058       // zero sized object.
9059       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
9060           (LHSValue.Base && isZeroSized(RHSValue)))
9061         return Error(E);
9062       return Success(CCR::Nonequal, E);
9063     }
9064 
9065     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9066     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
9067 
9068     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9069     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
9070 
9071     // C++11 [expr.rel]p3:
9072     //   Pointers to void (after pointer conversions) can be compared, with a
9073     //   result defined as follows: If both pointers represent the same
9074     //   address or are both the null pointer value, the result is true if the
9075     //   operator is <= or >= and false otherwise; otherwise the result is
9076     //   unspecified.
9077     // We interpret this as applying to pointers to *cv* void.
9078     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
9079       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
9080 
9081     // C++11 [expr.rel]p2:
9082     // - If two pointers point to non-static data members of the same object,
9083     //   or to subobjects or array elements fo such members, recursively, the
9084     //   pointer to the later declared member compares greater provided the
9085     //   two members have the same access control and provided their class is
9086     //   not a union.
9087     //   [...]
9088     // - Otherwise pointer comparisons are unspecified.
9089     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
9090       bool WasArrayIndex;
9091       unsigned Mismatch = FindDesignatorMismatch(
9092           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
9093       // At the point where the designators diverge, the comparison has a
9094       // specified value if:
9095       //  - we are comparing array indices
9096       //  - we are comparing fields of a union, or fields with the same access
9097       // Otherwise, the result is unspecified and thus the comparison is not a
9098       // constant expression.
9099       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
9100           Mismatch < RHSDesignator.Entries.size()) {
9101         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
9102         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
9103         if (!LF && !RF)
9104           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
9105         else if (!LF)
9106           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
9107               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
9108               << RF->getParent() << RF;
9109         else if (!RF)
9110           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
9111               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
9112               << LF->getParent() << LF;
9113         else if (!LF->getParent()->isUnion() &&
9114                  LF->getAccess() != RF->getAccess())
9115           Info.CCEDiag(E,
9116                        diag::note_constexpr_pointer_comparison_differing_access)
9117               << LF << LF->getAccess() << RF << RF->getAccess()
9118               << LF->getParent();
9119       }
9120     }
9121 
9122     // The comparison here must be unsigned, and performed with the same
9123     // width as the pointer.
9124     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
9125     uint64_t CompareLHS = LHSOffset.getQuantity();
9126     uint64_t CompareRHS = RHSOffset.getQuantity();
9127     assert(PtrSize <= 64 && "Unexpected pointer width");
9128     uint64_t Mask = ~0ULL >> (64 - PtrSize);
9129     CompareLHS &= Mask;
9130     CompareRHS &= Mask;
9131 
9132     // If there is a base and this is a relational operator, we can only
9133     // compare pointers within the object in question; otherwise, the result
9134     // depends on where the object is located in memory.
9135     if (!LHSValue.Base.isNull() && IsRelational) {
9136       QualType BaseTy = getType(LHSValue.Base);
9137       if (BaseTy->isIncompleteType())
9138         return Error(E);
9139       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
9140       uint64_t OffsetLimit = Size.getQuantity();
9141       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
9142         return Error(E);
9143     }
9144 
9145     if (CompareLHS < CompareRHS)
9146       return Success(CCR::Less, E);
9147     if (CompareLHS > CompareRHS)
9148       return Success(CCR::Greater, E);
9149     return Success(CCR::Equal, E);
9150   }
9151 
9152   if (LHSTy->isMemberPointerType()) {
9153     assert(IsEquality && "unexpected member pointer operation");
9154     assert(RHSTy->isMemberPointerType() && "invalid comparison");
9155 
9156     MemberPtr LHSValue, RHSValue;
9157 
9158     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
9159     if (!LHSOK && !Info.noteFailure())
9160       return false;
9161 
9162     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9163       return false;
9164 
9165     // C++11 [expr.eq]p2:
9166     //   If both operands are null, they compare equal. Otherwise if only one is
9167     //   null, they compare unequal.
9168     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
9169       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
9170       return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
9171     }
9172 
9173     //   Otherwise if either is a pointer to a virtual member function, the
9174     //   result is unspecified.
9175     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
9176       if (MD->isVirtual())
9177         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
9178     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
9179       if (MD->isVirtual())
9180         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
9181 
9182     //   Otherwise they compare equal if and only if they would refer to the
9183     //   same member of the same most derived object or the same subobject if
9184     //   they were dereferenced with a hypothetical object of the associated
9185     //   class type.
9186     bool Equal = LHSValue == RHSValue;
9187     return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
9188   }
9189 
9190   if (LHSTy->isNullPtrType()) {
9191     assert(E->isComparisonOp() && "unexpected nullptr operation");
9192     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
9193     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
9194     // are compared, the result is true of the operator is <=, >= or ==, and
9195     // false otherwise.
9196     return Success(CCR::Equal, E);
9197   }
9198 
9199   return DoAfter();
9200 }
9201 
9202 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
9203   if (!CheckLiteralType(Info, E))
9204     return false;
9205 
9206   auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9207                        const BinaryOperator *E) {
9208     // Evaluation succeeded. Lookup the information for the comparison category
9209     // type and fetch the VarDecl for the result.
9210     const ComparisonCategoryInfo &CmpInfo =
9211         Info.Ctx.CompCategories.getInfoForType(E->getType());
9212     const VarDecl *VD =
9213         CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
9214     // Check and evaluate the result as a constant expression.
9215     LValue LV;
9216     LV.set(VD);
9217     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
9218       return false;
9219     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
9220   };
9221   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9222     return ExprEvaluatorBaseTy::VisitBinCmp(E);
9223   });
9224 }
9225 
9226 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9227   // We don't call noteFailure immediately because the assignment happens after
9228   // we evaluate LHS and RHS.
9229   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
9230     return Error(E);
9231 
9232   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
9233   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
9234     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
9235 
9236   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
9237           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
9238          "DataRecursiveIntBinOpEvaluator should have handled integral types");
9239 
9240   if (E->isComparisonOp()) {
9241     // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
9242     // comparisons and then translating the result.
9243     auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9244                          const BinaryOperator *E) {
9245       using CCR = ComparisonCategoryResult;
9246       bool IsEqual   = ResKind == CCR::Equal,
9247            IsLess    = ResKind == CCR::Less,
9248            IsGreater = ResKind == CCR::Greater;
9249       auto Op = E->getOpcode();
9250       switch (Op) {
9251       default:
9252         llvm_unreachable("unsupported binary operator");
9253       case BO_EQ:
9254       case BO_NE:
9255         return Success(IsEqual == (Op == BO_EQ), E);
9256       case BO_LT: return Success(IsLess, E);
9257       case BO_GT: return Success(IsGreater, E);
9258       case BO_LE: return Success(IsEqual || IsLess, E);
9259       case BO_GE: return Success(IsEqual || IsGreater, E);
9260       }
9261     };
9262     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9263       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9264     });
9265   }
9266 
9267   QualType LHSTy = E->getLHS()->getType();
9268   QualType RHSTy = E->getRHS()->getType();
9269 
9270   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
9271       E->getOpcode() == BO_Sub) {
9272     LValue LHSValue, RHSValue;
9273 
9274     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9275     if (!LHSOK && !Info.noteFailure())
9276       return false;
9277 
9278     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9279       return false;
9280 
9281     // Reject differing bases from the normal codepath; we special-case
9282     // comparisons to null.
9283     if (!HasSameBase(LHSValue, RHSValue)) {
9284       // Handle &&A - &&B.
9285       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
9286         return Error(E);
9287       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
9288       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
9289       if (!LHSExpr || !RHSExpr)
9290         return Error(E);
9291       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
9292       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
9293       if (!LHSAddrExpr || !RHSAddrExpr)
9294         return Error(E);
9295       // Make sure both labels come from the same function.
9296       if (LHSAddrExpr->getLabel()->getDeclContext() !=
9297           RHSAddrExpr->getLabel()->getDeclContext())
9298         return Error(E);
9299       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
9300     }
9301     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9302     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
9303 
9304     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9305     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
9306 
9307     // C++11 [expr.add]p6:
9308     //   Unless both pointers point to elements of the same array object, or
9309     //   one past the last element of the array object, the behavior is
9310     //   undefined.
9311     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
9312         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
9313                                 RHSDesignator))
9314       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
9315 
9316     QualType Type = E->getLHS()->getType();
9317     QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
9318 
9319     CharUnits ElementSize;
9320     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
9321       return false;
9322 
9323     // As an extension, a type may have zero size (empty struct or union in
9324     // C, array of zero length). Pointer subtraction in such cases has
9325     // undefined behavior, so is not constant.
9326     if (ElementSize.isZero()) {
9327       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
9328           << ElementType;
9329       return false;
9330     }
9331 
9332     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
9333     // and produce incorrect results when it overflows. Such behavior
9334     // appears to be non-conforming, but is common, so perhaps we should
9335     // assume the standard intended for such cases to be undefined behavior
9336     // and check for them.
9337 
9338     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
9339     // overflow in the final conversion to ptrdiff_t.
9340     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
9341     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
9342     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
9343                     false);
9344     APSInt TrueResult = (LHS - RHS) / ElemSize;
9345     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
9346 
9347     if (Result.extend(65) != TrueResult &&
9348         !HandleOverflow(Info, E, TrueResult, E->getType()))
9349       return false;
9350     return Success(Result, E);
9351   }
9352 
9353   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9354 }
9355 
9356 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
9357 /// a result as the expression's type.
9358 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
9359                                     const UnaryExprOrTypeTraitExpr *E) {
9360   switch(E->getKind()) {
9361   case UETT_AlignOf: {
9362     if (E->isArgumentType())
9363       return Success(GetAlignOfType(Info, E->getArgumentType()), E);
9364     else
9365       return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
9366   }
9367 
9368   case UETT_VecStep: {
9369     QualType Ty = E->getTypeOfArgument();
9370 
9371     if (Ty->isVectorType()) {
9372       unsigned n = Ty->castAs<VectorType>()->getNumElements();
9373 
9374       // The vec_step built-in functions that take a 3-component
9375       // vector return 4. (OpenCL 1.1 spec 6.11.12)
9376       if (n == 3)
9377         n = 4;
9378 
9379       return Success(n, E);
9380     } else
9381       return Success(1, E);
9382   }
9383 
9384   case UETT_SizeOf: {
9385     QualType SrcTy = E->getTypeOfArgument();
9386     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
9387     //   the result is the size of the referenced type."
9388     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
9389       SrcTy = Ref->getPointeeType();
9390 
9391     CharUnits Sizeof;
9392     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
9393       return false;
9394     return Success(Sizeof, E);
9395   }
9396   case UETT_OpenMPRequiredSimdAlign:
9397     assert(E->isArgumentType());
9398     return Success(
9399         Info.Ctx.toCharUnitsFromBits(
9400                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
9401             .getQuantity(),
9402         E);
9403   }
9404 
9405   llvm_unreachable("unknown expr/type trait");
9406 }
9407 
9408 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
9409   CharUnits Result;
9410   unsigned n = OOE->getNumComponents();
9411   if (n == 0)
9412     return Error(OOE);
9413   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
9414   for (unsigned i = 0; i != n; ++i) {
9415     OffsetOfNode ON = OOE->getComponent(i);
9416     switch (ON.getKind()) {
9417     case OffsetOfNode::Array: {
9418       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
9419       APSInt IdxResult;
9420       if (!EvaluateInteger(Idx, IdxResult, Info))
9421         return false;
9422       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
9423       if (!AT)
9424         return Error(OOE);
9425       CurrentType = AT->getElementType();
9426       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
9427       Result += IdxResult.getSExtValue() * ElementSize;
9428       break;
9429     }
9430 
9431     case OffsetOfNode::Field: {
9432       FieldDecl *MemberDecl = ON.getField();
9433       const RecordType *RT = CurrentType->getAs<RecordType>();
9434       if (!RT)
9435         return Error(OOE);
9436       RecordDecl *RD = RT->getDecl();
9437       if (RD->isInvalidDecl()) return false;
9438       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
9439       unsigned i = MemberDecl->getFieldIndex();
9440       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
9441       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
9442       CurrentType = MemberDecl->getType().getNonReferenceType();
9443       break;
9444     }
9445 
9446     case OffsetOfNode::Identifier:
9447       llvm_unreachable("dependent __builtin_offsetof");
9448 
9449     case OffsetOfNode::Base: {
9450       CXXBaseSpecifier *BaseSpec = ON.getBase();
9451       if (BaseSpec->isVirtual())
9452         return Error(OOE);
9453 
9454       // Find the layout of the class whose base we are looking into.
9455       const RecordType *RT = CurrentType->getAs<RecordType>();
9456       if (!RT)
9457         return Error(OOE);
9458       RecordDecl *RD = RT->getDecl();
9459       if (RD->isInvalidDecl()) return false;
9460       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
9461 
9462       // Find the base class itself.
9463       CurrentType = BaseSpec->getType();
9464       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
9465       if (!BaseRT)
9466         return Error(OOE);
9467 
9468       // Add the offset to the base.
9469       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
9470       break;
9471     }
9472     }
9473   }
9474   return Success(Result, OOE);
9475 }
9476 
9477 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9478   switch (E->getOpcode()) {
9479   default:
9480     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
9481     // See C99 6.6p3.
9482     return Error(E);
9483   case UO_Extension:
9484     // FIXME: Should extension allow i-c-e extension expressions in its scope?
9485     // If so, we could clear the diagnostic ID.
9486     return Visit(E->getSubExpr());
9487   case UO_Plus:
9488     // The result is just the value.
9489     return Visit(E->getSubExpr());
9490   case UO_Minus: {
9491     if (!Visit(E->getSubExpr()))
9492       return false;
9493     if (!Result.isInt()) return Error(E);
9494     const APSInt &Value = Result.getInt();
9495     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
9496         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
9497                         E->getType()))
9498       return false;
9499     return Success(-Value, E);
9500   }
9501   case UO_Not: {
9502     if (!Visit(E->getSubExpr()))
9503       return false;
9504     if (!Result.isInt()) return Error(E);
9505     return Success(~Result.getInt(), E);
9506   }
9507   case UO_LNot: {
9508     bool bres;
9509     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
9510       return false;
9511     return Success(!bres, E);
9512   }
9513   }
9514 }
9515 
9516 /// HandleCast - This is used to evaluate implicit or explicit casts where the
9517 /// result type is integer.
9518 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
9519   const Expr *SubExpr = E->getSubExpr();
9520   QualType DestType = E->getType();
9521   QualType SrcType = SubExpr->getType();
9522 
9523   switch (E->getCastKind()) {
9524   case CK_BaseToDerived:
9525   case CK_DerivedToBase:
9526   case CK_UncheckedDerivedToBase:
9527   case CK_Dynamic:
9528   case CK_ToUnion:
9529   case CK_ArrayToPointerDecay:
9530   case CK_FunctionToPointerDecay:
9531   case CK_NullToPointer:
9532   case CK_NullToMemberPointer:
9533   case CK_BaseToDerivedMemberPointer:
9534   case CK_DerivedToBaseMemberPointer:
9535   case CK_ReinterpretMemberPointer:
9536   case CK_ConstructorConversion:
9537   case CK_IntegralToPointer:
9538   case CK_ToVoid:
9539   case CK_VectorSplat:
9540   case CK_IntegralToFloating:
9541   case CK_FloatingCast:
9542   case CK_CPointerToObjCPointerCast:
9543   case CK_BlockPointerToObjCPointerCast:
9544   case CK_AnyPointerToBlockPointerCast:
9545   case CK_ObjCObjectLValueCast:
9546   case CK_FloatingRealToComplex:
9547   case CK_FloatingComplexToReal:
9548   case CK_FloatingComplexCast:
9549   case CK_FloatingComplexToIntegralComplex:
9550   case CK_IntegralRealToComplex:
9551   case CK_IntegralComplexCast:
9552   case CK_IntegralComplexToFloatingComplex:
9553   case CK_BuiltinFnToFnPtr:
9554   case CK_ZeroToOCLOpaqueType:
9555   case CK_NonAtomicToAtomic:
9556   case CK_AddressSpaceConversion:
9557   case CK_IntToOCLSampler:
9558   case CK_FixedPointCast:
9559     llvm_unreachable("invalid cast kind for integral value");
9560 
9561   case CK_BitCast:
9562   case CK_Dependent:
9563   case CK_LValueBitCast:
9564   case CK_ARCProduceObject:
9565   case CK_ARCConsumeObject:
9566   case CK_ARCReclaimReturnedObject:
9567   case CK_ARCExtendBlockObject:
9568   case CK_CopyAndAutoreleaseBlockObject:
9569     return Error(E);
9570 
9571   case CK_UserDefinedConversion:
9572   case CK_LValueToRValue:
9573   case CK_AtomicToNonAtomic:
9574   case CK_NoOp:
9575     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9576 
9577   case CK_MemberPointerToBoolean:
9578   case CK_PointerToBoolean:
9579   case CK_IntegralToBoolean:
9580   case CK_FloatingToBoolean:
9581   case CK_BooleanToSignedIntegral:
9582   case CK_FloatingComplexToBoolean:
9583   case CK_IntegralComplexToBoolean: {
9584     bool BoolResult;
9585     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
9586       return false;
9587     uint64_t IntResult = BoolResult;
9588     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
9589       IntResult = (uint64_t)-1;
9590     return Success(IntResult, E);
9591   }
9592 
9593   case CK_FixedPointToBoolean: {
9594     // Unsigned padding does not affect this.
9595     APValue Val;
9596     if (!Evaluate(Val, Info, SubExpr))
9597       return false;
9598     return Success(Val.getInt().getBoolValue(), E);
9599   }
9600 
9601   case CK_IntegralCast: {
9602     if (!Visit(SubExpr))
9603       return false;
9604 
9605     if (!Result.isInt()) {
9606       // Allow casts of address-of-label differences if they are no-ops
9607       // or narrowing.  (The narrowing case isn't actually guaranteed to
9608       // be constant-evaluatable except in some narrow cases which are hard
9609       // to detect here.  We let it through on the assumption the user knows
9610       // what they are doing.)
9611       if (Result.isAddrLabelDiff())
9612         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
9613       // Only allow casts of lvalues if they are lossless.
9614       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
9615     }
9616 
9617     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
9618                                       Result.getInt()), E);
9619   }
9620 
9621   case CK_PointerToIntegral: {
9622     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
9623 
9624     LValue LV;
9625     if (!EvaluatePointer(SubExpr, LV, Info))
9626       return false;
9627 
9628     if (LV.getLValueBase()) {
9629       // Only allow based lvalue casts if they are lossless.
9630       // FIXME: Allow a larger integer size than the pointer size, and allow
9631       // narrowing back down to pointer width in subsequent integral casts.
9632       // FIXME: Check integer type's active bits, not its type size.
9633       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
9634         return Error(E);
9635 
9636       LV.Designator.setInvalid();
9637       LV.moveInto(Result);
9638       return true;
9639     }
9640 
9641     uint64_t V;
9642     if (LV.isNullPointer())
9643       V = Info.Ctx.getTargetNullPointerValue(SrcType);
9644     else
9645       V = LV.getLValueOffset().getQuantity();
9646 
9647     APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
9648     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
9649   }
9650 
9651   case CK_IntegralComplexToReal: {
9652     ComplexValue C;
9653     if (!EvaluateComplex(SubExpr, C, Info))
9654       return false;
9655     return Success(C.getComplexIntReal(), E);
9656   }
9657 
9658   case CK_FloatingToIntegral: {
9659     APFloat F(0.0);
9660     if (!EvaluateFloat(SubExpr, F, Info))
9661       return false;
9662 
9663     APSInt Value;
9664     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
9665       return false;
9666     return Success(Value, E);
9667   }
9668   }
9669 
9670   llvm_unreachable("unknown cast resulting in integral value");
9671 }
9672 
9673 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9674   if (E->getSubExpr()->getType()->isAnyComplexType()) {
9675     ComplexValue LV;
9676     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9677       return false;
9678     if (!LV.isComplexInt())
9679       return Error(E);
9680     return Success(LV.getComplexIntReal(), E);
9681   }
9682 
9683   return Visit(E->getSubExpr());
9684 }
9685 
9686 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9687   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
9688     ComplexValue LV;
9689     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9690       return false;
9691     if (!LV.isComplexInt())
9692       return Error(E);
9693     return Success(LV.getComplexIntImag(), E);
9694   }
9695 
9696   VisitIgnoredValue(E->getSubExpr());
9697   return Success(0, E);
9698 }
9699 
9700 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9701   return Success(E->getPackLength(), E);
9702 }
9703 
9704 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9705   return Success(E->getValue(), E);
9706 }
9707 
9708 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9709   switch (E->getOpcode()) {
9710     default:
9711       // Invalid unary operators
9712       return Error(E);
9713     case UO_Plus:
9714       // The result is just the value.
9715       return Visit(E->getSubExpr());
9716     case UO_Minus: {
9717       if (!Visit(E->getSubExpr())) return false;
9718       if (!Result.isInt()) return Error(E);
9719       const APSInt &Value = Result.getInt();
9720       if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
9721         SmallString<64> S;
9722         FixedPointValueToString(S, Value,
9723                                 Info.Ctx.getTypeInfo(E->getType()).Width);
9724         Info.CCEDiag(E, diag::note_constexpr_overflow) << S << E->getType();
9725         if (Info.noteUndefinedBehavior()) return false;
9726       }
9727       return Success(-Value, E);
9728     }
9729     case UO_LNot: {
9730       bool bres;
9731       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
9732         return false;
9733       return Success(!bres, E);
9734     }
9735   }
9736 }
9737 
9738 //===----------------------------------------------------------------------===//
9739 // Float Evaluation
9740 //===----------------------------------------------------------------------===//
9741 
9742 namespace {
9743 class FloatExprEvaluator
9744   : public ExprEvaluatorBase<FloatExprEvaluator> {
9745   APFloat &Result;
9746 public:
9747   FloatExprEvaluator(EvalInfo &info, APFloat &result)
9748     : ExprEvaluatorBaseTy(info), Result(result) {}
9749 
9750   bool Success(const APValue &V, const Expr *e) {
9751     Result = V.getFloat();
9752     return true;
9753   }
9754 
9755   bool ZeroInitialization(const Expr *E) {
9756     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9757     return true;
9758   }
9759 
9760   bool VisitCallExpr(const CallExpr *E);
9761 
9762   bool VisitUnaryOperator(const UnaryOperator *E);
9763   bool VisitBinaryOperator(const BinaryOperator *E);
9764   bool VisitFloatingLiteral(const FloatingLiteral *E);
9765   bool VisitCastExpr(const CastExpr *E);
9766 
9767   bool VisitUnaryReal(const UnaryOperator *E);
9768   bool VisitUnaryImag(const UnaryOperator *E);
9769 
9770   // FIXME: Missing: array subscript of vector, member of vector
9771 };
9772 } // end anonymous namespace
9773 
9774 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
9775   assert(E->isRValue() && E->getType()->isRealFloatingType());
9776   return FloatExprEvaluator(Info, Result).Visit(E);
9777 }
9778 
9779 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
9780                                   QualType ResultTy,
9781                                   const Expr *Arg,
9782                                   bool SNaN,
9783                                   llvm::APFloat &Result) {
9784   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9785   if (!S) return false;
9786 
9787   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9788 
9789   llvm::APInt fill;
9790 
9791   // Treat empty strings as if they were zero.
9792   if (S->getString().empty())
9793     fill = llvm::APInt(32, 0);
9794   else if (S->getString().getAsInteger(0, fill))
9795     return false;
9796 
9797   if (Context.getTargetInfo().isNan2008()) {
9798     if (SNaN)
9799       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9800     else
9801       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9802   } else {
9803     // Prior to IEEE 754-2008, architectures were allowed to choose whether
9804     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9805     // a different encoding to what became a standard in 2008, and for pre-
9806     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9807     // sNaN. This is now known as "legacy NaN" encoding.
9808     if (SNaN)
9809       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9810     else
9811       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9812   }
9813 
9814   return true;
9815 }
9816 
9817 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
9818   switch (E->getBuiltinCallee()) {
9819   default:
9820     return ExprEvaluatorBaseTy::VisitCallExpr(E);
9821 
9822   case Builtin::BI__builtin_huge_val:
9823   case Builtin::BI__builtin_huge_valf:
9824   case Builtin::BI__builtin_huge_vall:
9825   case Builtin::BI__builtin_huge_valf128:
9826   case Builtin::BI__builtin_inf:
9827   case Builtin::BI__builtin_inff:
9828   case Builtin::BI__builtin_infl:
9829   case Builtin::BI__builtin_inff128: {
9830     const llvm::fltSemantics &Sem =
9831       Info.Ctx.getFloatTypeSemantics(E->getType());
9832     Result = llvm::APFloat::getInf(Sem);
9833     return true;
9834   }
9835 
9836   case Builtin::BI__builtin_nans:
9837   case Builtin::BI__builtin_nansf:
9838   case Builtin::BI__builtin_nansl:
9839   case Builtin::BI__builtin_nansf128:
9840     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9841                                true, Result))
9842       return Error(E);
9843     return true;
9844 
9845   case Builtin::BI__builtin_nan:
9846   case Builtin::BI__builtin_nanf:
9847   case Builtin::BI__builtin_nanl:
9848   case Builtin::BI__builtin_nanf128:
9849     // If this is __builtin_nan() turn this into a nan, otherwise we
9850     // can't constant fold it.
9851     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9852                                false, Result))
9853       return Error(E);
9854     return true;
9855 
9856   case Builtin::BI__builtin_fabs:
9857   case Builtin::BI__builtin_fabsf:
9858   case Builtin::BI__builtin_fabsl:
9859   case Builtin::BI__builtin_fabsf128:
9860     if (!EvaluateFloat(E->getArg(0), Result, Info))
9861       return false;
9862 
9863     if (Result.isNegative())
9864       Result.changeSign();
9865     return true;
9866 
9867   // FIXME: Builtin::BI__builtin_powi
9868   // FIXME: Builtin::BI__builtin_powif
9869   // FIXME: Builtin::BI__builtin_powil
9870 
9871   case Builtin::BI__builtin_copysign:
9872   case Builtin::BI__builtin_copysignf:
9873   case Builtin::BI__builtin_copysignl:
9874   case Builtin::BI__builtin_copysignf128: {
9875     APFloat RHS(0.);
9876     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9877         !EvaluateFloat(E->getArg(1), RHS, Info))
9878       return false;
9879     Result.copySign(RHS);
9880     return true;
9881   }
9882   }
9883 }
9884 
9885 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9886   if (E->getSubExpr()->getType()->isAnyComplexType()) {
9887     ComplexValue CV;
9888     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9889       return false;
9890     Result = CV.FloatReal;
9891     return true;
9892   }
9893 
9894   return Visit(E->getSubExpr());
9895 }
9896 
9897 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9898   if (E->getSubExpr()->getType()->isAnyComplexType()) {
9899     ComplexValue CV;
9900     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9901       return false;
9902     Result = CV.FloatImag;
9903     return true;
9904   }
9905 
9906   VisitIgnoredValue(E->getSubExpr());
9907   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9908   Result = llvm::APFloat::getZero(Sem);
9909   return true;
9910 }
9911 
9912 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9913   switch (E->getOpcode()) {
9914   default: return Error(E);
9915   case UO_Plus:
9916     return EvaluateFloat(E->getSubExpr(), Result, Info);
9917   case UO_Minus:
9918     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9919       return false;
9920     Result.changeSign();
9921     return true;
9922   }
9923 }
9924 
9925 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9926   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9927     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9928 
9929   APFloat RHS(0.0);
9930   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
9931   if (!LHSOK && !Info.noteFailure())
9932     return false;
9933   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9934          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
9935 }
9936 
9937 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9938   Result = E->getValue();
9939   return true;
9940 }
9941 
9942 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9943   const Expr* SubExpr = E->getSubExpr();
9944 
9945   switch (E->getCastKind()) {
9946   default:
9947     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9948 
9949   case CK_IntegralToFloating: {
9950     APSInt IntResult;
9951     return EvaluateInteger(SubExpr, IntResult, Info) &&
9952            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9953                                 E->getType(), Result);
9954   }
9955 
9956   case CK_FloatingCast: {
9957     if (!Visit(SubExpr))
9958       return false;
9959     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9960                                   Result);
9961   }
9962 
9963   case CK_FloatingComplexToReal: {
9964     ComplexValue V;
9965     if (!EvaluateComplex(SubExpr, V, Info))
9966       return false;
9967     Result = V.getComplexFloatReal();
9968     return true;
9969   }
9970   }
9971 }
9972 
9973 //===----------------------------------------------------------------------===//
9974 // Complex Evaluation (for float and integer)
9975 //===----------------------------------------------------------------------===//
9976 
9977 namespace {
9978 class ComplexExprEvaluator
9979   : public ExprEvaluatorBase<ComplexExprEvaluator> {
9980   ComplexValue &Result;
9981 
9982 public:
9983   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
9984     : ExprEvaluatorBaseTy(info), Result(Result) {}
9985 
9986   bool Success(const APValue &V, const Expr *e) {
9987     Result.setFrom(V);
9988     return true;
9989   }
9990 
9991   bool ZeroInitialization(const Expr *E);
9992 
9993   //===--------------------------------------------------------------------===//
9994   //                            Visitor Methods
9995   //===--------------------------------------------------------------------===//
9996 
9997   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
9998   bool VisitCastExpr(const CastExpr *E);
9999   bool VisitBinaryOperator(const BinaryOperator *E);
10000   bool VisitUnaryOperator(const UnaryOperator *E);
10001   bool VisitInitListExpr(const InitListExpr *E);
10002 };
10003 } // end anonymous namespace
10004 
10005 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
10006                             EvalInfo &Info) {
10007   assert(E->isRValue() && E->getType()->isAnyComplexType());
10008   return ComplexExprEvaluator(Info, Result).Visit(E);
10009 }
10010 
10011 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
10012   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
10013   if (ElemTy->isRealFloatingType()) {
10014     Result.makeComplexFloat();
10015     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
10016     Result.FloatReal = Zero;
10017     Result.FloatImag = Zero;
10018   } else {
10019     Result.makeComplexInt();
10020     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
10021     Result.IntReal = Zero;
10022     Result.IntImag = Zero;
10023   }
10024   return true;
10025 }
10026 
10027 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
10028   const Expr* SubExpr = E->getSubExpr();
10029 
10030   if (SubExpr->getType()->isRealFloatingType()) {
10031     Result.makeComplexFloat();
10032     APFloat &Imag = Result.FloatImag;
10033     if (!EvaluateFloat(SubExpr, Imag, Info))
10034       return false;
10035 
10036     Result.FloatReal = APFloat(Imag.getSemantics());
10037     return true;
10038   } else {
10039     assert(SubExpr->getType()->isIntegerType() &&
10040            "Unexpected imaginary literal.");
10041 
10042     Result.makeComplexInt();
10043     APSInt &Imag = Result.IntImag;
10044     if (!EvaluateInteger(SubExpr, Imag, Info))
10045       return false;
10046 
10047     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
10048     return true;
10049   }
10050 }
10051 
10052 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
10053 
10054   switch (E->getCastKind()) {
10055   case CK_BitCast:
10056   case CK_BaseToDerived:
10057   case CK_DerivedToBase:
10058   case CK_UncheckedDerivedToBase:
10059   case CK_Dynamic:
10060   case CK_ToUnion:
10061   case CK_ArrayToPointerDecay:
10062   case CK_FunctionToPointerDecay:
10063   case CK_NullToPointer:
10064   case CK_NullToMemberPointer:
10065   case CK_BaseToDerivedMemberPointer:
10066   case CK_DerivedToBaseMemberPointer:
10067   case CK_MemberPointerToBoolean:
10068   case CK_ReinterpretMemberPointer:
10069   case CK_ConstructorConversion:
10070   case CK_IntegralToPointer:
10071   case CK_PointerToIntegral:
10072   case CK_PointerToBoolean:
10073   case CK_ToVoid:
10074   case CK_VectorSplat:
10075   case CK_IntegralCast:
10076   case CK_BooleanToSignedIntegral:
10077   case CK_IntegralToBoolean:
10078   case CK_IntegralToFloating:
10079   case CK_FloatingToIntegral:
10080   case CK_FloatingToBoolean:
10081   case CK_FloatingCast:
10082   case CK_CPointerToObjCPointerCast:
10083   case CK_BlockPointerToObjCPointerCast:
10084   case CK_AnyPointerToBlockPointerCast:
10085   case CK_ObjCObjectLValueCast:
10086   case CK_FloatingComplexToReal:
10087   case CK_FloatingComplexToBoolean:
10088   case CK_IntegralComplexToReal:
10089   case CK_IntegralComplexToBoolean:
10090   case CK_ARCProduceObject:
10091   case CK_ARCConsumeObject:
10092   case CK_ARCReclaimReturnedObject:
10093   case CK_ARCExtendBlockObject:
10094   case CK_CopyAndAutoreleaseBlockObject:
10095   case CK_BuiltinFnToFnPtr:
10096   case CK_ZeroToOCLOpaqueType:
10097   case CK_NonAtomicToAtomic:
10098   case CK_AddressSpaceConversion:
10099   case CK_IntToOCLSampler:
10100   case CK_FixedPointCast:
10101   case CK_FixedPointToBoolean:
10102     llvm_unreachable("invalid cast kind for complex value");
10103 
10104   case CK_LValueToRValue:
10105   case CK_AtomicToNonAtomic:
10106   case CK_NoOp:
10107     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10108 
10109   case CK_Dependent:
10110   case CK_LValueBitCast:
10111   case CK_UserDefinedConversion:
10112     return Error(E);
10113 
10114   case CK_FloatingRealToComplex: {
10115     APFloat &Real = Result.FloatReal;
10116     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
10117       return false;
10118 
10119     Result.makeComplexFloat();
10120     Result.FloatImag = APFloat(Real.getSemantics());
10121     return true;
10122   }
10123 
10124   case CK_FloatingComplexCast: {
10125     if (!Visit(E->getSubExpr()))
10126       return false;
10127 
10128     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10129     QualType From
10130       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10131 
10132     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
10133            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
10134   }
10135 
10136   case CK_FloatingComplexToIntegralComplex: {
10137     if (!Visit(E->getSubExpr()))
10138       return false;
10139 
10140     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10141     QualType From
10142       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10143     Result.makeComplexInt();
10144     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
10145                                 To, Result.IntReal) &&
10146            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
10147                                 To, Result.IntImag);
10148   }
10149 
10150   case CK_IntegralRealToComplex: {
10151     APSInt &Real = Result.IntReal;
10152     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
10153       return false;
10154 
10155     Result.makeComplexInt();
10156     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
10157     return true;
10158   }
10159 
10160   case CK_IntegralComplexCast: {
10161     if (!Visit(E->getSubExpr()))
10162       return false;
10163 
10164     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10165     QualType From
10166       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10167 
10168     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
10169     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
10170     return true;
10171   }
10172 
10173   case CK_IntegralComplexToFloatingComplex: {
10174     if (!Visit(E->getSubExpr()))
10175       return false;
10176 
10177     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
10178     QualType From
10179       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
10180     Result.makeComplexFloat();
10181     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
10182                                 To, Result.FloatReal) &&
10183            HandleIntToFloatCast(Info, E, From, Result.IntImag,
10184                                 To, Result.FloatImag);
10185   }
10186   }
10187 
10188   llvm_unreachable("unknown cast resulting in complex value");
10189 }
10190 
10191 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10192   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
10193     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10194 
10195   // Track whether the LHS or RHS is real at the type system level. When this is
10196   // the case we can simplify our evaluation strategy.
10197   bool LHSReal = false, RHSReal = false;
10198 
10199   bool LHSOK;
10200   if (E->getLHS()->getType()->isRealFloatingType()) {
10201     LHSReal = true;
10202     APFloat &Real = Result.FloatReal;
10203     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
10204     if (LHSOK) {
10205       Result.makeComplexFloat();
10206       Result.FloatImag = APFloat(Real.getSemantics());
10207     }
10208   } else {
10209     LHSOK = Visit(E->getLHS());
10210   }
10211   if (!LHSOK && !Info.noteFailure())
10212     return false;
10213 
10214   ComplexValue RHS;
10215   if (E->getRHS()->getType()->isRealFloatingType()) {
10216     RHSReal = true;
10217     APFloat &Real = RHS.FloatReal;
10218     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
10219       return false;
10220     RHS.makeComplexFloat();
10221     RHS.FloatImag = APFloat(Real.getSemantics());
10222   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
10223     return false;
10224 
10225   assert(!(LHSReal && RHSReal) &&
10226          "Cannot have both operands of a complex operation be real.");
10227   switch (E->getOpcode()) {
10228   default: return Error(E);
10229   case BO_Add:
10230     if (Result.isComplexFloat()) {
10231       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
10232                                        APFloat::rmNearestTiesToEven);
10233       if (LHSReal)
10234         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10235       else if (!RHSReal)
10236         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
10237                                          APFloat::rmNearestTiesToEven);
10238     } else {
10239       Result.getComplexIntReal() += RHS.getComplexIntReal();
10240       Result.getComplexIntImag() += RHS.getComplexIntImag();
10241     }
10242     break;
10243   case BO_Sub:
10244     if (Result.isComplexFloat()) {
10245       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
10246                                             APFloat::rmNearestTiesToEven);
10247       if (LHSReal) {
10248         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10249         Result.getComplexFloatImag().changeSign();
10250       } else if (!RHSReal) {
10251         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
10252                                               APFloat::rmNearestTiesToEven);
10253       }
10254     } else {
10255       Result.getComplexIntReal() -= RHS.getComplexIntReal();
10256       Result.getComplexIntImag() -= RHS.getComplexIntImag();
10257     }
10258     break;
10259   case BO_Mul:
10260     if (Result.isComplexFloat()) {
10261       // This is an implementation of complex multiplication according to the
10262       // constraints laid out in C11 Annex G. The implemention uses the
10263       // following naming scheme:
10264       //   (a + ib) * (c + id)
10265       ComplexValue LHS = Result;
10266       APFloat &A = LHS.getComplexFloatReal();
10267       APFloat &B = LHS.getComplexFloatImag();
10268       APFloat &C = RHS.getComplexFloatReal();
10269       APFloat &D = RHS.getComplexFloatImag();
10270       APFloat &ResR = Result.getComplexFloatReal();
10271       APFloat &ResI = Result.getComplexFloatImag();
10272       if (LHSReal) {
10273         assert(!RHSReal && "Cannot have two real operands for a complex op!");
10274         ResR = A * C;
10275         ResI = A * D;
10276       } else if (RHSReal) {
10277         ResR = C * A;
10278         ResI = C * B;
10279       } else {
10280         // In the fully general case, we need to handle NaNs and infinities
10281         // robustly.
10282         APFloat AC = A * C;
10283         APFloat BD = B * D;
10284         APFloat AD = A * D;
10285         APFloat BC = B * C;
10286         ResR = AC - BD;
10287         ResI = AD + BC;
10288         if (ResR.isNaN() && ResI.isNaN()) {
10289           bool Recalc = false;
10290           if (A.isInfinity() || B.isInfinity()) {
10291             A = APFloat::copySign(
10292                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10293             B = APFloat::copySign(
10294                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10295             if (C.isNaN())
10296               C = APFloat::copySign(APFloat(C.getSemantics()), C);
10297             if (D.isNaN())
10298               D = APFloat::copySign(APFloat(D.getSemantics()), D);
10299             Recalc = true;
10300           }
10301           if (C.isInfinity() || D.isInfinity()) {
10302             C = APFloat::copySign(
10303                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10304             D = APFloat::copySign(
10305                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10306             if (A.isNaN())
10307               A = APFloat::copySign(APFloat(A.getSemantics()), A);
10308             if (B.isNaN())
10309               B = APFloat::copySign(APFloat(B.getSemantics()), B);
10310             Recalc = true;
10311           }
10312           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
10313                           AD.isInfinity() || BC.isInfinity())) {
10314             if (A.isNaN())
10315               A = APFloat::copySign(APFloat(A.getSemantics()), A);
10316             if (B.isNaN())
10317               B = APFloat::copySign(APFloat(B.getSemantics()), B);
10318             if (C.isNaN())
10319               C = APFloat::copySign(APFloat(C.getSemantics()), C);
10320             if (D.isNaN())
10321               D = APFloat::copySign(APFloat(D.getSemantics()), D);
10322             Recalc = true;
10323           }
10324           if (Recalc) {
10325             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
10326             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
10327           }
10328         }
10329       }
10330     } else {
10331       ComplexValue LHS = Result;
10332       Result.getComplexIntReal() =
10333         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
10334          LHS.getComplexIntImag() * RHS.getComplexIntImag());
10335       Result.getComplexIntImag() =
10336         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
10337          LHS.getComplexIntImag() * RHS.getComplexIntReal());
10338     }
10339     break;
10340   case BO_Div:
10341     if (Result.isComplexFloat()) {
10342       // This is an implementation of complex division according to the
10343       // constraints laid out in C11 Annex G. The implemention uses the
10344       // following naming scheme:
10345       //   (a + ib) / (c + id)
10346       ComplexValue LHS = Result;
10347       APFloat &A = LHS.getComplexFloatReal();
10348       APFloat &B = LHS.getComplexFloatImag();
10349       APFloat &C = RHS.getComplexFloatReal();
10350       APFloat &D = RHS.getComplexFloatImag();
10351       APFloat &ResR = Result.getComplexFloatReal();
10352       APFloat &ResI = Result.getComplexFloatImag();
10353       if (RHSReal) {
10354         ResR = A / C;
10355         ResI = B / C;
10356       } else {
10357         if (LHSReal) {
10358           // No real optimizations we can do here, stub out with zero.
10359           B = APFloat::getZero(A.getSemantics());
10360         }
10361         int DenomLogB = 0;
10362         APFloat MaxCD = maxnum(abs(C), abs(D));
10363         if (MaxCD.isFinite()) {
10364           DenomLogB = ilogb(MaxCD);
10365           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
10366           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
10367         }
10368         APFloat Denom = C * C + D * D;
10369         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
10370                       APFloat::rmNearestTiesToEven);
10371         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
10372                       APFloat::rmNearestTiesToEven);
10373         if (ResR.isNaN() && ResI.isNaN()) {
10374           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
10375             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
10376             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
10377           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
10378                      D.isFinite()) {
10379             A = APFloat::copySign(
10380                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10381             B = APFloat::copySign(
10382                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10383             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
10384             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
10385           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
10386             C = APFloat::copySign(
10387                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10388             D = APFloat::copySign(
10389                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10390             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
10391             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
10392           }
10393         }
10394       }
10395     } else {
10396       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
10397         return Error(E, diag::note_expr_divide_by_zero);
10398 
10399       ComplexValue LHS = Result;
10400       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
10401         RHS.getComplexIntImag() * RHS.getComplexIntImag();
10402       Result.getComplexIntReal() =
10403         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
10404          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
10405       Result.getComplexIntImag() =
10406         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
10407          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
10408     }
10409     break;
10410   }
10411 
10412   return true;
10413 }
10414 
10415 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10416   // Get the operand value into 'Result'.
10417   if (!Visit(E->getSubExpr()))
10418     return false;
10419 
10420   switch (E->getOpcode()) {
10421   default:
10422     return Error(E);
10423   case UO_Extension:
10424     return true;
10425   case UO_Plus:
10426     // The result is always just the subexpr.
10427     return true;
10428   case UO_Minus:
10429     if (Result.isComplexFloat()) {
10430       Result.getComplexFloatReal().changeSign();
10431       Result.getComplexFloatImag().changeSign();
10432     }
10433     else {
10434       Result.getComplexIntReal() = -Result.getComplexIntReal();
10435       Result.getComplexIntImag() = -Result.getComplexIntImag();
10436     }
10437     return true;
10438   case UO_Not:
10439     if (Result.isComplexFloat())
10440       Result.getComplexFloatImag().changeSign();
10441     else
10442       Result.getComplexIntImag() = -Result.getComplexIntImag();
10443     return true;
10444   }
10445 }
10446 
10447 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10448   if (E->getNumInits() == 2) {
10449     if (E->getType()->isComplexType()) {
10450       Result.makeComplexFloat();
10451       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
10452         return false;
10453       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
10454         return false;
10455     } else {
10456       Result.makeComplexInt();
10457       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
10458         return false;
10459       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
10460         return false;
10461     }
10462     return true;
10463   }
10464   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
10465 }
10466 
10467 //===----------------------------------------------------------------------===//
10468 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
10469 // implicit conversion.
10470 //===----------------------------------------------------------------------===//
10471 
10472 namespace {
10473 class AtomicExprEvaluator :
10474     public ExprEvaluatorBase<AtomicExprEvaluator> {
10475   const LValue *This;
10476   APValue &Result;
10477 public:
10478   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
10479       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10480 
10481   bool Success(const APValue &V, const Expr *E) {
10482     Result = V;
10483     return true;
10484   }
10485 
10486   bool ZeroInitialization(const Expr *E) {
10487     ImplicitValueInitExpr VIE(
10488         E->getType()->castAs<AtomicType>()->getValueType());
10489     // For atomic-qualified class (and array) types in C++, initialize the
10490     // _Atomic-wrapped subobject directly, in-place.
10491     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
10492                 : Evaluate(Result, Info, &VIE);
10493   }
10494 
10495   bool VisitCastExpr(const CastExpr *E) {
10496     switch (E->getCastKind()) {
10497     default:
10498       return ExprEvaluatorBaseTy::VisitCastExpr(E);
10499     case CK_NonAtomicToAtomic:
10500       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
10501                   : Evaluate(Result, Info, E->getSubExpr());
10502     }
10503   }
10504 };
10505 } // end anonymous namespace
10506 
10507 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
10508                            EvalInfo &Info) {
10509   assert(E->isRValue() && E->getType()->isAtomicType());
10510   return AtomicExprEvaluator(Info, This, Result).Visit(E);
10511 }
10512 
10513 //===----------------------------------------------------------------------===//
10514 // Void expression evaluation, primarily for a cast to void on the LHS of a
10515 // comma operator
10516 //===----------------------------------------------------------------------===//
10517 
10518 namespace {
10519 class VoidExprEvaluator
10520   : public ExprEvaluatorBase<VoidExprEvaluator> {
10521 public:
10522   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
10523 
10524   bool Success(const APValue &V, const Expr *e) { return true; }
10525 
10526   bool ZeroInitialization(const Expr *E) { return true; }
10527 
10528   bool VisitCastExpr(const CastExpr *E) {
10529     switch (E->getCastKind()) {
10530     default:
10531       return ExprEvaluatorBaseTy::VisitCastExpr(E);
10532     case CK_ToVoid:
10533       VisitIgnoredValue(E->getSubExpr());
10534       return true;
10535     }
10536   }
10537 
10538   bool VisitCallExpr(const CallExpr *E) {
10539     switch (E->getBuiltinCallee()) {
10540     default:
10541       return ExprEvaluatorBaseTy::VisitCallExpr(E);
10542     case Builtin::BI__assume:
10543     case Builtin::BI__builtin_assume:
10544       // The argument is not evaluated!
10545       return true;
10546     }
10547   }
10548 };
10549 } // end anonymous namespace
10550 
10551 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
10552   assert(E->isRValue() && E->getType()->isVoidType());
10553   return VoidExprEvaluator(Info).Visit(E);
10554 }
10555 
10556 //===----------------------------------------------------------------------===//
10557 // Top level Expr::EvaluateAsRValue method.
10558 //===----------------------------------------------------------------------===//
10559 
10560 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
10561   // In C, function designators are not lvalues, but we evaluate them as if they
10562   // are.
10563   QualType T = E->getType();
10564   if (E->isGLValue() || T->isFunctionType()) {
10565     LValue LV;
10566     if (!EvaluateLValue(E, LV, Info))
10567       return false;
10568     LV.moveInto(Result);
10569   } else if (T->isVectorType()) {
10570     if (!EvaluateVector(E, Result, Info))
10571       return false;
10572   } else if (T->isIntegralOrEnumerationType()) {
10573     if (!IntExprEvaluator(Info, Result).Visit(E))
10574       return false;
10575   } else if (T->hasPointerRepresentation()) {
10576     LValue LV;
10577     if (!EvaluatePointer(E, LV, Info))
10578       return false;
10579     LV.moveInto(Result);
10580   } else if (T->isRealFloatingType()) {
10581     llvm::APFloat F(0.0);
10582     if (!EvaluateFloat(E, F, Info))
10583       return false;
10584     Result = APValue(F);
10585   } else if (T->isAnyComplexType()) {
10586     ComplexValue C;
10587     if (!EvaluateComplex(E, C, Info))
10588       return false;
10589     C.moveInto(Result);
10590   } else if (T->isFixedPointType()) {
10591     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
10592   } else if (T->isMemberPointerType()) {
10593     MemberPtr P;
10594     if (!EvaluateMemberPointer(E, P, Info))
10595       return false;
10596     P.moveInto(Result);
10597     return true;
10598   } else if (T->isArrayType()) {
10599     LValue LV;
10600     APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
10601     if (!EvaluateArray(E, LV, Value, Info))
10602       return false;
10603     Result = Value;
10604   } else if (T->isRecordType()) {
10605     LValue LV;
10606     APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
10607     if (!EvaluateRecord(E, LV, Value, Info))
10608       return false;
10609     Result = Value;
10610   } else if (T->isVoidType()) {
10611     if (!Info.getLangOpts().CPlusPlus11)
10612       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
10613         << E->getType();
10614     if (!EvaluateVoid(E, Info))
10615       return false;
10616   } else if (T->isAtomicType()) {
10617     QualType Unqual = T.getAtomicUnqualifiedType();
10618     if (Unqual->isArrayType() || Unqual->isRecordType()) {
10619       LValue LV;
10620       APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
10621       if (!EvaluateAtomic(E, &LV, Value, Info))
10622         return false;
10623     } else {
10624       if (!EvaluateAtomic(E, nullptr, Result, Info))
10625         return false;
10626     }
10627   } else if (Info.getLangOpts().CPlusPlus11) {
10628     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
10629     return false;
10630   } else {
10631     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10632     return false;
10633   }
10634 
10635   return true;
10636 }
10637 
10638 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
10639 /// cases, the in-place evaluation is essential, since later initializers for
10640 /// an object can indirectly refer to subobjects which were initialized earlier.
10641 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
10642                             const Expr *E, bool AllowNonLiteralTypes) {
10643   assert(!E->isValueDependent());
10644 
10645   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
10646     return false;
10647 
10648   if (E->isRValue()) {
10649     // Evaluate arrays and record types in-place, so that later initializers can
10650     // refer to earlier-initialized members of the object.
10651     QualType T = E->getType();
10652     if (T->isArrayType())
10653       return EvaluateArray(E, This, Result, Info);
10654     else if (T->isRecordType())
10655       return EvaluateRecord(E, This, Result, Info);
10656     else if (T->isAtomicType()) {
10657       QualType Unqual = T.getAtomicUnqualifiedType();
10658       if (Unqual->isArrayType() || Unqual->isRecordType())
10659         return EvaluateAtomic(E, &This, Result, Info);
10660     }
10661   }
10662 
10663   // For any other type, in-place evaluation is unimportant.
10664   return Evaluate(Result, Info, E);
10665 }
10666 
10667 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
10668 /// lvalue-to-rvalue cast if it is an lvalue.
10669 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
10670   if (E->getType().isNull())
10671     return false;
10672 
10673   if (!CheckLiteralType(Info, E))
10674     return false;
10675 
10676   if (!::Evaluate(Result, Info, E))
10677     return false;
10678 
10679   if (E->isGLValue()) {
10680     LValue LV;
10681     LV.setFrom(Info.Ctx, Result);
10682     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
10683       return false;
10684   }
10685 
10686   // Check this core constant expression is a constant expression.
10687   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
10688 }
10689 
10690 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
10691                                  const ASTContext &Ctx, bool &IsConst) {
10692   // Fast-path evaluations of integer literals, since we sometimes see files
10693   // containing vast quantities of these.
10694   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
10695     Result.Val = APValue(APSInt(L->getValue(),
10696                                 L->getType()->isUnsignedIntegerType()));
10697     IsConst = true;
10698     return true;
10699   }
10700 
10701   // This case should be rare, but we need to check it before we check on
10702   // the type below.
10703   if (Exp->getType().isNull()) {
10704     IsConst = false;
10705     return true;
10706   }
10707 
10708   // FIXME: Evaluating values of large array and record types can cause
10709   // performance problems. Only do so in C++11 for now.
10710   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
10711                           Exp->getType()->isRecordType()) &&
10712       !Ctx.getLangOpts().CPlusPlus11) {
10713     IsConst = false;
10714     return true;
10715   }
10716   return false;
10717 }
10718 
10719 
10720 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
10721 /// any crazy technique (that has nothing to do with language standards) that
10722 /// we want to.  If this function returns true, it returns the folded constant
10723 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
10724 /// will be applied to the result.
10725 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
10726   bool IsConst;
10727   if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
10728     return IsConst;
10729 
10730   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
10731   return ::EvaluateAsRValue(Info, this, Result.Val);
10732 }
10733 
10734 bool Expr::EvaluateAsBooleanCondition(bool &Result,
10735                                       const ASTContext &Ctx) const {
10736   EvalResult Scratch;
10737   return EvaluateAsRValue(Scratch, Ctx) &&
10738          HandleConversionToBool(Scratch.Val, Result);
10739 }
10740 
10741 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10742                                       Expr::SideEffectsKind SEK) {
10743   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10744          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10745 }
10746 
10747 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
10748                          SideEffectsKind AllowSideEffects) const {
10749   if (!getType()->isIntegralOrEnumerationType())
10750     return false;
10751 
10752   EvalResult ExprResult;
10753   if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
10754       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10755     return false;
10756 
10757   Result = ExprResult.Val.getInt();
10758   return true;
10759 }
10760 
10761 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10762                            SideEffectsKind AllowSideEffects) const {
10763   if (!getType()->isRealFloatingType())
10764     return false;
10765 
10766   EvalResult ExprResult;
10767   if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
10768       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10769     return false;
10770 
10771   Result = ExprResult.Val.getFloat();
10772   return true;
10773 }
10774 
10775 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
10776   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
10777 
10778   LValue LV;
10779   if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10780       !CheckLValueConstantExpression(Info, getExprLoc(),
10781                                      Ctx.getLValueReferenceType(getType()), LV,
10782                                      Expr::EvaluateForCodeGen))
10783     return false;
10784 
10785   LV.moveInto(Result.Val);
10786   return true;
10787 }
10788 
10789 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
10790                                   const ASTContext &Ctx) const {
10791   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
10792   EvalInfo Info(Ctx, Result, EM);
10793   if (!::Evaluate(Result.Val, Info, this))
10794     return false;
10795 
10796   return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
10797                                  Usage);
10798 }
10799 
10800 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10801                                  const VarDecl *VD,
10802                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
10803   // FIXME: Evaluating initializers for large array and record types can cause
10804   // performance problems. Only do so in C++11 for now.
10805   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
10806       !Ctx.getLangOpts().CPlusPlus11)
10807     return false;
10808 
10809   Expr::EvalStatus EStatus;
10810   EStatus.Diag = &Notes;
10811 
10812   EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10813                                       ? EvalInfo::EM_ConstantExpression
10814                                       : EvalInfo::EM_ConstantFold);
10815   InitInfo.setEvaluatingDecl(VD, Value);
10816 
10817   LValue LVal;
10818   LVal.set(VD);
10819 
10820   // C++11 [basic.start.init]p2:
10821   //  Variables with static storage duration or thread storage duration shall be
10822   //  zero-initialized before any other initialization takes place.
10823   // This behavior is not present in C.
10824   if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
10825       !VD->getType()->isReferenceType()) {
10826     ImplicitValueInitExpr VIE(VD->getType());
10827     if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
10828                          /*AllowNonLiteralTypes=*/true))
10829       return false;
10830   }
10831 
10832   if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10833                        /*AllowNonLiteralTypes=*/true) ||
10834       EStatus.HasSideEffects)
10835     return false;
10836 
10837   return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10838                                  Value);
10839 }
10840 
10841 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10842 /// constant folded, but discard the result.
10843 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
10844   EvalResult Result;
10845   return EvaluateAsRValue(Result, Ctx) &&
10846          !hasUnacceptableSideEffect(Result, SEK);
10847 }
10848 
10849 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
10850                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
10851   EvalResult EvalResult;
10852   EvalResult.Diag = Diag;
10853   bool Result = EvaluateAsRValue(EvalResult, Ctx);
10854   (void)Result;
10855   assert(Result && "Could not evaluate expression");
10856   assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
10857 
10858   return EvalResult.Val.getInt();
10859 }
10860 
10861 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
10862     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
10863   EvalResult EvalResult;
10864   EvalResult.Diag = Diag;
10865   EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
10866   bool Result = ::EvaluateAsRValue(Info, this, EvalResult.Val);
10867   (void)Result;
10868   assert(Result && "Could not evaluate expression");
10869   assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
10870 
10871   return EvalResult.Val.getInt();
10872 }
10873 
10874 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
10875   bool IsConst;
10876   EvalResult EvalResult;
10877   if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
10878     EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
10879     (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10880   }
10881 }
10882 
10883 bool Expr::EvalResult::isGlobalLValue() const {
10884   assert(Val.isLValue());
10885   return IsGlobalLValue(Val.getLValueBase());
10886 }
10887 
10888 
10889 /// isIntegerConstantExpr - this recursive routine will test if an expression is
10890 /// an integer constant expression.
10891 
10892 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10893 /// comma, etc
10894 
10895 // CheckICE - This function does the fundamental ICE checking: the returned
10896 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10897 // and a (possibly null) SourceLocation indicating the location of the problem.
10898 //
10899 // Note that to reduce code duplication, this helper does no evaluation
10900 // itself; the caller checks whether the expression is evaluatable, and
10901 // in the rare cases where CheckICE actually cares about the evaluated
10902 // value, it calls into Evaluate.
10903 
10904 namespace {
10905 
10906 enum ICEKind {
10907   /// This expression is an ICE.
10908   IK_ICE,
10909   /// This expression is not an ICE, but if it isn't evaluated, it's
10910   /// a legal subexpression for an ICE. This return value is used to handle
10911   /// the comma operator in C99 mode, and non-constant subexpressions.
10912   IK_ICEIfUnevaluated,
10913   /// This expression is not an ICE, and is not a legal subexpression for one.
10914   IK_NotICE
10915 };
10916 
10917 struct ICEDiag {
10918   ICEKind Kind;
10919   SourceLocation Loc;
10920 
10921   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
10922 };
10923 
10924 }
10925 
10926 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10927 
10928 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
10929 
10930 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
10931   Expr::EvalResult EVResult;
10932   if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
10933       !EVResult.Val.isInt())
10934     return ICEDiag(IK_NotICE, E->getBeginLoc());
10935 
10936   return NoDiag();
10937 }
10938 
10939 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
10940   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
10941   if (!E->getType()->isIntegralOrEnumerationType())
10942     return ICEDiag(IK_NotICE, E->getBeginLoc());
10943 
10944   switch (E->getStmtClass()) {
10945 #define ABSTRACT_STMT(Node)
10946 #define STMT(Node, Base) case Expr::Node##Class:
10947 #define EXPR(Node, Base)
10948 #include "clang/AST/StmtNodes.inc"
10949   case Expr::PredefinedExprClass:
10950   case Expr::FloatingLiteralClass:
10951   case Expr::ImaginaryLiteralClass:
10952   case Expr::StringLiteralClass:
10953   case Expr::ArraySubscriptExprClass:
10954   case Expr::OMPArraySectionExprClass:
10955   case Expr::MemberExprClass:
10956   case Expr::CompoundAssignOperatorClass:
10957   case Expr::CompoundLiteralExprClass:
10958   case Expr::ExtVectorElementExprClass:
10959   case Expr::DesignatedInitExprClass:
10960   case Expr::ArrayInitLoopExprClass:
10961   case Expr::ArrayInitIndexExprClass:
10962   case Expr::NoInitExprClass:
10963   case Expr::DesignatedInitUpdateExprClass:
10964   case Expr::ImplicitValueInitExprClass:
10965   case Expr::ParenListExprClass:
10966   case Expr::VAArgExprClass:
10967   case Expr::AddrLabelExprClass:
10968   case Expr::StmtExprClass:
10969   case Expr::CXXMemberCallExprClass:
10970   case Expr::CUDAKernelCallExprClass:
10971   case Expr::CXXDynamicCastExprClass:
10972   case Expr::CXXTypeidExprClass:
10973   case Expr::CXXUuidofExprClass:
10974   case Expr::MSPropertyRefExprClass:
10975   case Expr::MSPropertySubscriptExprClass:
10976   case Expr::CXXNullPtrLiteralExprClass:
10977   case Expr::UserDefinedLiteralClass:
10978   case Expr::CXXThisExprClass:
10979   case Expr::CXXThrowExprClass:
10980   case Expr::CXXNewExprClass:
10981   case Expr::CXXDeleteExprClass:
10982   case Expr::CXXPseudoDestructorExprClass:
10983   case Expr::UnresolvedLookupExprClass:
10984   case Expr::TypoExprClass:
10985   case Expr::DependentScopeDeclRefExprClass:
10986   case Expr::CXXConstructExprClass:
10987   case Expr::CXXInheritedCtorInitExprClass:
10988   case Expr::CXXStdInitializerListExprClass:
10989   case Expr::CXXBindTemporaryExprClass:
10990   case Expr::ExprWithCleanupsClass:
10991   case Expr::CXXTemporaryObjectExprClass:
10992   case Expr::CXXUnresolvedConstructExprClass:
10993   case Expr::CXXDependentScopeMemberExprClass:
10994   case Expr::UnresolvedMemberExprClass:
10995   case Expr::ObjCStringLiteralClass:
10996   case Expr::ObjCBoxedExprClass:
10997   case Expr::ObjCArrayLiteralClass:
10998   case Expr::ObjCDictionaryLiteralClass:
10999   case Expr::ObjCEncodeExprClass:
11000   case Expr::ObjCMessageExprClass:
11001   case Expr::ObjCSelectorExprClass:
11002   case Expr::ObjCProtocolExprClass:
11003   case Expr::ObjCIvarRefExprClass:
11004   case Expr::ObjCPropertyRefExprClass:
11005   case Expr::ObjCSubscriptRefExprClass:
11006   case Expr::ObjCIsaExprClass:
11007   case Expr::ObjCAvailabilityCheckExprClass:
11008   case Expr::ShuffleVectorExprClass:
11009   case Expr::ConvertVectorExprClass:
11010   case Expr::BlockExprClass:
11011   case Expr::NoStmtClass:
11012   case Expr::OpaqueValueExprClass:
11013   case Expr::PackExpansionExprClass:
11014   case Expr::SubstNonTypeTemplateParmPackExprClass:
11015   case Expr::FunctionParmPackExprClass:
11016   case Expr::AsTypeExprClass:
11017   case Expr::ObjCIndirectCopyRestoreExprClass:
11018   case Expr::MaterializeTemporaryExprClass:
11019   case Expr::PseudoObjectExprClass:
11020   case Expr::AtomicExprClass:
11021   case Expr::LambdaExprClass:
11022   case Expr::CXXFoldExprClass:
11023   case Expr::CoawaitExprClass:
11024   case Expr::DependentCoawaitExprClass:
11025   case Expr::CoyieldExprClass:
11026     return ICEDiag(IK_NotICE, E->getBeginLoc());
11027 
11028   case Expr::InitListExprClass: {
11029     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
11030     // form "T x = { a };" is equivalent to "T x = a;".
11031     // Unless we're initializing a reference, T is a scalar as it is known to be
11032     // of integral or enumeration type.
11033     if (E->isRValue())
11034       if (cast<InitListExpr>(E)->getNumInits() == 1)
11035         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
11036     return ICEDiag(IK_NotICE, E->getBeginLoc());
11037   }
11038 
11039   case Expr::SizeOfPackExprClass:
11040   case Expr::GNUNullExprClass:
11041     // GCC considers the GNU __null value to be an integral constant expression.
11042     return NoDiag();
11043 
11044   case Expr::SubstNonTypeTemplateParmExprClass:
11045     return
11046       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
11047 
11048   case Expr::ParenExprClass:
11049     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
11050   case Expr::GenericSelectionExprClass:
11051     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
11052   case Expr::IntegerLiteralClass:
11053   case Expr::FixedPointLiteralClass:
11054   case Expr::CharacterLiteralClass:
11055   case Expr::ObjCBoolLiteralExprClass:
11056   case Expr::CXXBoolLiteralExprClass:
11057   case Expr::CXXScalarValueInitExprClass:
11058   case Expr::TypeTraitExprClass:
11059   case Expr::ArrayTypeTraitExprClass:
11060   case Expr::ExpressionTraitExprClass:
11061   case Expr::CXXNoexceptExprClass:
11062     return NoDiag();
11063   case Expr::CallExprClass:
11064   case Expr::CXXOperatorCallExprClass: {
11065     // C99 6.6/3 allows function calls within unevaluated subexpressions of
11066     // constant expressions, but they can never be ICEs because an ICE cannot
11067     // contain an operand of (pointer to) function type.
11068     const CallExpr *CE = cast<CallExpr>(E);
11069     if (CE->getBuiltinCallee())
11070       return CheckEvalInICE(E, Ctx);
11071     return ICEDiag(IK_NotICE, E->getBeginLoc());
11072   }
11073   case Expr::DeclRefExprClass: {
11074     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
11075       return NoDiag();
11076     const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
11077     if (Ctx.getLangOpts().CPlusPlus &&
11078         D && IsConstNonVolatile(D->getType())) {
11079       // Parameter variables are never constants.  Without this check,
11080       // getAnyInitializer() can find a default argument, which leads
11081       // to chaos.
11082       if (isa<ParmVarDecl>(D))
11083         return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
11084 
11085       // C++ 7.1.5.1p2
11086       //   A variable of non-volatile const-qualified integral or enumeration
11087       //   type initialized by an ICE can be used in ICEs.
11088       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
11089         if (!Dcl->getType()->isIntegralOrEnumerationType())
11090           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
11091 
11092         const VarDecl *VD;
11093         // Look for a declaration of this variable that has an initializer, and
11094         // check whether it is an ICE.
11095         if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
11096           return NoDiag();
11097         else
11098           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
11099       }
11100     }
11101     return ICEDiag(IK_NotICE, E->getBeginLoc());
11102   }
11103   case Expr::UnaryOperatorClass: {
11104     const UnaryOperator *Exp = cast<UnaryOperator>(E);
11105     switch (Exp->getOpcode()) {
11106     case UO_PostInc:
11107     case UO_PostDec:
11108     case UO_PreInc:
11109     case UO_PreDec:
11110     case UO_AddrOf:
11111     case UO_Deref:
11112     case UO_Coawait:
11113       // C99 6.6/3 allows increment and decrement within unevaluated
11114       // subexpressions of constant expressions, but they can never be ICEs
11115       // because an ICE cannot contain an lvalue operand.
11116       return ICEDiag(IK_NotICE, E->getBeginLoc());
11117     case UO_Extension:
11118     case UO_LNot:
11119     case UO_Plus:
11120     case UO_Minus:
11121     case UO_Not:
11122     case UO_Real:
11123     case UO_Imag:
11124       return CheckICE(Exp->getSubExpr(), Ctx);
11125     }
11126 
11127     // OffsetOf falls through here.
11128     LLVM_FALLTHROUGH;
11129   }
11130   case Expr::OffsetOfExprClass: {
11131     // Note that per C99, offsetof must be an ICE. And AFAIK, using
11132     // EvaluateAsRValue matches the proposed gcc behavior for cases like
11133     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
11134     // compliance: we should warn earlier for offsetof expressions with
11135     // array subscripts that aren't ICEs, and if the array subscripts
11136     // are ICEs, the value of the offsetof must be an integer constant.
11137     return CheckEvalInICE(E, Ctx);
11138   }
11139   case Expr::UnaryExprOrTypeTraitExprClass: {
11140     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
11141     if ((Exp->getKind() ==  UETT_SizeOf) &&
11142         Exp->getTypeOfArgument()->isVariableArrayType())
11143       return ICEDiag(IK_NotICE, E->getBeginLoc());
11144     return NoDiag();
11145   }
11146   case Expr::BinaryOperatorClass: {
11147     const BinaryOperator *Exp = cast<BinaryOperator>(E);
11148     switch (Exp->getOpcode()) {
11149     case BO_PtrMemD:
11150     case BO_PtrMemI:
11151     case BO_Assign:
11152     case BO_MulAssign:
11153     case BO_DivAssign:
11154     case BO_RemAssign:
11155     case BO_AddAssign:
11156     case BO_SubAssign:
11157     case BO_ShlAssign:
11158     case BO_ShrAssign:
11159     case BO_AndAssign:
11160     case BO_XorAssign:
11161     case BO_OrAssign:
11162       // C99 6.6/3 allows assignments within unevaluated subexpressions of
11163       // constant expressions, but they can never be ICEs because an ICE cannot
11164       // contain an lvalue operand.
11165       return ICEDiag(IK_NotICE, E->getBeginLoc());
11166 
11167     case BO_Mul:
11168     case BO_Div:
11169     case BO_Rem:
11170     case BO_Add:
11171     case BO_Sub:
11172     case BO_Shl:
11173     case BO_Shr:
11174     case BO_LT:
11175     case BO_GT:
11176     case BO_LE:
11177     case BO_GE:
11178     case BO_EQ:
11179     case BO_NE:
11180     case BO_And:
11181     case BO_Xor:
11182     case BO_Or:
11183     case BO_Comma:
11184     case BO_Cmp: {
11185       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11186       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
11187       if (Exp->getOpcode() == BO_Div ||
11188           Exp->getOpcode() == BO_Rem) {
11189         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
11190         // we don't evaluate one.
11191         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
11192           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
11193           if (REval == 0)
11194             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
11195           if (REval.isSigned() && REval.isAllOnesValue()) {
11196             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
11197             if (LEval.isMinSignedValue())
11198               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
11199           }
11200         }
11201       }
11202       if (Exp->getOpcode() == BO_Comma) {
11203         if (Ctx.getLangOpts().C99) {
11204           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
11205           // if it isn't evaluated.
11206           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
11207             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
11208         } else {
11209           // In both C89 and C++, commas in ICEs are illegal.
11210           return ICEDiag(IK_NotICE, E->getBeginLoc());
11211         }
11212       }
11213       return Worst(LHSResult, RHSResult);
11214     }
11215     case BO_LAnd:
11216     case BO_LOr: {
11217       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11218       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
11219       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
11220         // Rare case where the RHS has a comma "side-effect"; we need
11221         // to actually check the condition to see whether the side
11222         // with the comma is evaluated.
11223         if ((Exp->getOpcode() == BO_LAnd) !=
11224             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
11225           return RHSResult;
11226         return NoDiag();
11227       }
11228 
11229       return Worst(LHSResult, RHSResult);
11230     }
11231     }
11232     LLVM_FALLTHROUGH;
11233   }
11234   case Expr::ImplicitCastExprClass:
11235   case Expr::CStyleCastExprClass:
11236   case Expr::CXXFunctionalCastExprClass:
11237   case Expr::CXXStaticCastExprClass:
11238   case Expr::CXXReinterpretCastExprClass:
11239   case Expr::CXXConstCastExprClass:
11240   case Expr::ObjCBridgedCastExprClass: {
11241     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
11242     if (isa<ExplicitCastExpr>(E)) {
11243       if (const FloatingLiteral *FL
11244             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
11245         unsigned DestWidth = Ctx.getIntWidth(E->getType());
11246         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
11247         APSInt IgnoredVal(DestWidth, !DestSigned);
11248         bool Ignored;
11249         // If the value does not fit in the destination type, the behavior is
11250         // undefined, so we are not required to treat it as a constant
11251         // expression.
11252         if (FL->getValue().convertToInteger(IgnoredVal,
11253                                             llvm::APFloat::rmTowardZero,
11254                                             &Ignored) & APFloat::opInvalidOp)
11255           return ICEDiag(IK_NotICE, E->getBeginLoc());
11256         return NoDiag();
11257       }
11258     }
11259     switch (cast<CastExpr>(E)->getCastKind()) {
11260     case CK_LValueToRValue:
11261     case CK_AtomicToNonAtomic:
11262     case CK_NonAtomicToAtomic:
11263     case CK_NoOp:
11264     case CK_IntegralToBoolean:
11265     case CK_IntegralCast:
11266       return CheckICE(SubExpr, Ctx);
11267     default:
11268       return ICEDiag(IK_NotICE, E->getBeginLoc());
11269     }
11270   }
11271   case Expr::BinaryConditionalOperatorClass: {
11272     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
11273     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
11274     if (CommonResult.Kind == IK_NotICE) return CommonResult;
11275     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
11276     if (FalseResult.Kind == IK_NotICE) return FalseResult;
11277     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
11278     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
11279         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
11280     return FalseResult;
11281   }
11282   case Expr::ConditionalOperatorClass: {
11283     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
11284     // If the condition (ignoring parens) is a __builtin_constant_p call,
11285     // then only the true side is actually considered in an integer constant
11286     // expression, and it is fully evaluated.  This is an important GNU
11287     // extension.  See GCC PR38377 for discussion.
11288     if (const CallExpr *CallCE
11289         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
11290       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
11291         return CheckEvalInICE(E, Ctx);
11292     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
11293     if (CondResult.Kind == IK_NotICE)
11294       return CondResult;
11295 
11296     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
11297     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
11298 
11299     if (TrueResult.Kind == IK_NotICE)
11300       return TrueResult;
11301     if (FalseResult.Kind == IK_NotICE)
11302       return FalseResult;
11303     if (CondResult.Kind == IK_ICEIfUnevaluated)
11304       return CondResult;
11305     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
11306       return NoDiag();
11307     // Rare case where the diagnostics depend on which side is evaluated
11308     // Note that if we get here, CondResult is 0, and at least one of
11309     // TrueResult and FalseResult is non-zero.
11310     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
11311       return FalseResult;
11312     return TrueResult;
11313   }
11314   case Expr::CXXDefaultArgExprClass:
11315     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
11316   case Expr::CXXDefaultInitExprClass:
11317     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
11318   case Expr::ChooseExprClass: {
11319     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
11320   }
11321   }
11322 
11323   llvm_unreachable("Invalid StmtClass!");
11324 }
11325 
11326 /// Evaluate an expression as a C++11 integral constant expression.
11327 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
11328                                                     const Expr *E,
11329                                                     llvm::APSInt *Value,
11330                                                     SourceLocation *Loc) {
11331   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
11332     if (Loc) *Loc = E->getExprLoc();
11333     return false;
11334   }
11335 
11336   APValue Result;
11337   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
11338     return false;
11339 
11340   if (!Result.isInt()) {
11341     if (Loc) *Loc = E->getExprLoc();
11342     return false;
11343   }
11344 
11345   if (Value) *Value = Result.getInt();
11346   return true;
11347 }
11348 
11349 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
11350                                  SourceLocation *Loc) const {
11351   if (Ctx.getLangOpts().CPlusPlus11)
11352     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
11353 
11354   ICEDiag D = CheckICE(this, Ctx);
11355   if (D.Kind != IK_ICE) {
11356     if (Loc) *Loc = D.Loc;
11357     return false;
11358   }
11359   return true;
11360 }
11361 
11362 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
11363                                  SourceLocation *Loc, bool isEvaluated) const {
11364   if (Ctx.getLangOpts().CPlusPlus11)
11365     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
11366 
11367   if (!isIntegerConstantExpr(Ctx, Loc))
11368     return false;
11369   // The only possible side-effects here are due to UB discovered in the
11370   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
11371   // required to treat the expression as an ICE, so we produce the folded
11372   // value.
11373   if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
11374     llvm_unreachable("ICE cannot be evaluated!");
11375   return true;
11376 }
11377 
11378 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
11379   return CheckICE(this, Ctx).Kind == IK_ICE;
11380 }
11381 
11382 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
11383                                SourceLocation *Loc) const {
11384   // We support this checking in C++98 mode in order to diagnose compatibility
11385   // issues.
11386   assert(Ctx.getLangOpts().CPlusPlus);
11387 
11388   // Build evaluation settings.
11389   Expr::EvalStatus Status;
11390   SmallVector<PartialDiagnosticAt, 8> Diags;
11391   Status.Diag = &Diags;
11392   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
11393 
11394   APValue Scratch;
11395   bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
11396 
11397   if (!Diags.empty()) {
11398     IsConstExpr = false;
11399     if (Loc) *Loc = Diags[0].first;
11400   } else if (!IsConstExpr) {
11401     // FIXME: This shouldn't happen.
11402     if (Loc) *Loc = getExprLoc();
11403   }
11404 
11405   return IsConstExpr;
11406 }
11407 
11408 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
11409                                     const FunctionDecl *Callee,
11410                                     ArrayRef<const Expr*> Args,
11411                                     const Expr *This) const {
11412   Expr::EvalStatus Status;
11413   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
11414 
11415   LValue ThisVal;
11416   const LValue *ThisPtr = nullptr;
11417   if (This) {
11418 #ifndef NDEBUG
11419     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
11420     assert(MD && "Don't provide `this` for non-methods.");
11421     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
11422 #endif
11423     if (EvaluateObjectArgument(Info, This, ThisVal))
11424       ThisPtr = &ThisVal;
11425     if (Info.EvalStatus.HasSideEffects)
11426       return false;
11427   }
11428 
11429   ArgVector ArgValues(Args.size());
11430   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
11431        I != E; ++I) {
11432     if ((*I)->isValueDependent() ||
11433         !Evaluate(ArgValues[I - Args.begin()], Info, *I))
11434       // If evaluation fails, throw away the argument entirely.
11435       ArgValues[I - Args.begin()] = APValue();
11436     if (Info.EvalStatus.HasSideEffects)
11437       return false;
11438   }
11439 
11440   // Build fake call to Callee.
11441   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
11442                        ArgValues.data());
11443   return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
11444 }
11445 
11446 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
11447                                    SmallVectorImpl<
11448                                      PartialDiagnosticAt> &Diags) {
11449   // FIXME: It would be useful to check constexpr function templates, but at the
11450   // moment the constant expression evaluator cannot cope with the non-rigorous
11451   // ASTs which we build for dependent expressions.
11452   if (FD->isDependentContext())
11453     return true;
11454 
11455   Expr::EvalStatus Status;
11456   Status.Diag = &Diags;
11457 
11458   EvalInfo Info(FD->getASTContext(), Status,
11459                 EvalInfo::EM_PotentialConstantExpression);
11460 
11461   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
11462   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
11463 
11464   // Fabricate an arbitrary expression on the stack and pretend that it
11465   // is a temporary being used as the 'this' pointer.
11466   LValue This;
11467   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
11468   This.set({&VIE, Info.CurrentCall->Index});
11469 
11470   ArrayRef<const Expr*> Args;
11471 
11472   APValue Scratch;
11473   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
11474     // Evaluate the call as a constant initializer, to allow the construction
11475     // of objects of non-literal types.
11476     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
11477     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
11478   } else {
11479     SourceLocation Loc = FD->getLocation();
11480     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
11481                        Args, FD->getBody(), Info, Scratch, nullptr);
11482   }
11483 
11484   return Diags.empty();
11485 }
11486 
11487 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
11488                                               const FunctionDecl *FD,
11489                                               SmallVectorImpl<
11490                                                 PartialDiagnosticAt> &Diags) {
11491   Expr::EvalStatus Status;
11492   Status.Diag = &Diags;
11493 
11494   EvalInfo Info(FD->getASTContext(), Status,
11495                 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
11496 
11497   // Fabricate a call stack frame to give the arguments a plausible cover story.
11498   ArrayRef<const Expr*> Args;
11499   ArgVector ArgValues(0);
11500   bool Success = EvaluateArgs(Args, ArgValues, Info);
11501   (void)Success;
11502   assert(Success &&
11503          "Failed to set up arguments for potential constant evaluation");
11504   CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
11505 
11506   APValue ResultScratch;
11507   Evaluate(ResultScratch, Info, E);
11508   return Diags.empty();
11509 }
11510 
11511 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
11512                                  unsigned Type) const {
11513   if (!getType()->isPointerType())
11514     return false;
11515 
11516   Expr::EvalStatus Status;
11517   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
11518   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
11519 }
11520