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 using namespace clang;
52 using llvm::APSInt;
53 using llvm::APFloat;
54 
55 static bool IsGlobalLValue(APValue::LValueBase B);
56 
57 namespace {
58   struct LValue;
59   struct CallStackFrame;
60   struct EvalInfo;
61 
62   static QualType getType(APValue::LValueBase B) {
63     if (!B) return QualType();
64     if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65       return D->getType();
66 
67     const Expr *Base = B.get<const Expr*>();
68 
69     // For a materialized temporary, the type of the temporary we materialized
70     // may not be the type of the expression.
71     if (const MaterializeTemporaryExpr *MTE =
72             dyn_cast<MaterializeTemporaryExpr>(Base)) {
73       SmallVector<const Expr *, 2> CommaLHSs;
74       SmallVector<SubobjectAdjustment, 2> Adjustments;
75       const Expr *Temp = MTE->GetTemporaryExpr();
76       const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
77                                                                Adjustments);
78       // Keep any cv-qualifiers from the reference if we generated a temporary
79       // for it directly. Otherwise use the type after adjustment.
80       if (!Adjustments.empty())
81         return Inner->getType();
82     }
83 
84     return Base->getType();
85   }
86 
87   /// Get an LValue path entry, which is known to not be an array index, as a
88   /// field or base class.
89   static
90   APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
91     APValue::BaseOrMemberType Value;
92     Value.setFromOpaqueValue(E.BaseOrMember);
93     return Value;
94   }
95 
96   /// Get an LValue path entry, which is known to not be an array index, as a
97   /// field declaration.
98   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
99     return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
100   }
101   /// Get an LValue path entry, which is known to not be an array index, as a
102   /// base class declaration.
103   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
104     return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
105   }
106   /// Determine whether this LValue path entry for a base class names a virtual
107   /// base class.
108   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
109     return getAsBaseOrMember(E).getInt();
110   }
111 
112   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
113   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
114     const FunctionDecl *Callee = CE->getDirectCallee();
115     return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
116   }
117 
118   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
119   /// This will look through a single cast.
120   ///
121   /// Returns null if we couldn't unwrap a function with alloc_size.
122   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
123     if (!E->getType()->isPointerType())
124       return nullptr;
125 
126     E = E->IgnoreParens();
127     // If we're doing a variable assignment from e.g. malloc(N), there will
128     // probably be a cast of some kind. Ignore it.
129     if (const auto *Cast = dyn_cast<CastExpr>(E))
130       E = Cast->getSubExpr()->IgnoreParens();
131 
132     if (const auto *CE = dyn_cast<CallExpr>(E))
133       return getAllocSizeAttr(CE) ? CE : nullptr;
134     return nullptr;
135   }
136 
137   /// Determines whether or not the given Base contains a call to a function
138   /// with the alloc_size attribute.
139   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
140     const auto *E = Base.dyn_cast<const Expr *>();
141     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
142   }
143 
144   /// Determines if an LValue with the given LValueBase will have an unsized
145   /// array in its designator.
146   /// Find the path length and type of the most-derived subobject in the given
147   /// path, and find the size of the containing array, if any.
148   static unsigned
149   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
150                            ArrayRef<APValue::LValuePathEntry> Path,
151                            uint64_t &ArraySize, QualType &Type, bool &IsArray) {
152     // This only accepts LValueBases from APValues, and APValues don't support
153     // arrays that lack size info.
154     assert(!isBaseAnAllocSizeCall(Base) &&
155            "Unsized arrays shouldn't appear here");
156     unsigned MostDerivedLength = 0;
157     Type = getType(Base);
158 
159     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
160       if (Type->isArrayType()) {
161         const ConstantArrayType *CAT =
162             cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
163         Type = CAT->getElementType();
164         ArraySize = CAT->getSize().getZExtValue();
165         MostDerivedLength = I + 1;
166         IsArray = true;
167       } else if (Type->isAnyComplexType()) {
168         const ComplexType *CT = Type->castAs<ComplexType>();
169         Type = CT->getElementType();
170         ArraySize = 2;
171         MostDerivedLength = I + 1;
172         IsArray = true;
173       } else if (const FieldDecl *FD = getAsField(Path[I])) {
174         Type = FD->getType();
175         ArraySize = 0;
176         MostDerivedLength = I + 1;
177         IsArray = false;
178       } else {
179         // Path[I] describes a base class.
180         ArraySize = 0;
181         IsArray = false;
182       }
183     }
184     return MostDerivedLength;
185   }
186 
187   // The order of this enum is important for diagnostics.
188   enum CheckSubobjectKind {
189     CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
190     CSK_This, CSK_Real, CSK_Imag
191   };
192 
193   /// A path from a glvalue to a subobject of that glvalue.
194   struct SubobjectDesignator {
195     /// True if the subobject was named in a manner not supported by C++11. Such
196     /// lvalues can still be folded, but they are not core constant expressions
197     /// and we cannot perform lvalue-to-rvalue conversions on them.
198     unsigned Invalid : 1;
199 
200     /// Is this a pointer one past the end of an object?
201     unsigned IsOnePastTheEnd : 1;
202 
203     /// Indicator of whether the first entry is an unsized array.
204     unsigned FirstEntryIsAnUnsizedArray : 1;
205 
206     /// Indicator of whether the most-derived object is an array element.
207     unsigned MostDerivedIsArrayElement : 1;
208 
209     /// The length of the path to the most-derived object of which this is a
210     /// subobject.
211     unsigned MostDerivedPathLength : 28;
212 
213     /// The size of the array of which the most-derived object is an element.
214     /// This will always be 0 if the most-derived object is not an array
215     /// element. 0 is not an indicator of whether or not the most-derived object
216     /// is an array, however, because 0-length arrays are allowed.
217     ///
218     /// If the current array is an unsized array, the value of this is
219     /// undefined.
220     uint64_t MostDerivedArraySize;
221 
222     /// The type of the most derived object referred to by this address.
223     QualType MostDerivedType;
224 
225     typedef APValue::LValuePathEntry PathEntry;
226 
227     /// The entries on the path from the glvalue to the designated subobject.
228     SmallVector<PathEntry, 8> Entries;
229 
230     SubobjectDesignator() : Invalid(true) {}
231 
232     explicit SubobjectDesignator(QualType T)
233         : Invalid(false), IsOnePastTheEnd(false),
234           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
235           MostDerivedPathLength(0), MostDerivedArraySize(0),
236           MostDerivedType(T) {}
237 
238     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
239         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
240           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
241           MostDerivedPathLength(0), MostDerivedArraySize(0) {
242       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
243       if (!Invalid) {
244         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
245         ArrayRef<PathEntry> VEntries = V.getLValuePath();
246         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
247         if (V.getLValueBase()) {
248           bool IsArray = false;
249           MostDerivedPathLength = findMostDerivedSubobject(
250               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
251               MostDerivedType, IsArray);
252           MostDerivedIsArrayElement = IsArray;
253         }
254       }
255     }
256 
257     void setInvalid() {
258       Invalid = true;
259       Entries.clear();
260     }
261 
262     /// Determine whether the most derived subobject is an array without a
263     /// known bound.
264     bool isMostDerivedAnUnsizedArray() const {
265       assert(!Invalid && "Calling this makes no sense on invalid designators");
266       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
267     }
268 
269     /// Determine what the most derived array's size is. Results in an assertion
270     /// failure if the most derived array lacks a size.
271     uint64_t getMostDerivedArraySize() const {
272       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
273       return MostDerivedArraySize;
274     }
275 
276     /// Determine whether this is a one-past-the-end pointer.
277     bool isOnePastTheEnd() const {
278       assert(!Invalid);
279       if (IsOnePastTheEnd)
280         return true;
281       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
282           Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
283         return true;
284       return false;
285     }
286 
287     /// Check that this refers to a valid subobject.
288     bool isValidSubobject() const {
289       if (Invalid)
290         return false;
291       return !isOnePastTheEnd();
292     }
293     /// Check that this refers to a valid subobject, and if not, produce a
294     /// relevant diagnostic and set the designator as invalid.
295     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
296 
297     /// Update this designator to refer to the first element within this array.
298     void addArrayUnchecked(const ConstantArrayType *CAT) {
299       PathEntry Entry;
300       Entry.ArrayIndex = 0;
301       Entries.push_back(Entry);
302 
303       // This is a most-derived object.
304       MostDerivedType = CAT->getElementType();
305       MostDerivedIsArrayElement = true;
306       MostDerivedArraySize = CAT->getSize().getZExtValue();
307       MostDerivedPathLength = Entries.size();
308     }
309     /// Update this designator to refer to the first element within the array of
310     /// elements of type T. This is an array of unknown size.
311     void addUnsizedArrayUnchecked(QualType ElemTy) {
312       PathEntry Entry;
313       Entry.ArrayIndex = 0;
314       Entries.push_back(Entry);
315 
316       MostDerivedType = ElemTy;
317       MostDerivedIsArrayElement = true;
318       // The value in MostDerivedArraySize is undefined in this case. So, set it
319       // to an arbitrary value that's likely to loudly break things if it's
320       // used.
321       MostDerivedArraySize = std::numeric_limits<uint64_t>::max() / 2;
322       MostDerivedPathLength = Entries.size();
323     }
324     /// Update this designator to refer to the given base or member of this
325     /// object.
326     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
327       PathEntry Entry;
328       APValue::BaseOrMemberType Value(D, Virtual);
329       Entry.BaseOrMember = Value.getOpaqueValue();
330       Entries.push_back(Entry);
331 
332       // If this isn't a base class, it's a new most-derived object.
333       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
334         MostDerivedType = FD->getType();
335         MostDerivedIsArrayElement = false;
336         MostDerivedArraySize = 0;
337         MostDerivedPathLength = Entries.size();
338       }
339     }
340     /// Update this designator to refer to the given complex component.
341     void addComplexUnchecked(QualType EltTy, bool Imag) {
342       PathEntry Entry;
343       Entry.ArrayIndex = Imag;
344       Entries.push_back(Entry);
345 
346       // This is technically a most-derived object, though in practice this
347       // is unlikely to matter.
348       MostDerivedType = EltTy;
349       MostDerivedIsArrayElement = true;
350       MostDerivedArraySize = 2;
351       MostDerivedPathLength = Entries.size();
352     }
353     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
354                                    const APSInt &N);
355     /// Add N to the address of this subobject.
356     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
357       if (Invalid || !N) return;
358       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
359       if (isMostDerivedAnUnsizedArray()) {
360         // Can't verify -- trust that the user is doing the right thing (or if
361         // not, trust that the caller will catch the bad behavior).
362         // FIXME: Should we reject if this overflows, at least?
363         Entries.back().ArrayIndex += TruncatedN;
364         return;
365       }
366 
367       // [expr.add]p4: For the purposes of these operators, a pointer to a
368       // nonarray object behaves the same as a pointer to the first element of
369       // an array of length one with the type of the object as its element type.
370       bool IsArray = MostDerivedPathLength == Entries.size() &&
371                      MostDerivedIsArrayElement;
372       uint64_t ArrayIndex =
373           IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
374       uint64_t ArraySize =
375           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
376 
377       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
378         // Calculate the actual index in a wide enough type, so we can include
379         // it in the note.
380         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
381         (llvm::APInt&)N += ArrayIndex;
382         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
383         diagnosePointerArithmetic(Info, E, N);
384         setInvalid();
385         return;
386       }
387 
388       ArrayIndex += TruncatedN;
389       assert(ArrayIndex <= ArraySize &&
390              "bounds check succeeded for out-of-bounds index");
391 
392       if (IsArray)
393         Entries.back().ArrayIndex = ArrayIndex;
394       else
395         IsOnePastTheEnd = (ArrayIndex != 0);
396     }
397   };
398 
399   /// A stack frame in the constexpr call stack.
400   struct CallStackFrame {
401     EvalInfo &Info;
402 
403     /// Parent - The caller of this stack frame.
404     CallStackFrame *Caller;
405 
406     /// Callee - The function which was called.
407     const FunctionDecl *Callee;
408 
409     /// This - The binding for the this pointer in this call, if any.
410     const LValue *This;
411 
412     /// Arguments - Parameter bindings for this function call, indexed by
413     /// parameters' function scope indices.
414     APValue *Arguments;
415 
416     // Note that we intentionally use std::map here so that references to
417     // values are stable.
418     typedef std::map<const void*, APValue> MapTy;
419     typedef MapTy::const_iterator temp_iterator;
420     /// Temporaries - Temporary lvalues materialized within this stack frame.
421     MapTy Temporaries;
422 
423     /// CallLoc - The location of the call expression for this call.
424     SourceLocation CallLoc;
425 
426     /// Index - The call index of this call.
427     unsigned Index;
428 
429     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
430     // on the overall stack usage of deeply-recursing constexpr evaluataions.
431     // (We should cache this map rather than recomputing it repeatedly.)
432     // But let's try this and see how it goes; we can look into caching the map
433     // as a later change.
434 
435     /// LambdaCaptureFields - Mapping from captured variables/this to
436     /// corresponding data members in the closure class.
437     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
438     FieldDecl *LambdaThisCaptureField;
439 
440     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
441                    const FunctionDecl *Callee, const LValue *This,
442                    APValue *Arguments);
443     ~CallStackFrame();
444 
445     APValue *getTemporary(const void *Key) {
446       MapTy::iterator I = Temporaries.find(Key);
447       return I == Temporaries.end() ? nullptr : &I->second;
448     }
449     APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
450   };
451 
452   /// Temporarily override 'this'.
453   class ThisOverrideRAII {
454   public:
455     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
456         : Frame(Frame), OldThis(Frame.This) {
457       if (Enable)
458         Frame.This = NewThis;
459     }
460     ~ThisOverrideRAII() {
461       Frame.This = OldThis;
462     }
463   private:
464     CallStackFrame &Frame;
465     const LValue *OldThis;
466   };
467 
468   /// A partial diagnostic which we might know in advance that we are not going
469   /// to emit.
470   class OptionalDiagnostic {
471     PartialDiagnostic *Diag;
472 
473   public:
474     explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
475       : Diag(Diag) {}
476 
477     template<typename T>
478     OptionalDiagnostic &operator<<(const T &v) {
479       if (Diag)
480         *Diag << v;
481       return *this;
482     }
483 
484     OptionalDiagnostic &operator<<(const APSInt &I) {
485       if (Diag) {
486         SmallVector<char, 32> Buffer;
487         I.toString(Buffer);
488         *Diag << StringRef(Buffer.data(), Buffer.size());
489       }
490       return *this;
491     }
492 
493     OptionalDiagnostic &operator<<(const APFloat &F) {
494       if (Diag) {
495         // FIXME: Force the precision of the source value down so we don't
496         // print digits which are usually useless (we don't really care here if
497         // we truncate a digit by accident in edge cases).  Ideally,
498         // APFloat::toString would automatically print the shortest
499         // representation which rounds to the correct value, but it's a bit
500         // tricky to implement.
501         unsigned precision =
502             llvm::APFloat::semanticsPrecision(F.getSemantics());
503         precision = (precision * 59 + 195) / 196;
504         SmallVector<char, 32> Buffer;
505         F.toString(Buffer, precision);
506         *Diag << StringRef(Buffer.data(), Buffer.size());
507       }
508       return *this;
509     }
510   };
511 
512   /// A cleanup, and a flag indicating whether it is lifetime-extended.
513   class Cleanup {
514     llvm::PointerIntPair<APValue*, 1, bool> Value;
515 
516   public:
517     Cleanup(APValue *Val, bool IsLifetimeExtended)
518         : Value(Val, IsLifetimeExtended) {}
519 
520     bool isLifetimeExtended() const { return Value.getInt(); }
521     void endLifetime() {
522       *Value.getPointer() = APValue();
523     }
524   };
525 
526   /// EvalInfo - This is a private struct used by the evaluator to capture
527   /// information about a subexpression as it is folded.  It retains information
528   /// about the AST context, but also maintains information about the folded
529   /// expression.
530   ///
531   /// If an expression could be evaluated, it is still possible it is not a C
532   /// "integer constant expression" or constant expression.  If not, this struct
533   /// captures information about how and why not.
534   ///
535   /// One bit of information passed *into* the request for constant folding
536   /// indicates whether the subexpression is "evaluated" or not according to C
537   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
538   /// evaluate the expression regardless of what the RHS is, but C only allows
539   /// certain things in certain situations.
540   struct EvalInfo {
541     ASTContext &Ctx;
542 
543     /// EvalStatus - Contains information about the evaluation.
544     Expr::EvalStatus &EvalStatus;
545 
546     /// CurrentCall - The top of the constexpr call stack.
547     CallStackFrame *CurrentCall;
548 
549     /// CallStackDepth - The number of calls in the call stack right now.
550     unsigned CallStackDepth;
551 
552     /// NextCallIndex - The next call index to assign.
553     unsigned NextCallIndex;
554 
555     /// StepsLeft - The remaining number of evaluation steps we're permitted
556     /// to perform. This is essentially a limit for the number of statements
557     /// we will evaluate.
558     unsigned StepsLeft;
559 
560     /// BottomFrame - The frame in which evaluation started. This must be
561     /// initialized after CurrentCall and CallStackDepth.
562     CallStackFrame BottomFrame;
563 
564     /// A stack of values whose lifetimes end at the end of some surrounding
565     /// evaluation frame.
566     llvm::SmallVector<Cleanup, 16> CleanupStack;
567 
568     /// EvaluatingDecl - This is the declaration whose initializer is being
569     /// evaluated, if any.
570     APValue::LValueBase EvaluatingDecl;
571 
572     /// EvaluatingDeclValue - This is the value being constructed for the
573     /// declaration whose initializer is being evaluated, if any.
574     APValue *EvaluatingDeclValue;
575 
576     /// The current array initialization index, if we're performing array
577     /// initialization.
578     uint64_t ArrayInitIndex = -1;
579 
580     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
581     /// notes attached to it will also be stored, otherwise they will not be.
582     bool HasActiveDiagnostic;
583 
584     /// \brief Have we emitted a diagnostic explaining why we couldn't constant
585     /// fold (not just why it's not strictly a constant expression)?
586     bool HasFoldFailureDiagnostic;
587 
588     /// \brief Whether or not we're currently speculatively evaluating.
589     bool IsSpeculativelyEvaluating;
590 
591     enum EvaluationMode {
592       /// Evaluate as a constant expression. Stop if we find that the expression
593       /// is not a constant expression.
594       EM_ConstantExpression,
595 
596       /// Evaluate as a potential constant expression. Keep going if we hit a
597       /// construct that we can't evaluate yet (because we don't yet know the
598       /// value of something) but stop if we hit something that could never be
599       /// a constant expression.
600       EM_PotentialConstantExpression,
601 
602       /// Fold the expression to a constant. Stop if we hit a side-effect that
603       /// we can't model.
604       EM_ConstantFold,
605 
606       /// Evaluate the expression looking for integer overflow and similar
607       /// issues. Don't worry about side-effects, and try to visit all
608       /// subexpressions.
609       EM_EvaluateForOverflow,
610 
611       /// Evaluate in any way we know how. Don't worry about side-effects that
612       /// can't be modeled.
613       EM_IgnoreSideEffects,
614 
615       /// Evaluate as a constant expression. Stop if we find that the expression
616       /// is not a constant expression. Some expressions can be retried in the
617       /// optimizer if we don't constant fold them here, but in an unevaluated
618       /// context we try to fold them immediately since the optimizer never
619       /// gets a chance to look at it.
620       EM_ConstantExpressionUnevaluated,
621 
622       /// Evaluate as a potential constant expression. Keep going if we hit a
623       /// construct that we can't evaluate yet (because we don't yet know the
624       /// value of something) but stop if we hit something that could never be
625       /// a constant expression. Some expressions can be retried in the
626       /// optimizer if we don't constant fold them here, but in an unevaluated
627       /// context we try to fold them immediately since the optimizer never
628       /// gets a chance to look at it.
629       EM_PotentialConstantExpressionUnevaluated,
630 
631       /// Evaluate as a constant expression. In certain scenarios, if:
632       /// - we find a MemberExpr with a base that can't be evaluated, or
633       /// - we find a variable initialized with a call to a function that has
634       ///   the alloc_size attribute on it
635       /// then we may consider evaluation to have succeeded.
636       ///
637       /// In either case, the LValue returned shall have an invalid base; in the
638       /// former, the base will be the invalid MemberExpr, in the latter, the
639       /// base will be either the alloc_size CallExpr or a CastExpr wrapping
640       /// said CallExpr.
641       EM_OffsetFold,
642     } EvalMode;
643 
644     /// Are we checking whether the expression is a potential constant
645     /// expression?
646     bool checkingPotentialConstantExpression() const {
647       return EvalMode == EM_PotentialConstantExpression ||
648              EvalMode == EM_PotentialConstantExpressionUnevaluated;
649     }
650 
651     /// Are we checking an expression for overflow?
652     // FIXME: We should check for any kind of undefined or suspicious behavior
653     // in such constructs, not just overflow.
654     bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
655 
656     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
657       : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
658         CallStackDepth(0), NextCallIndex(1),
659         StepsLeft(getLangOpts().ConstexprStepLimit),
660         BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
661         EvaluatingDecl((const ValueDecl *)nullptr),
662         EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
663         HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
664         EvalMode(Mode) {}
665 
666     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
667       EvaluatingDecl = Base;
668       EvaluatingDeclValue = &Value;
669     }
670 
671     const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
672 
673     bool CheckCallLimit(SourceLocation Loc) {
674       // Don't perform any constexpr calls (other than the call we're checking)
675       // when checking a potential constant expression.
676       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
677         return false;
678       if (NextCallIndex == 0) {
679         // NextCallIndex has wrapped around.
680         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
681         return false;
682       }
683       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
684         return true;
685       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
686         << getLangOpts().ConstexprCallDepth;
687       return false;
688     }
689 
690     CallStackFrame *getCallFrame(unsigned CallIndex) {
691       assert(CallIndex && "no call index in getCallFrame");
692       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
693       // be null in this loop.
694       CallStackFrame *Frame = CurrentCall;
695       while (Frame->Index > CallIndex)
696         Frame = Frame->Caller;
697       return (Frame->Index == CallIndex) ? Frame : nullptr;
698     }
699 
700     bool nextStep(const Stmt *S) {
701       if (!StepsLeft) {
702         FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
703         return false;
704       }
705       --StepsLeft;
706       return true;
707     }
708 
709   private:
710     /// Add a diagnostic to the diagnostics list.
711     PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
712       PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
713       EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
714       return EvalStatus.Diag->back().second;
715     }
716 
717     /// Add notes containing a call stack to the current point of evaluation.
718     void addCallStack(unsigned Limit);
719 
720   private:
721     OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
722                             unsigned ExtraNotes, bool IsCCEDiag) {
723 
724       if (EvalStatus.Diag) {
725         // If we have a prior diagnostic, it will be noting that the expression
726         // isn't a constant expression. This diagnostic is more important,
727         // unless we require this evaluation to produce a constant expression.
728         //
729         // FIXME: We might want to show both diagnostics to the user in
730         // EM_ConstantFold mode.
731         if (!EvalStatus.Diag->empty()) {
732           switch (EvalMode) {
733           case EM_ConstantFold:
734           case EM_IgnoreSideEffects:
735           case EM_EvaluateForOverflow:
736             if (!HasFoldFailureDiagnostic)
737               break;
738             // We've already failed to fold something. Keep that diagnostic.
739             LLVM_FALLTHROUGH;
740           case EM_ConstantExpression:
741           case EM_PotentialConstantExpression:
742           case EM_ConstantExpressionUnevaluated:
743           case EM_PotentialConstantExpressionUnevaluated:
744           case EM_OffsetFold:
745             HasActiveDiagnostic = false;
746             return OptionalDiagnostic();
747           }
748         }
749 
750         unsigned CallStackNotes = CallStackDepth - 1;
751         unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
752         if (Limit)
753           CallStackNotes = std::min(CallStackNotes, Limit + 1);
754         if (checkingPotentialConstantExpression())
755           CallStackNotes = 0;
756 
757         HasActiveDiagnostic = true;
758         HasFoldFailureDiagnostic = !IsCCEDiag;
759         EvalStatus.Diag->clear();
760         EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
761         addDiag(Loc, DiagId);
762         if (!checkingPotentialConstantExpression())
763           addCallStack(Limit);
764         return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
765       }
766       HasActiveDiagnostic = false;
767       return OptionalDiagnostic();
768     }
769   public:
770     // Diagnose that the evaluation could not be folded (FF => FoldFailure)
771     OptionalDiagnostic
772     FFDiag(SourceLocation Loc,
773           diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
774           unsigned ExtraNotes = 0) {
775       return Diag(Loc, DiagId, ExtraNotes, false);
776     }
777 
778     OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
779                               = diag::note_invalid_subexpr_in_const_expr,
780                             unsigned ExtraNotes = 0) {
781       if (EvalStatus.Diag)
782         return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
783       HasActiveDiagnostic = false;
784       return OptionalDiagnostic();
785     }
786 
787     /// Diagnose that the evaluation does not produce a C++11 core constant
788     /// expression.
789     ///
790     /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
791     /// EM_PotentialConstantExpression mode and we produce one of these.
792     OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
793                                  = diag::note_invalid_subexpr_in_const_expr,
794                                unsigned ExtraNotes = 0) {
795       // Don't override a previous diagnostic. Don't bother collecting
796       // diagnostics if we're evaluating for overflow.
797       if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
798         HasActiveDiagnostic = false;
799         return OptionalDiagnostic();
800       }
801       return Diag(Loc, DiagId, ExtraNotes, true);
802     }
803     OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
804                                  = diag::note_invalid_subexpr_in_const_expr,
805                                unsigned ExtraNotes = 0) {
806       return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
807     }
808     /// Add a note to a prior diagnostic.
809     OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
810       if (!HasActiveDiagnostic)
811         return OptionalDiagnostic();
812       return OptionalDiagnostic(&addDiag(Loc, DiagId));
813     }
814 
815     /// Add a stack of notes to a prior diagnostic.
816     void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
817       if (HasActiveDiagnostic) {
818         EvalStatus.Diag->insert(EvalStatus.Diag->end(),
819                                 Diags.begin(), Diags.end());
820       }
821     }
822 
823     /// Should we continue evaluation after encountering a side-effect that we
824     /// couldn't model?
825     bool keepEvaluatingAfterSideEffect() {
826       switch (EvalMode) {
827       case EM_PotentialConstantExpression:
828       case EM_PotentialConstantExpressionUnevaluated:
829       case EM_EvaluateForOverflow:
830       case EM_IgnoreSideEffects:
831         return true;
832 
833       case EM_ConstantExpression:
834       case EM_ConstantExpressionUnevaluated:
835       case EM_ConstantFold:
836       case EM_OffsetFold:
837         return false;
838       }
839       llvm_unreachable("Missed EvalMode case");
840     }
841 
842     /// Note that we have had a side-effect, and determine whether we should
843     /// keep evaluating.
844     bool noteSideEffect() {
845       EvalStatus.HasSideEffects = true;
846       return keepEvaluatingAfterSideEffect();
847     }
848 
849     /// Should we continue evaluation after encountering undefined behavior?
850     bool keepEvaluatingAfterUndefinedBehavior() {
851       switch (EvalMode) {
852       case EM_EvaluateForOverflow:
853       case EM_IgnoreSideEffects:
854       case EM_ConstantFold:
855       case EM_OffsetFold:
856         return true;
857 
858       case EM_PotentialConstantExpression:
859       case EM_PotentialConstantExpressionUnevaluated:
860       case EM_ConstantExpression:
861       case EM_ConstantExpressionUnevaluated:
862         return false;
863       }
864       llvm_unreachable("Missed EvalMode case");
865     }
866 
867     /// Note that we hit something that was technically undefined behavior, but
868     /// that we can evaluate past it (such as signed overflow or floating-point
869     /// division by zero.)
870     bool noteUndefinedBehavior() {
871       EvalStatus.HasUndefinedBehavior = true;
872       return keepEvaluatingAfterUndefinedBehavior();
873     }
874 
875     /// Should we continue evaluation as much as possible after encountering a
876     /// construct which can't be reduced to a value?
877     bool keepEvaluatingAfterFailure() {
878       if (!StepsLeft)
879         return false;
880 
881       switch (EvalMode) {
882       case EM_PotentialConstantExpression:
883       case EM_PotentialConstantExpressionUnevaluated:
884       case EM_EvaluateForOverflow:
885         return true;
886 
887       case EM_ConstantExpression:
888       case EM_ConstantExpressionUnevaluated:
889       case EM_ConstantFold:
890       case EM_IgnoreSideEffects:
891       case EM_OffsetFold:
892         return false;
893       }
894       llvm_unreachable("Missed EvalMode case");
895     }
896 
897     /// Notes that we failed to evaluate an expression that other expressions
898     /// directly depend on, and determine if we should keep evaluating. This
899     /// should only be called if we actually intend to keep evaluating.
900     ///
901     /// Call noteSideEffect() instead if we may be able to ignore the value that
902     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
903     ///
904     /// (Foo(), 1)      // use noteSideEffect
905     /// (Foo() || true) // use noteSideEffect
906     /// Foo() + 1       // use noteFailure
907     LLVM_NODISCARD bool noteFailure() {
908       // Failure when evaluating some expression often means there is some
909       // subexpression whose evaluation was skipped. Therefore, (because we
910       // don't track whether we skipped an expression when unwinding after an
911       // evaluation failure) every evaluation failure that bubbles up from a
912       // subexpression implies that a side-effect has potentially happened. We
913       // skip setting the HasSideEffects flag to true until we decide to
914       // continue evaluating after that point, which happens here.
915       bool KeepGoing = keepEvaluatingAfterFailure();
916       EvalStatus.HasSideEffects |= KeepGoing;
917       return KeepGoing;
918     }
919 
920     class ArrayInitLoopIndex {
921       EvalInfo &Info;
922       uint64_t OuterIndex;
923 
924     public:
925       ArrayInitLoopIndex(EvalInfo &Info)
926           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
927         Info.ArrayInitIndex = 0;
928       }
929       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
930 
931       operator uint64_t&() { return Info.ArrayInitIndex; }
932     };
933   };
934 
935   /// Object used to treat all foldable expressions as constant expressions.
936   struct FoldConstant {
937     EvalInfo &Info;
938     bool Enabled;
939     bool HadNoPriorDiags;
940     EvalInfo::EvaluationMode OldMode;
941 
942     explicit FoldConstant(EvalInfo &Info, bool Enabled)
943       : Info(Info),
944         Enabled(Enabled),
945         HadNoPriorDiags(Info.EvalStatus.Diag &&
946                         Info.EvalStatus.Diag->empty() &&
947                         !Info.EvalStatus.HasSideEffects),
948         OldMode(Info.EvalMode) {
949       if (Enabled &&
950           (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
951            Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
952         Info.EvalMode = EvalInfo::EM_ConstantFold;
953     }
954     void keepDiagnostics() { Enabled = false; }
955     ~FoldConstant() {
956       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
957           !Info.EvalStatus.HasSideEffects)
958         Info.EvalStatus.Diag->clear();
959       Info.EvalMode = OldMode;
960     }
961   };
962 
963   /// RAII object used to treat the current evaluation as the correct pointer
964   /// offset fold for the current EvalMode
965   struct FoldOffsetRAII {
966     EvalInfo &Info;
967     EvalInfo::EvaluationMode OldMode;
968     explicit FoldOffsetRAII(EvalInfo &Info)
969         : Info(Info), OldMode(Info.EvalMode) {
970       if (!Info.checkingPotentialConstantExpression())
971         Info.EvalMode = EvalInfo::EM_OffsetFold;
972     }
973 
974     ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
975   };
976 
977   /// RAII object used to optionally suppress diagnostics and side-effects from
978   /// a speculative evaluation.
979   class SpeculativeEvaluationRAII {
980     EvalInfo *Info = nullptr;
981     Expr::EvalStatus OldStatus;
982     bool OldIsSpeculativelyEvaluating;
983 
984     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
985       Info = Other.Info;
986       OldStatus = Other.OldStatus;
987       OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
988       Other.Info = nullptr;
989     }
990 
991     void maybeRestoreState() {
992       if (!Info)
993         return;
994 
995       Info->EvalStatus = OldStatus;
996       Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
997     }
998 
999   public:
1000     SpeculativeEvaluationRAII() = default;
1001 
1002     SpeculativeEvaluationRAII(
1003         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1004         : Info(&Info), OldStatus(Info.EvalStatus),
1005           OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
1006       Info.EvalStatus.Diag = NewDiag;
1007       Info.IsSpeculativelyEvaluating = true;
1008     }
1009 
1010     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1011     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1012       moveFromAndCancel(std::move(Other));
1013     }
1014 
1015     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1016       maybeRestoreState();
1017       moveFromAndCancel(std::move(Other));
1018       return *this;
1019     }
1020 
1021     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1022   };
1023 
1024   /// RAII object wrapping a full-expression or block scope, and handling
1025   /// the ending of the lifetime of temporaries created within it.
1026   template<bool IsFullExpression>
1027   class ScopeRAII {
1028     EvalInfo &Info;
1029     unsigned OldStackSize;
1030   public:
1031     ScopeRAII(EvalInfo &Info)
1032         : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1033     ~ScopeRAII() {
1034       // Body moved to a static method to encourage the compiler to inline away
1035       // instances of this class.
1036       cleanup(Info, OldStackSize);
1037     }
1038   private:
1039     static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1040       unsigned NewEnd = OldStackSize;
1041       for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1042            I != N; ++I) {
1043         if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1044           // Full-expression cleanup of a lifetime-extended temporary: nothing
1045           // to do, just move this cleanup to the right place in the stack.
1046           std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1047           ++NewEnd;
1048         } else {
1049           // End the lifetime of the object.
1050           Info.CleanupStack[I].endLifetime();
1051         }
1052       }
1053       Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1054                               Info.CleanupStack.end());
1055     }
1056   };
1057   typedef ScopeRAII<false> BlockScopeRAII;
1058   typedef ScopeRAII<true> FullExpressionRAII;
1059 }
1060 
1061 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1062                                          CheckSubobjectKind CSK) {
1063   if (Invalid)
1064     return false;
1065   if (isOnePastTheEnd()) {
1066     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1067       << CSK;
1068     setInvalid();
1069     return false;
1070   }
1071   return true;
1072 }
1073 
1074 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1075                                                     const Expr *E,
1076                                                     const APSInt &N) {
1077   // If we're complaining, we must be able to statically determine the size of
1078   // the most derived array.
1079   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1080     Info.CCEDiag(E, diag::note_constexpr_array_index)
1081       << N << /*array*/ 0
1082       << static_cast<unsigned>(getMostDerivedArraySize());
1083   else
1084     Info.CCEDiag(E, diag::note_constexpr_array_index)
1085       << N << /*non-array*/ 1;
1086   setInvalid();
1087 }
1088 
1089 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1090                                const FunctionDecl *Callee, const LValue *This,
1091                                APValue *Arguments)
1092     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1093       Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1094   Info.CurrentCall = this;
1095   ++Info.CallStackDepth;
1096 }
1097 
1098 CallStackFrame::~CallStackFrame() {
1099   assert(Info.CurrentCall == this && "calls retired out of order");
1100   --Info.CallStackDepth;
1101   Info.CurrentCall = Caller;
1102 }
1103 
1104 APValue &CallStackFrame::createTemporary(const void *Key,
1105                                          bool IsLifetimeExtended) {
1106   APValue &Result = Temporaries[Key];
1107   assert(Result.isUninit() && "temporary created multiple times");
1108   Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1109   return Result;
1110 }
1111 
1112 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
1113 
1114 void EvalInfo::addCallStack(unsigned Limit) {
1115   // Determine which calls to skip, if any.
1116   unsigned ActiveCalls = CallStackDepth - 1;
1117   unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1118   if (Limit && Limit < ActiveCalls) {
1119     SkipStart = Limit / 2 + Limit % 2;
1120     SkipEnd = ActiveCalls - Limit / 2;
1121   }
1122 
1123   // Walk the call stack and add the diagnostics.
1124   unsigned CallIdx = 0;
1125   for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1126        Frame = Frame->Caller, ++CallIdx) {
1127     // Skip this call?
1128     if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1129       if (CallIdx == SkipStart) {
1130         // Note that we're skipping calls.
1131         addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1132           << unsigned(ActiveCalls - Limit);
1133       }
1134       continue;
1135     }
1136 
1137     // Use a different note for an inheriting constructor, because from the
1138     // user's perspective it's not really a function at all.
1139     if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1140       if (CD->isInheritingConstructor()) {
1141         addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1142           << CD->getParent();
1143         continue;
1144       }
1145     }
1146 
1147     SmallVector<char, 128> Buffer;
1148     llvm::raw_svector_ostream Out(Buffer);
1149     describeCall(Frame, Out);
1150     addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1151   }
1152 }
1153 
1154 namespace {
1155   struct ComplexValue {
1156   private:
1157     bool IsInt;
1158 
1159   public:
1160     APSInt IntReal, IntImag;
1161     APFloat FloatReal, FloatImag;
1162 
1163     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1164 
1165     void makeComplexFloat() { IsInt = false; }
1166     bool isComplexFloat() const { return !IsInt; }
1167     APFloat &getComplexFloatReal() { return FloatReal; }
1168     APFloat &getComplexFloatImag() { return FloatImag; }
1169 
1170     void makeComplexInt() { IsInt = true; }
1171     bool isComplexInt() const { return IsInt; }
1172     APSInt &getComplexIntReal() { return IntReal; }
1173     APSInt &getComplexIntImag() { return IntImag; }
1174 
1175     void moveInto(APValue &v) const {
1176       if (isComplexFloat())
1177         v = APValue(FloatReal, FloatImag);
1178       else
1179         v = APValue(IntReal, IntImag);
1180     }
1181     void setFrom(const APValue &v) {
1182       assert(v.isComplexFloat() || v.isComplexInt());
1183       if (v.isComplexFloat()) {
1184         makeComplexFloat();
1185         FloatReal = v.getComplexFloatReal();
1186         FloatImag = v.getComplexFloatImag();
1187       } else {
1188         makeComplexInt();
1189         IntReal = v.getComplexIntReal();
1190         IntImag = v.getComplexIntImag();
1191       }
1192     }
1193   };
1194 
1195   struct LValue {
1196     APValue::LValueBase Base;
1197     CharUnits Offset;
1198     unsigned InvalidBase : 1;
1199     unsigned CallIndex : 31;
1200     SubobjectDesignator Designator;
1201     bool IsNullPtr;
1202 
1203     const APValue::LValueBase getLValueBase() const { return Base; }
1204     CharUnits &getLValueOffset() { return Offset; }
1205     const CharUnits &getLValueOffset() const { return Offset; }
1206     unsigned getLValueCallIndex() const { return CallIndex; }
1207     SubobjectDesignator &getLValueDesignator() { return Designator; }
1208     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1209     bool isNullPointer() const { return IsNullPtr;}
1210 
1211     void moveInto(APValue &V) const {
1212       if (Designator.Invalid)
1213         V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1214                     IsNullPtr);
1215       else {
1216         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1217         assert(!Designator.FirstEntryIsAnUnsizedArray &&
1218                "Unsized array with a valid base?");
1219         V = APValue(Base, Offset, Designator.Entries,
1220                     Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
1221       }
1222     }
1223     void setFrom(ASTContext &Ctx, const APValue &V) {
1224       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1225       Base = V.getLValueBase();
1226       Offset = V.getLValueOffset();
1227       InvalidBase = false;
1228       CallIndex = V.getLValueCallIndex();
1229       Designator = SubobjectDesignator(Ctx, V);
1230       IsNullPtr = V.isNullPointer();
1231     }
1232 
1233     void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
1234 #ifndef NDEBUG
1235       // We only allow a few types of invalid bases. Enforce that here.
1236       if (BInvalid) {
1237         const auto *E = B.get<const Expr *>();
1238         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1239                "Unexpected type of invalid base");
1240       }
1241 #endif
1242 
1243       Base = B;
1244       Offset = CharUnits::fromQuantity(0);
1245       InvalidBase = BInvalid;
1246       CallIndex = I;
1247       Designator = SubobjectDesignator(getType(B));
1248       IsNullPtr = false;
1249     }
1250 
1251     void setNull(QualType PointerTy, uint64_t TargetVal) {
1252       Base = (Expr *)nullptr;
1253       Offset = CharUnits::fromQuantity(TargetVal);
1254       InvalidBase = false;
1255       CallIndex = 0;
1256       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1257       IsNullPtr = true;
1258     }
1259 
1260     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1261       set(B, I, true);
1262     }
1263 
1264     // Check that this LValue is not based on a null pointer. If it is, produce
1265     // a diagnostic and mark the designator as invalid.
1266     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1267                           CheckSubobjectKind CSK) {
1268       if (Designator.Invalid)
1269         return false;
1270       if (IsNullPtr) {
1271         Info.CCEDiag(E, diag::note_constexpr_null_subobject)
1272           << CSK;
1273         Designator.setInvalid();
1274         return false;
1275       }
1276       return true;
1277     }
1278 
1279     // Check this LValue refers to an object. If not, set the designator to be
1280     // invalid and emit a diagnostic.
1281     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1282       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1283              Designator.checkSubobject(Info, E, CSK);
1284     }
1285 
1286     void addDecl(EvalInfo &Info, const Expr *E,
1287                  const Decl *D, bool Virtual = false) {
1288       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1289         Designator.addDeclUnchecked(D, Virtual);
1290     }
1291     void addUnsizedArray(EvalInfo &Info, QualType ElemTy) {
1292       assert(Designator.Entries.empty() && getType(Base)->isPointerType());
1293       assert(isBaseAnAllocSizeCall(Base) &&
1294              "Only alloc_size bases can have unsized arrays");
1295       Designator.FirstEntryIsAnUnsizedArray = true;
1296       Designator.addUnsizedArrayUnchecked(ElemTy);
1297     }
1298     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1299       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1300         Designator.addArrayUnchecked(CAT);
1301     }
1302     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1303       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1304         Designator.addComplexUnchecked(EltTy, Imag);
1305     }
1306     void clearIsNullPointer() {
1307       IsNullPtr = false;
1308     }
1309     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1310                               const APSInt &Index, CharUnits ElementSize) {
1311       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1312       // but we're not required to diagnose it and it's valid in C++.)
1313       if (!Index)
1314         return;
1315 
1316       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1317       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1318       // offsets.
1319       uint64_t Offset64 = Offset.getQuantity();
1320       uint64_t ElemSize64 = ElementSize.getQuantity();
1321       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1322       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1323 
1324       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1325         Designator.adjustIndex(Info, E, Index);
1326       clearIsNullPointer();
1327     }
1328     void adjustOffset(CharUnits N) {
1329       Offset += N;
1330       if (N.getQuantity())
1331         clearIsNullPointer();
1332     }
1333   };
1334 
1335   struct MemberPtr {
1336     MemberPtr() {}
1337     explicit MemberPtr(const ValueDecl *Decl) :
1338       DeclAndIsDerivedMember(Decl, false), Path() {}
1339 
1340     /// The member or (direct or indirect) field referred to by this member
1341     /// pointer, or 0 if this is a null member pointer.
1342     const ValueDecl *getDecl() const {
1343       return DeclAndIsDerivedMember.getPointer();
1344     }
1345     /// Is this actually a member of some type derived from the relevant class?
1346     bool isDerivedMember() const {
1347       return DeclAndIsDerivedMember.getInt();
1348     }
1349     /// Get the class which the declaration actually lives in.
1350     const CXXRecordDecl *getContainingRecord() const {
1351       return cast<CXXRecordDecl>(
1352           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1353     }
1354 
1355     void moveInto(APValue &V) const {
1356       V = APValue(getDecl(), isDerivedMember(), Path);
1357     }
1358     void setFrom(const APValue &V) {
1359       assert(V.isMemberPointer());
1360       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1361       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1362       Path.clear();
1363       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1364       Path.insert(Path.end(), P.begin(), P.end());
1365     }
1366 
1367     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1368     /// whether the member is a member of some class derived from the class type
1369     /// of the member pointer.
1370     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1371     /// Path - The path of base/derived classes from the member declaration's
1372     /// class (exclusive) to the class type of the member pointer (inclusive).
1373     SmallVector<const CXXRecordDecl*, 4> Path;
1374 
1375     /// Perform a cast towards the class of the Decl (either up or down the
1376     /// hierarchy).
1377     bool castBack(const CXXRecordDecl *Class) {
1378       assert(!Path.empty());
1379       const CXXRecordDecl *Expected;
1380       if (Path.size() >= 2)
1381         Expected = Path[Path.size() - 2];
1382       else
1383         Expected = getContainingRecord();
1384       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1385         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1386         // if B does not contain the original member and is not a base or
1387         // derived class of the class containing the original member, the result
1388         // of the cast is undefined.
1389         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1390         // (D::*). We consider that to be a language defect.
1391         return false;
1392       }
1393       Path.pop_back();
1394       return true;
1395     }
1396     /// Perform a base-to-derived member pointer cast.
1397     bool castToDerived(const CXXRecordDecl *Derived) {
1398       if (!getDecl())
1399         return true;
1400       if (!isDerivedMember()) {
1401         Path.push_back(Derived);
1402         return true;
1403       }
1404       if (!castBack(Derived))
1405         return false;
1406       if (Path.empty())
1407         DeclAndIsDerivedMember.setInt(false);
1408       return true;
1409     }
1410     /// Perform a derived-to-base member pointer cast.
1411     bool castToBase(const CXXRecordDecl *Base) {
1412       if (!getDecl())
1413         return true;
1414       if (Path.empty())
1415         DeclAndIsDerivedMember.setInt(true);
1416       if (isDerivedMember()) {
1417         Path.push_back(Base);
1418         return true;
1419       }
1420       return castBack(Base);
1421     }
1422   };
1423 
1424   /// Compare two member pointers, which are assumed to be of the same type.
1425   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1426     if (!LHS.getDecl() || !RHS.getDecl())
1427       return !LHS.getDecl() && !RHS.getDecl();
1428     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1429       return false;
1430     return LHS.Path == RHS.Path;
1431   }
1432 }
1433 
1434 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1435 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1436                             const LValue &This, const Expr *E,
1437                             bool AllowNonLiteralTypes = false);
1438 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1439                            bool InvalidBaseOK = false);
1440 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1441                             bool InvalidBaseOK = false);
1442 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1443                                   EvalInfo &Info);
1444 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1445 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1446 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1447                                     EvalInfo &Info);
1448 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1449 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1450 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1451                            EvalInfo &Info);
1452 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1453 
1454 //===----------------------------------------------------------------------===//
1455 // Misc utilities
1456 //===----------------------------------------------------------------------===//
1457 
1458 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1459 /// preserving its value (by extending by up to one bit as needed).
1460 static void negateAsSigned(APSInt &Int) {
1461   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1462     Int = Int.extend(Int.getBitWidth() + 1);
1463     Int.setIsSigned(true);
1464   }
1465   Int = -Int;
1466 }
1467 
1468 /// Produce a string describing the given constexpr call.
1469 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1470   unsigned ArgIndex = 0;
1471   bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1472                       !isa<CXXConstructorDecl>(Frame->Callee) &&
1473                       cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1474 
1475   if (!IsMemberCall)
1476     Out << *Frame->Callee << '(';
1477 
1478   if (Frame->This && IsMemberCall) {
1479     APValue Val;
1480     Frame->This->moveInto(Val);
1481     Val.printPretty(Out, Frame->Info.Ctx,
1482                     Frame->This->Designator.MostDerivedType);
1483     // FIXME: Add parens around Val if needed.
1484     Out << "->" << *Frame->Callee << '(';
1485     IsMemberCall = false;
1486   }
1487 
1488   for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1489        E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1490     if (ArgIndex > (unsigned)IsMemberCall)
1491       Out << ", ";
1492 
1493     const ParmVarDecl *Param = *I;
1494     const APValue &Arg = Frame->Arguments[ArgIndex];
1495     Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1496 
1497     if (ArgIndex == 0 && IsMemberCall)
1498       Out << "->" << *Frame->Callee << '(';
1499   }
1500 
1501   Out << ')';
1502 }
1503 
1504 /// Evaluate an expression to see if it had side-effects, and discard its
1505 /// result.
1506 /// \return \c true if the caller should keep evaluating.
1507 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1508   APValue Scratch;
1509   if (!Evaluate(Scratch, Info, E))
1510     // We don't need the value, but we might have skipped a side effect here.
1511     return Info.noteSideEffect();
1512   return true;
1513 }
1514 
1515 /// Should this call expression be treated as a string literal?
1516 static bool IsStringLiteralCall(const CallExpr *E) {
1517   unsigned Builtin = E->getBuiltinCallee();
1518   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1519           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1520 }
1521 
1522 static bool IsGlobalLValue(APValue::LValueBase B) {
1523   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1524   // constant expression of pointer type that evaluates to...
1525 
1526   // ... a null pointer value, or a prvalue core constant expression of type
1527   // std::nullptr_t.
1528   if (!B) return true;
1529 
1530   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1531     // ... the address of an object with static storage duration,
1532     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1533       return VD->hasGlobalStorage();
1534     // ... the address of a function,
1535     return isa<FunctionDecl>(D);
1536   }
1537 
1538   const Expr *E = B.get<const Expr*>();
1539   switch (E->getStmtClass()) {
1540   default:
1541     return false;
1542   case Expr::CompoundLiteralExprClass: {
1543     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1544     return CLE->isFileScope() && CLE->isLValue();
1545   }
1546   case Expr::MaterializeTemporaryExprClass:
1547     // A materialized temporary might have been lifetime-extended to static
1548     // storage duration.
1549     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1550   // A string literal has static storage duration.
1551   case Expr::StringLiteralClass:
1552   case Expr::PredefinedExprClass:
1553   case Expr::ObjCStringLiteralClass:
1554   case Expr::ObjCEncodeExprClass:
1555   case Expr::CXXTypeidExprClass:
1556   case Expr::CXXUuidofExprClass:
1557     return true;
1558   case Expr::CallExprClass:
1559     return IsStringLiteralCall(cast<CallExpr>(E));
1560   // For GCC compatibility, &&label has static storage duration.
1561   case Expr::AddrLabelExprClass:
1562     return true;
1563   // A Block literal expression may be used as the initialization value for
1564   // Block variables at global or local static scope.
1565   case Expr::BlockExprClass:
1566     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1567   case Expr::ImplicitValueInitExprClass:
1568     // FIXME:
1569     // We can never form an lvalue with an implicit value initialization as its
1570     // base through expression evaluation, so these only appear in one case: the
1571     // implicit variable declaration we invent when checking whether a constexpr
1572     // constructor can produce a constant expression. We must assume that such
1573     // an expression might be a global lvalue.
1574     return true;
1575   }
1576 }
1577 
1578 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1579   assert(Base && "no location for a null lvalue");
1580   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1581   if (VD)
1582     Info.Note(VD->getLocation(), diag::note_declared_at);
1583   else
1584     Info.Note(Base.get<const Expr*>()->getExprLoc(),
1585               diag::note_constexpr_temporary_here);
1586 }
1587 
1588 /// Check that this reference or pointer core constant expression is a valid
1589 /// value for an address or reference constant expression. Return true if we
1590 /// can fold this expression, whether or not it's a constant expression.
1591 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1592                                           QualType Type, const LValue &LVal) {
1593   bool IsReferenceType = Type->isReferenceType();
1594 
1595   APValue::LValueBase Base = LVal.getLValueBase();
1596   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1597 
1598   // Check that the object is a global. Note that the fake 'this' object we
1599   // manufacture when checking potential constant expressions is conservatively
1600   // assumed to be global here.
1601   if (!IsGlobalLValue(Base)) {
1602     if (Info.getLangOpts().CPlusPlus11) {
1603       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1604       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
1605         << IsReferenceType << !Designator.Entries.empty()
1606         << !!VD << VD;
1607       NoteLValueLocation(Info, Base);
1608     } else {
1609       Info.FFDiag(Loc);
1610     }
1611     // Don't allow references to temporaries to escape.
1612     return false;
1613   }
1614   assert((Info.checkingPotentialConstantExpression() ||
1615           LVal.getLValueCallIndex() == 0) &&
1616          "have call index for global lvalue");
1617 
1618   if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1619     if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1620       // Check if this is a thread-local variable.
1621       if (Var->getTLSKind())
1622         return false;
1623 
1624       // A dllimport variable never acts like a constant.
1625       if (Var->hasAttr<DLLImportAttr>())
1626         return false;
1627     }
1628     if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1629       // __declspec(dllimport) must be handled very carefully:
1630       // We must never initialize an expression with the thunk in C++.
1631       // Doing otherwise would allow the same id-expression to yield
1632       // different addresses for the same function in different translation
1633       // units.  However, this means that we must dynamically initialize the
1634       // expression with the contents of the import address table at runtime.
1635       //
1636       // The C language has no notion of ODR; furthermore, it has no notion of
1637       // dynamic initialization.  This means that we are permitted to
1638       // perform initialization with the address of the thunk.
1639       if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
1640         return false;
1641     }
1642   }
1643 
1644   // Allow address constant expressions to be past-the-end pointers. This is
1645   // an extension: the standard requires them to point to an object.
1646   if (!IsReferenceType)
1647     return true;
1648 
1649   // A reference constant expression must refer to an object.
1650   if (!Base) {
1651     // FIXME: diagnostic
1652     Info.CCEDiag(Loc);
1653     return true;
1654   }
1655 
1656   // Does this refer one past the end of some object?
1657   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1658     const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1659     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
1660       << !Designator.Entries.empty() << !!VD << VD;
1661     NoteLValueLocation(Info, Base);
1662   }
1663 
1664   return true;
1665 }
1666 
1667 /// Member pointers are constant expressions unless they point to a
1668 /// non-virtual dllimport member function.
1669 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1670                                                  SourceLocation Loc,
1671                                                  QualType Type,
1672                                                  const APValue &Value) {
1673   const ValueDecl *Member = Value.getMemberPointerDecl();
1674   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1675   if (!FD)
1676     return true;
1677   return FD->isVirtual() || !FD->hasAttr<DLLImportAttr>();
1678 }
1679 
1680 /// Check that this core constant expression is of literal type, and if not,
1681 /// produce an appropriate diagnostic.
1682 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1683                              const LValue *This = nullptr) {
1684   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1685     return true;
1686 
1687   // C++1y: A constant initializer for an object o [...] may also invoke
1688   // constexpr constructors for o and its subobjects even if those objects
1689   // are of non-literal class types.
1690   //
1691   // C++11 missed this detail for aggregates, so classes like this:
1692   //   struct foo_t { union { int i; volatile int j; } u; };
1693   // are not (obviously) initializable like so:
1694   //   __attribute__((__require_constant_initialization__))
1695   //   static const foo_t x = {{0}};
1696   // because "i" is a subobject with non-literal initialization (due to the
1697   // volatile member of the union). See:
1698   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1699   // Therefore, we use the C++1y behavior.
1700   if (This && Info.EvaluatingDecl == This->getLValueBase())
1701     return true;
1702 
1703   // Prvalue constant expressions must be of literal types.
1704   if (Info.getLangOpts().CPlusPlus11)
1705     Info.FFDiag(E, diag::note_constexpr_nonliteral)
1706       << E->getType();
1707   else
1708     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1709   return false;
1710 }
1711 
1712 /// Check that this core constant expression value is a valid value for a
1713 /// constant expression. If not, report an appropriate diagnostic. Does not
1714 /// check that the expression is of literal type.
1715 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1716                                     QualType Type, const APValue &Value) {
1717   if (Value.isUninit()) {
1718     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
1719       << true << Type;
1720     return false;
1721   }
1722 
1723   // We allow _Atomic(T) to be initialized from anything that T can be
1724   // initialized from.
1725   if (const AtomicType *AT = Type->getAs<AtomicType>())
1726     Type = AT->getValueType();
1727 
1728   // Core issue 1454: For a literal constant expression of array or class type,
1729   // each subobject of its value shall have been initialized by a constant
1730   // expression.
1731   if (Value.isArray()) {
1732     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1733     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1734       if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1735                                    Value.getArrayInitializedElt(I)))
1736         return false;
1737     }
1738     if (!Value.hasArrayFiller())
1739       return true;
1740     return CheckConstantExpression(Info, DiagLoc, EltTy,
1741                                    Value.getArrayFiller());
1742   }
1743   if (Value.isUnion() && Value.getUnionField()) {
1744     return CheckConstantExpression(Info, DiagLoc,
1745                                    Value.getUnionField()->getType(),
1746                                    Value.getUnionValue());
1747   }
1748   if (Value.isStruct()) {
1749     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1750     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1751       unsigned BaseIndex = 0;
1752       for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1753              End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1754         if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1755                                      Value.getStructBase(BaseIndex)))
1756           return false;
1757       }
1758     }
1759     for (const auto *I : RD->fields()) {
1760       if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1761                                    Value.getStructField(I->getFieldIndex())))
1762         return false;
1763     }
1764   }
1765 
1766   if (Value.isLValue()) {
1767     LValue LVal;
1768     LVal.setFrom(Info.Ctx, Value);
1769     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1770   }
1771 
1772   if (Value.isMemberPointer())
1773     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value);
1774 
1775   // Everything else is fine.
1776   return true;
1777 }
1778 
1779 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1780   return LVal.Base.dyn_cast<const ValueDecl*>();
1781 }
1782 
1783 static bool IsLiteralLValue(const LValue &Value) {
1784   if (Value.CallIndex)
1785     return false;
1786   const Expr *E = Value.Base.dyn_cast<const Expr*>();
1787   return E && !isa<MaterializeTemporaryExpr>(E);
1788 }
1789 
1790 static bool IsWeakLValue(const LValue &Value) {
1791   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1792   return Decl && Decl->isWeak();
1793 }
1794 
1795 static bool isZeroSized(const LValue &Value) {
1796   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1797   if (Decl && isa<VarDecl>(Decl)) {
1798     QualType Ty = Decl->getType();
1799     if (Ty->isArrayType())
1800       return Ty->isIncompleteType() ||
1801              Decl->getASTContext().getTypeSize(Ty) == 0;
1802   }
1803   return false;
1804 }
1805 
1806 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1807   // A null base expression indicates a null pointer.  These are always
1808   // evaluatable, and they are false unless the offset is zero.
1809   if (!Value.getLValueBase()) {
1810     Result = !Value.getLValueOffset().isZero();
1811     return true;
1812   }
1813 
1814   // We have a non-null base.  These are generally known to be true, but if it's
1815   // a weak declaration it can be null at runtime.
1816   Result = true;
1817   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1818   return !Decl || !Decl->isWeak();
1819 }
1820 
1821 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1822   switch (Val.getKind()) {
1823   case APValue::Uninitialized:
1824     return false;
1825   case APValue::Int:
1826     Result = Val.getInt().getBoolValue();
1827     return true;
1828   case APValue::Float:
1829     Result = !Val.getFloat().isZero();
1830     return true;
1831   case APValue::ComplexInt:
1832     Result = Val.getComplexIntReal().getBoolValue() ||
1833              Val.getComplexIntImag().getBoolValue();
1834     return true;
1835   case APValue::ComplexFloat:
1836     Result = !Val.getComplexFloatReal().isZero() ||
1837              !Val.getComplexFloatImag().isZero();
1838     return true;
1839   case APValue::LValue:
1840     return EvalPointerValueAsBool(Val, Result);
1841   case APValue::MemberPointer:
1842     Result = Val.getMemberPointerDecl();
1843     return true;
1844   case APValue::Vector:
1845   case APValue::Array:
1846   case APValue::Struct:
1847   case APValue::Union:
1848   case APValue::AddrLabelDiff:
1849     return false;
1850   }
1851 
1852   llvm_unreachable("unknown APValue kind");
1853 }
1854 
1855 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1856                                        EvalInfo &Info) {
1857   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
1858   APValue Val;
1859   if (!Evaluate(Val, Info, E))
1860     return false;
1861   return HandleConversionToBool(Val, Result);
1862 }
1863 
1864 template<typename T>
1865 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1866                            const T &SrcValue, QualType DestType) {
1867   Info.CCEDiag(E, diag::note_constexpr_overflow)
1868     << SrcValue << DestType;
1869   return Info.noteUndefinedBehavior();
1870 }
1871 
1872 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1873                                  QualType SrcType, const APFloat &Value,
1874                                  QualType DestType, APSInt &Result) {
1875   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1876   // Determine whether we are converting to unsigned or signed.
1877   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
1878 
1879   Result = APSInt(DestWidth, !DestSigned);
1880   bool ignored;
1881   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1882       & APFloat::opInvalidOp)
1883     return HandleOverflow(Info, E, Value, DestType);
1884   return true;
1885 }
1886 
1887 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1888                                    QualType SrcType, QualType DestType,
1889                                    APFloat &Result) {
1890   APFloat Value = Result;
1891   bool ignored;
1892   if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1893                      APFloat::rmNearestTiesToEven, &ignored)
1894       & APFloat::opOverflow)
1895     return HandleOverflow(Info, E, Value, DestType);
1896   return true;
1897 }
1898 
1899 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1900                                  QualType DestType, QualType SrcType,
1901                                  const APSInt &Value) {
1902   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1903   APSInt Result = Value;
1904   // Figure out if this is a truncate, extend or noop cast.
1905   // If the input is signed, do a sign extend, noop, or truncate.
1906   Result = Result.extOrTrunc(DestWidth);
1907   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
1908   return Result;
1909 }
1910 
1911 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1912                                  QualType SrcType, const APSInt &Value,
1913                                  QualType DestType, APFloat &Result) {
1914   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1915   if (Result.convertFromAPInt(Value, Value.isSigned(),
1916                               APFloat::rmNearestTiesToEven)
1917       & APFloat::opOverflow)
1918     return HandleOverflow(Info, E, Value, DestType);
1919   return true;
1920 }
1921 
1922 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1923                                   APValue &Value, const FieldDecl *FD) {
1924   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1925 
1926   if (!Value.isInt()) {
1927     // Trying to store a pointer-cast-to-integer into a bitfield.
1928     // FIXME: In this case, we should provide the diagnostic for casting
1929     // a pointer to an integer.
1930     assert(Value.isLValue() && "integral value neither int nor lvalue?");
1931     Info.FFDiag(E);
1932     return false;
1933   }
1934 
1935   APSInt &Int = Value.getInt();
1936   unsigned OldBitWidth = Int.getBitWidth();
1937   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1938   if (NewBitWidth < OldBitWidth)
1939     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1940   return true;
1941 }
1942 
1943 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1944                                   llvm::APInt &Res) {
1945   APValue SVal;
1946   if (!Evaluate(SVal, Info, E))
1947     return false;
1948   if (SVal.isInt()) {
1949     Res = SVal.getInt();
1950     return true;
1951   }
1952   if (SVal.isFloat()) {
1953     Res = SVal.getFloat().bitcastToAPInt();
1954     return true;
1955   }
1956   if (SVal.isVector()) {
1957     QualType VecTy = E->getType();
1958     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1959     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1960     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1961     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1962     Res = llvm::APInt::getNullValue(VecSize);
1963     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1964       APValue &Elt = SVal.getVectorElt(i);
1965       llvm::APInt EltAsInt;
1966       if (Elt.isInt()) {
1967         EltAsInt = Elt.getInt();
1968       } else if (Elt.isFloat()) {
1969         EltAsInt = Elt.getFloat().bitcastToAPInt();
1970       } else {
1971         // Don't try to handle vectors of anything other than int or float
1972         // (not sure if it's possible to hit this case).
1973         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1974         return false;
1975       }
1976       unsigned BaseEltSize = EltAsInt.getBitWidth();
1977       if (BigEndian)
1978         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1979       else
1980         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1981     }
1982     return true;
1983   }
1984   // Give up if the input isn't an int, float, or vector.  For example, we
1985   // reject "(v4i16)(intptr_t)&a".
1986   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1987   return false;
1988 }
1989 
1990 /// Perform the given integer operation, which is known to need at most BitWidth
1991 /// bits, and check for overflow in the original type (if that type was not an
1992 /// unsigned type).
1993 template<typename Operation>
1994 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1995                                  const APSInt &LHS, const APSInt &RHS,
1996                                  unsigned BitWidth, Operation Op,
1997                                  APSInt &Result) {
1998   if (LHS.isUnsigned()) {
1999     Result = Op(LHS, RHS);
2000     return true;
2001   }
2002 
2003   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2004   Result = Value.trunc(LHS.getBitWidth());
2005   if (Result.extend(BitWidth) != Value) {
2006     if (Info.checkingForOverflow())
2007       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2008                                        diag::warn_integer_constant_overflow)
2009           << Result.toString(10) << E->getType();
2010     else
2011       return HandleOverflow(Info, E, Value, E->getType());
2012   }
2013   return true;
2014 }
2015 
2016 /// Perform the given binary integer operation.
2017 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2018                               BinaryOperatorKind Opcode, APSInt RHS,
2019                               APSInt &Result) {
2020   switch (Opcode) {
2021   default:
2022     Info.FFDiag(E);
2023     return false;
2024   case BO_Mul:
2025     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2026                                 std::multiplies<APSInt>(), Result);
2027   case BO_Add:
2028     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2029                                 std::plus<APSInt>(), Result);
2030   case BO_Sub:
2031     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2032                                 std::minus<APSInt>(), Result);
2033   case BO_And: Result = LHS & RHS; return true;
2034   case BO_Xor: Result = LHS ^ RHS; return true;
2035   case BO_Or:  Result = LHS | RHS; return true;
2036   case BO_Div:
2037   case BO_Rem:
2038     if (RHS == 0) {
2039       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2040       return false;
2041     }
2042     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2043     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2044     // this operation and gives the two's complement result.
2045     if (RHS.isNegative() && RHS.isAllOnesValue() &&
2046         LHS.isSigned() && LHS.isMinSignedValue())
2047       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2048                             E->getType());
2049     return true;
2050   case BO_Shl: {
2051     if (Info.getLangOpts().OpenCL)
2052       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2053       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2054                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2055                     RHS.isUnsigned());
2056     else if (RHS.isSigned() && RHS.isNegative()) {
2057       // During constant-folding, a negative shift is an opposite shift. Such
2058       // a shift is not a constant expression.
2059       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2060       RHS = -RHS;
2061       goto shift_right;
2062     }
2063   shift_left:
2064     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2065     // the shifted type.
2066     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2067     if (SA != RHS) {
2068       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2069         << RHS << E->getType() << LHS.getBitWidth();
2070     } else if (LHS.isSigned()) {
2071       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2072       // operand, and must not overflow the corresponding unsigned type.
2073       if (LHS.isNegative())
2074         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2075       else if (LHS.countLeadingZeros() < SA)
2076         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2077     }
2078     Result = LHS << SA;
2079     return true;
2080   }
2081   case BO_Shr: {
2082     if (Info.getLangOpts().OpenCL)
2083       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2084       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2085                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2086                     RHS.isUnsigned());
2087     else if (RHS.isSigned() && RHS.isNegative()) {
2088       // During constant-folding, a negative shift is an opposite shift. Such a
2089       // shift is not a constant expression.
2090       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2091       RHS = -RHS;
2092       goto shift_left;
2093     }
2094   shift_right:
2095     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2096     // shifted type.
2097     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2098     if (SA != RHS)
2099       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2100         << RHS << E->getType() << LHS.getBitWidth();
2101     Result = LHS >> SA;
2102     return true;
2103   }
2104 
2105   case BO_LT: Result = LHS < RHS; return true;
2106   case BO_GT: Result = LHS > RHS; return true;
2107   case BO_LE: Result = LHS <= RHS; return true;
2108   case BO_GE: Result = LHS >= RHS; return true;
2109   case BO_EQ: Result = LHS == RHS; return true;
2110   case BO_NE: Result = LHS != RHS; return true;
2111   }
2112 }
2113 
2114 /// Perform the given binary floating-point operation, in-place, on LHS.
2115 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2116                                   APFloat &LHS, BinaryOperatorKind Opcode,
2117                                   const APFloat &RHS) {
2118   switch (Opcode) {
2119   default:
2120     Info.FFDiag(E);
2121     return false;
2122   case BO_Mul:
2123     LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2124     break;
2125   case BO_Add:
2126     LHS.add(RHS, APFloat::rmNearestTiesToEven);
2127     break;
2128   case BO_Sub:
2129     LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2130     break;
2131   case BO_Div:
2132     LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2133     break;
2134   }
2135 
2136   if (LHS.isInfinity() || LHS.isNaN()) {
2137     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2138     return Info.noteUndefinedBehavior();
2139   }
2140   return true;
2141 }
2142 
2143 /// Cast an lvalue referring to a base subobject to a derived class, by
2144 /// truncating the lvalue's path to the given length.
2145 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2146                                const RecordDecl *TruncatedType,
2147                                unsigned TruncatedElements) {
2148   SubobjectDesignator &D = Result.Designator;
2149 
2150   // Check we actually point to a derived class object.
2151   if (TruncatedElements == D.Entries.size())
2152     return true;
2153   assert(TruncatedElements >= D.MostDerivedPathLength &&
2154          "not casting to a derived class");
2155   if (!Result.checkSubobject(Info, E, CSK_Derived))
2156     return false;
2157 
2158   // Truncate the path to the subobject, and remove any derived-to-base offsets.
2159   const RecordDecl *RD = TruncatedType;
2160   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2161     if (RD->isInvalidDecl()) return false;
2162     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2163     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2164     if (isVirtualBaseClass(D.Entries[I]))
2165       Result.Offset -= Layout.getVBaseClassOffset(Base);
2166     else
2167       Result.Offset -= Layout.getBaseClassOffset(Base);
2168     RD = Base;
2169   }
2170   D.Entries.resize(TruncatedElements);
2171   return true;
2172 }
2173 
2174 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2175                                    const CXXRecordDecl *Derived,
2176                                    const CXXRecordDecl *Base,
2177                                    const ASTRecordLayout *RL = nullptr) {
2178   if (!RL) {
2179     if (Derived->isInvalidDecl()) return false;
2180     RL = &Info.Ctx.getASTRecordLayout(Derived);
2181   }
2182 
2183   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2184   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2185   return true;
2186 }
2187 
2188 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2189                              const CXXRecordDecl *DerivedDecl,
2190                              const CXXBaseSpecifier *Base) {
2191   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2192 
2193   if (!Base->isVirtual())
2194     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2195 
2196   SubobjectDesignator &D = Obj.Designator;
2197   if (D.Invalid)
2198     return false;
2199 
2200   // Extract most-derived object and corresponding type.
2201   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2202   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2203     return false;
2204 
2205   // Find the virtual base class.
2206   if (DerivedDecl->isInvalidDecl()) return false;
2207   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2208   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2209   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2210   return true;
2211 }
2212 
2213 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2214                                  QualType Type, LValue &Result) {
2215   for (CastExpr::path_const_iterator PathI = E->path_begin(),
2216                                      PathE = E->path_end();
2217        PathI != PathE; ++PathI) {
2218     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2219                           *PathI))
2220       return false;
2221     Type = (*PathI)->getType();
2222   }
2223   return true;
2224 }
2225 
2226 /// Update LVal to refer to the given field, which must be a member of the type
2227 /// currently described by LVal.
2228 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2229                                const FieldDecl *FD,
2230                                const ASTRecordLayout *RL = nullptr) {
2231   if (!RL) {
2232     if (FD->getParent()->isInvalidDecl()) return false;
2233     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2234   }
2235 
2236   unsigned I = FD->getFieldIndex();
2237   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2238   LVal.addDecl(Info, E, FD);
2239   return true;
2240 }
2241 
2242 /// Update LVal to refer to the given indirect field.
2243 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2244                                        LValue &LVal,
2245                                        const IndirectFieldDecl *IFD) {
2246   for (const auto *C : IFD->chain())
2247     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2248       return false;
2249   return true;
2250 }
2251 
2252 /// Get the size of the given type in char units.
2253 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2254                          QualType Type, CharUnits &Size) {
2255   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2256   // extension.
2257   if (Type->isVoidType() || Type->isFunctionType()) {
2258     Size = CharUnits::One();
2259     return true;
2260   }
2261 
2262   if (Type->isDependentType()) {
2263     Info.FFDiag(Loc);
2264     return false;
2265   }
2266 
2267   if (!Type->isConstantSizeType()) {
2268     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2269     // FIXME: Better diagnostic.
2270     Info.FFDiag(Loc);
2271     return false;
2272   }
2273 
2274   Size = Info.Ctx.getTypeSizeInChars(Type);
2275   return true;
2276 }
2277 
2278 /// Update a pointer value to model pointer arithmetic.
2279 /// \param Info - Information about the ongoing evaluation.
2280 /// \param E - The expression being evaluated, for diagnostic purposes.
2281 /// \param LVal - The pointer value to be updated.
2282 /// \param EltTy - The pointee type represented by LVal.
2283 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2284 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2285                                         LValue &LVal, QualType EltTy,
2286                                         APSInt Adjustment) {
2287   CharUnits SizeOfPointee;
2288   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2289     return false;
2290 
2291   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2292   return true;
2293 }
2294 
2295 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2296                                         LValue &LVal, QualType EltTy,
2297                                         int64_t Adjustment) {
2298   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2299                                      APSInt::get(Adjustment));
2300 }
2301 
2302 /// Update an lvalue to refer to a component of a complex number.
2303 /// \param Info - Information about the ongoing evaluation.
2304 /// \param LVal - The lvalue to be updated.
2305 /// \param EltTy - The complex number's component type.
2306 /// \param Imag - False for the real component, true for the imaginary.
2307 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2308                                        LValue &LVal, QualType EltTy,
2309                                        bool Imag) {
2310   if (Imag) {
2311     CharUnits SizeOfComponent;
2312     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2313       return false;
2314     LVal.Offset += SizeOfComponent;
2315   }
2316   LVal.addComplex(Info, E, EltTy, Imag);
2317   return true;
2318 }
2319 
2320 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2321                                            QualType Type, const LValue &LVal,
2322                                            APValue &RVal);
2323 
2324 /// Try to evaluate the initializer for a variable declaration.
2325 ///
2326 /// \param Info   Information about the ongoing evaluation.
2327 /// \param E      An expression to be used when printing diagnostics.
2328 /// \param VD     The variable whose initializer should be obtained.
2329 /// \param Frame  The frame in which the variable was created. Must be null
2330 ///               if this variable is not local to the evaluation.
2331 /// \param Result Filled in with a pointer to the value of the variable.
2332 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2333                                 const VarDecl *VD, CallStackFrame *Frame,
2334                                 APValue *&Result) {
2335 
2336   // If this is a parameter to an active constexpr function call, perform
2337   // argument substitution.
2338   if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2339     // Assume arguments of a potential constant expression are unknown
2340     // constant expressions.
2341     if (Info.checkingPotentialConstantExpression())
2342       return false;
2343     if (!Frame || !Frame->Arguments) {
2344       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2345       return false;
2346     }
2347     Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2348     return true;
2349   }
2350 
2351   // If this is a local variable, dig out its value.
2352   if (Frame) {
2353     Result = Frame->getTemporary(VD);
2354     if (!Result) {
2355       // Assume variables referenced within a lambda's call operator that were
2356       // not declared within the call operator are captures and during checking
2357       // of a potential constant expression, assume they are unknown constant
2358       // expressions.
2359       assert(isLambdaCallOperator(Frame->Callee) &&
2360              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2361              "missing value for local variable");
2362       if (Info.checkingPotentialConstantExpression())
2363         return false;
2364       // FIXME: implement capture evaluation during constant expr evaluation.
2365       Info.FFDiag(E->getLocStart(),
2366            diag::note_unimplemented_constexpr_lambda_feature_ast)
2367           << "captures not currently allowed";
2368       return false;
2369     }
2370     return true;
2371   }
2372 
2373   // Dig out the initializer, and use the declaration which it's attached to.
2374   const Expr *Init = VD->getAnyInitializer(VD);
2375   if (!Init || Init->isValueDependent()) {
2376     // If we're checking a potential constant expression, the variable could be
2377     // initialized later.
2378     if (!Info.checkingPotentialConstantExpression())
2379       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2380     return false;
2381   }
2382 
2383   // If we're currently evaluating the initializer of this declaration, use that
2384   // in-flight value.
2385   if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2386     Result = Info.EvaluatingDeclValue;
2387     return true;
2388   }
2389 
2390   // Never evaluate the initializer of a weak variable. We can't be sure that
2391   // this is the definition which will be used.
2392   if (VD->isWeak()) {
2393     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2394     return false;
2395   }
2396 
2397   // Check that we can fold the initializer. In C++, we will have already done
2398   // this in the cases where it matters for conformance.
2399   SmallVector<PartialDiagnosticAt, 8> Notes;
2400   if (!VD->evaluateValue(Notes)) {
2401     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2402               Notes.size() + 1) << VD;
2403     Info.Note(VD->getLocation(), diag::note_declared_at);
2404     Info.addNotes(Notes);
2405     return false;
2406   } else if (!VD->checkInitIsICE()) {
2407     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2408                  Notes.size() + 1) << VD;
2409     Info.Note(VD->getLocation(), diag::note_declared_at);
2410     Info.addNotes(Notes);
2411   }
2412 
2413   Result = VD->getEvaluatedValue();
2414   return true;
2415 }
2416 
2417 static bool IsConstNonVolatile(QualType T) {
2418   Qualifiers Quals = T.getQualifiers();
2419   return Quals.hasConst() && !Quals.hasVolatile();
2420 }
2421 
2422 /// Get the base index of the given base class within an APValue representing
2423 /// the given derived class.
2424 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2425                              const CXXRecordDecl *Base) {
2426   Base = Base->getCanonicalDecl();
2427   unsigned Index = 0;
2428   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2429          E = Derived->bases_end(); I != E; ++I, ++Index) {
2430     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2431       return Index;
2432   }
2433 
2434   llvm_unreachable("base class missing from derived class's bases list");
2435 }
2436 
2437 /// Extract the value of a character from a string literal.
2438 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2439                                             uint64_t Index) {
2440   // FIXME: Support MakeStringConstant
2441   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2442     std::string Str;
2443     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2444     assert(Index <= Str.size() && "Index too large");
2445     return APSInt::getUnsigned(Str.c_str()[Index]);
2446   }
2447 
2448   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2449     Lit = PE->getFunctionName();
2450   const StringLiteral *S = cast<StringLiteral>(Lit);
2451   const ConstantArrayType *CAT =
2452       Info.Ctx.getAsConstantArrayType(S->getType());
2453   assert(CAT && "string literal isn't an array");
2454   QualType CharType = CAT->getElementType();
2455   assert(CharType->isIntegerType() && "unexpected character type");
2456 
2457   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2458                CharType->isUnsignedIntegerType());
2459   if (Index < S->getLength())
2460     Value = S->getCodeUnit(Index);
2461   return Value;
2462 }
2463 
2464 // Expand a string literal into an array of characters.
2465 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2466                                 APValue &Result) {
2467   const StringLiteral *S = cast<StringLiteral>(Lit);
2468   const ConstantArrayType *CAT =
2469       Info.Ctx.getAsConstantArrayType(S->getType());
2470   assert(CAT && "string literal isn't an array");
2471   QualType CharType = CAT->getElementType();
2472   assert(CharType->isIntegerType() && "unexpected character type");
2473 
2474   unsigned Elts = CAT->getSize().getZExtValue();
2475   Result = APValue(APValue::UninitArray(),
2476                    std::min(S->getLength(), Elts), Elts);
2477   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2478                CharType->isUnsignedIntegerType());
2479   if (Result.hasArrayFiller())
2480     Result.getArrayFiller() = APValue(Value);
2481   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2482     Value = S->getCodeUnit(I);
2483     Result.getArrayInitializedElt(I) = APValue(Value);
2484   }
2485 }
2486 
2487 // Expand an array so that it has more than Index filled elements.
2488 static void expandArray(APValue &Array, unsigned Index) {
2489   unsigned Size = Array.getArraySize();
2490   assert(Index < Size);
2491 
2492   // Always at least double the number of elements for which we store a value.
2493   unsigned OldElts = Array.getArrayInitializedElts();
2494   unsigned NewElts = std::max(Index+1, OldElts * 2);
2495   NewElts = std::min(Size, std::max(NewElts, 8u));
2496 
2497   // Copy the data across.
2498   APValue NewValue(APValue::UninitArray(), NewElts, Size);
2499   for (unsigned I = 0; I != OldElts; ++I)
2500     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2501   for (unsigned I = OldElts; I != NewElts; ++I)
2502     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2503   if (NewValue.hasArrayFiller())
2504     NewValue.getArrayFiller() = Array.getArrayFiller();
2505   Array.swap(NewValue);
2506 }
2507 
2508 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2509 /// conversion. If it's of class type, we may assume that the copy operation
2510 /// is trivial. Note that this is never true for a union type with fields
2511 /// (because the copy always "reads" the active member) and always true for
2512 /// a non-class type.
2513 static bool isReadByLvalueToRvalueConversion(QualType T) {
2514   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2515   if (!RD || (RD->isUnion() && !RD->field_empty()))
2516     return true;
2517   if (RD->isEmpty())
2518     return false;
2519 
2520   for (auto *Field : RD->fields())
2521     if (isReadByLvalueToRvalueConversion(Field->getType()))
2522       return true;
2523 
2524   for (auto &BaseSpec : RD->bases())
2525     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2526       return true;
2527 
2528   return false;
2529 }
2530 
2531 /// Diagnose an attempt to read from any unreadable field within the specified
2532 /// type, which might be a class type.
2533 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2534                                      QualType T) {
2535   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2536   if (!RD)
2537     return false;
2538 
2539   if (!RD->hasMutableFields())
2540     return false;
2541 
2542   for (auto *Field : RD->fields()) {
2543     // If we're actually going to read this field in some way, then it can't
2544     // be mutable. If we're in a union, then assigning to a mutable field
2545     // (even an empty one) can change the active member, so that's not OK.
2546     // FIXME: Add core issue number for the union case.
2547     if (Field->isMutable() &&
2548         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2549       Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2550       Info.Note(Field->getLocation(), diag::note_declared_at);
2551       return true;
2552     }
2553 
2554     if (diagnoseUnreadableFields(Info, E, Field->getType()))
2555       return true;
2556   }
2557 
2558   for (auto &BaseSpec : RD->bases())
2559     if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2560       return true;
2561 
2562   // All mutable fields were empty, and thus not actually read.
2563   return false;
2564 }
2565 
2566 /// Kinds of access we can perform on an object, for diagnostics.
2567 enum AccessKinds {
2568   AK_Read,
2569   AK_Assign,
2570   AK_Increment,
2571   AK_Decrement
2572 };
2573 
2574 namespace {
2575 /// A handle to a complete object (an object that is not a subobject of
2576 /// another object).
2577 struct CompleteObject {
2578   /// The value of the complete object.
2579   APValue *Value;
2580   /// The type of the complete object.
2581   QualType Type;
2582 
2583   CompleteObject() : Value(nullptr) {}
2584   CompleteObject(APValue *Value, QualType Type)
2585       : Value(Value), Type(Type) {
2586     assert(Value && "missing value for complete object");
2587   }
2588 
2589   explicit operator bool() const { return Value; }
2590 };
2591 } // end anonymous namespace
2592 
2593 /// Find the designated sub-object of an rvalue.
2594 template<typename SubobjectHandler>
2595 typename SubobjectHandler::result_type
2596 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2597               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2598   if (Sub.Invalid)
2599     // A diagnostic will have already been produced.
2600     return handler.failed();
2601   if (Sub.isOnePastTheEnd()) {
2602     if (Info.getLangOpts().CPlusPlus11)
2603       Info.FFDiag(E, diag::note_constexpr_access_past_end)
2604         << handler.AccessKind;
2605     else
2606       Info.FFDiag(E);
2607     return handler.failed();
2608   }
2609 
2610   APValue *O = Obj.Value;
2611   QualType ObjType = Obj.Type;
2612   const FieldDecl *LastField = nullptr;
2613 
2614   // Walk the designator's path to find the subobject.
2615   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2616     if (O->isUninit()) {
2617       if (!Info.checkingPotentialConstantExpression())
2618         Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2619       return handler.failed();
2620     }
2621 
2622     if (I == N) {
2623       // If we are reading an object of class type, there may still be more
2624       // things we need to check: if there are any mutable subobjects, we
2625       // cannot perform this read. (This only happens when performing a trivial
2626       // copy or assignment.)
2627       if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2628           diagnoseUnreadableFields(Info, E, ObjType))
2629         return handler.failed();
2630 
2631       if (!handler.found(*O, ObjType))
2632         return false;
2633 
2634       // If we modified a bit-field, truncate it to the right width.
2635       if (handler.AccessKind != AK_Read &&
2636           LastField && LastField->isBitField() &&
2637           !truncateBitfieldValue(Info, E, *O, LastField))
2638         return false;
2639 
2640       return true;
2641     }
2642 
2643     LastField = nullptr;
2644     if (ObjType->isArrayType()) {
2645       // Next subobject is an array element.
2646       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2647       assert(CAT && "vla in literal type?");
2648       uint64_t Index = Sub.Entries[I].ArrayIndex;
2649       if (CAT->getSize().ule(Index)) {
2650         // Note, it should not be possible to form a pointer with a valid
2651         // designator which points more than one past the end of the array.
2652         if (Info.getLangOpts().CPlusPlus11)
2653           Info.FFDiag(E, diag::note_constexpr_access_past_end)
2654             << handler.AccessKind;
2655         else
2656           Info.FFDiag(E);
2657         return handler.failed();
2658       }
2659 
2660       ObjType = CAT->getElementType();
2661 
2662       // An array object is represented as either an Array APValue or as an
2663       // LValue which refers to a string literal.
2664       if (O->isLValue()) {
2665         assert(I == N - 1 && "extracting subobject of character?");
2666         assert(!O->hasLValuePath() || O->getLValuePath().empty());
2667         if (handler.AccessKind != AK_Read)
2668           expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2669                               *O);
2670         else
2671           return handler.foundString(*O, ObjType, Index);
2672       }
2673 
2674       if (O->getArrayInitializedElts() > Index)
2675         O = &O->getArrayInitializedElt(Index);
2676       else if (handler.AccessKind != AK_Read) {
2677         expandArray(*O, Index);
2678         O = &O->getArrayInitializedElt(Index);
2679       } else
2680         O = &O->getArrayFiller();
2681     } else if (ObjType->isAnyComplexType()) {
2682       // Next subobject is a complex number.
2683       uint64_t Index = Sub.Entries[I].ArrayIndex;
2684       if (Index > 1) {
2685         if (Info.getLangOpts().CPlusPlus11)
2686           Info.FFDiag(E, diag::note_constexpr_access_past_end)
2687             << handler.AccessKind;
2688         else
2689           Info.FFDiag(E);
2690         return handler.failed();
2691       }
2692 
2693       bool WasConstQualified = ObjType.isConstQualified();
2694       ObjType = ObjType->castAs<ComplexType>()->getElementType();
2695       if (WasConstQualified)
2696         ObjType.addConst();
2697 
2698       assert(I == N - 1 && "extracting subobject of scalar?");
2699       if (O->isComplexInt()) {
2700         return handler.found(Index ? O->getComplexIntImag()
2701                                    : O->getComplexIntReal(), ObjType);
2702       } else {
2703         assert(O->isComplexFloat());
2704         return handler.found(Index ? O->getComplexFloatImag()
2705                                    : O->getComplexFloatReal(), ObjType);
2706       }
2707     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2708       if (Field->isMutable() && handler.AccessKind == AK_Read) {
2709         Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
2710           << Field;
2711         Info.Note(Field->getLocation(), diag::note_declared_at);
2712         return handler.failed();
2713       }
2714 
2715       // Next subobject is a class, struct or union field.
2716       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2717       if (RD->isUnion()) {
2718         const FieldDecl *UnionField = O->getUnionField();
2719         if (!UnionField ||
2720             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2721           Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
2722             << handler.AccessKind << Field << !UnionField << UnionField;
2723           return handler.failed();
2724         }
2725         O = &O->getUnionValue();
2726       } else
2727         O = &O->getStructField(Field->getFieldIndex());
2728 
2729       bool WasConstQualified = ObjType.isConstQualified();
2730       ObjType = Field->getType();
2731       if (WasConstQualified && !Field->isMutable())
2732         ObjType.addConst();
2733 
2734       if (ObjType.isVolatileQualified()) {
2735         if (Info.getLangOpts().CPlusPlus) {
2736           // FIXME: Include a description of the path to the volatile subobject.
2737           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2738             << handler.AccessKind << 2 << Field;
2739           Info.Note(Field->getLocation(), diag::note_declared_at);
2740         } else {
2741           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2742         }
2743         return handler.failed();
2744       }
2745 
2746       LastField = Field;
2747     } else {
2748       // Next subobject is a base class.
2749       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2750       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2751       O = &O->getStructBase(getBaseIndex(Derived, Base));
2752 
2753       bool WasConstQualified = ObjType.isConstQualified();
2754       ObjType = Info.Ctx.getRecordType(Base);
2755       if (WasConstQualified)
2756         ObjType.addConst();
2757     }
2758   }
2759 }
2760 
2761 namespace {
2762 struct ExtractSubobjectHandler {
2763   EvalInfo &Info;
2764   APValue &Result;
2765 
2766   static const AccessKinds AccessKind = AK_Read;
2767 
2768   typedef bool result_type;
2769   bool failed() { return false; }
2770   bool found(APValue &Subobj, QualType SubobjType) {
2771     Result = Subobj;
2772     return true;
2773   }
2774   bool found(APSInt &Value, QualType SubobjType) {
2775     Result = APValue(Value);
2776     return true;
2777   }
2778   bool found(APFloat &Value, QualType SubobjType) {
2779     Result = APValue(Value);
2780     return true;
2781   }
2782   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2783     Result = APValue(extractStringLiteralCharacter(
2784         Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2785     return true;
2786   }
2787 };
2788 } // end anonymous namespace
2789 
2790 const AccessKinds ExtractSubobjectHandler::AccessKind;
2791 
2792 /// Extract the designated sub-object of an rvalue.
2793 static bool extractSubobject(EvalInfo &Info, const Expr *E,
2794                              const CompleteObject &Obj,
2795                              const SubobjectDesignator &Sub,
2796                              APValue &Result) {
2797   ExtractSubobjectHandler Handler = { Info, Result };
2798   return findSubobject(Info, E, Obj, Sub, Handler);
2799 }
2800 
2801 namespace {
2802 struct ModifySubobjectHandler {
2803   EvalInfo &Info;
2804   APValue &NewVal;
2805   const Expr *E;
2806 
2807   typedef bool result_type;
2808   static const AccessKinds AccessKind = AK_Assign;
2809 
2810   bool checkConst(QualType QT) {
2811     // Assigning to a const object has undefined behavior.
2812     if (QT.isConstQualified()) {
2813       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
2814       return false;
2815     }
2816     return true;
2817   }
2818 
2819   bool failed() { return false; }
2820   bool found(APValue &Subobj, QualType SubobjType) {
2821     if (!checkConst(SubobjType))
2822       return false;
2823     // We've been given ownership of NewVal, so just swap it in.
2824     Subobj.swap(NewVal);
2825     return true;
2826   }
2827   bool found(APSInt &Value, QualType SubobjType) {
2828     if (!checkConst(SubobjType))
2829       return false;
2830     if (!NewVal.isInt()) {
2831       // Maybe trying to write a cast pointer value into a complex?
2832       Info.FFDiag(E);
2833       return false;
2834     }
2835     Value = NewVal.getInt();
2836     return true;
2837   }
2838   bool found(APFloat &Value, QualType SubobjType) {
2839     if (!checkConst(SubobjType))
2840       return false;
2841     Value = NewVal.getFloat();
2842     return true;
2843   }
2844   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2845     llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2846   }
2847 };
2848 } // end anonymous namespace
2849 
2850 const AccessKinds ModifySubobjectHandler::AccessKind;
2851 
2852 /// Update the designated sub-object of an rvalue to the given value.
2853 static bool modifySubobject(EvalInfo &Info, const Expr *E,
2854                             const CompleteObject &Obj,
2855                             const SubobjectDesignator &Sub,
2856                             APValue &NewVal) {
2857   ModifySubobjectHandler Handler = { Info, NewVal, E };
2858   return findSubobject(Info, E, Obj, Sub, Handler);
2859 }
2860 
2861 /// Find the position where two subobject designators diverge, or equivalently
2862 /// the length of the common initial subsequence.
2863 static unsigned FindDesignatorMismatch(QualType ObjType,
2864                                        const SubobjectDesignator &A,
2865                                        const SubobjectDesignator &B,
2866                                        bool &WasArrayIndex) {
2867   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2868   for (/**/; I != N; ++I) {
2869     if (!ObjType.isNull() &&
2870         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
2871       // Next subobject is an array element.
2872       if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2873         WasArrayIndex = true;
2874         return I;
2875       }
2876       if (ObjType->isAnyComplexType())
2877         ObjType = ObjType->castAs<ComplexType>()->getElementType();
2878       else
2879         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
2880     } else {
2881       if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2882         WasArrayIndex = false;
2883         return I;
2884       }
2885       if (const FieldDecl *FD = getAsField(A.Entries[I]))
2886         // Next subobject is a field.
2887         ObjType = FD->getType();
2888       else
2889         // Next subobject is a base class.
2890         ObjType = QualType();
2891     }
2892   }
2893   WasArrayIndex = false;
2894   return I;
2895 }
2896 
2897 /// Determine whether the given subobject designators refer to elements of the
2898 /// same array object.
2899 static bool AreElementsOfSameArray(QualType ObjType,
2900                                    const SubobjectDesignator &A,
2901                                    const SubobjectDesignator &B) {
2902   if (A.Entries.size() != B.Entries.size())
2903     return false;
2904 
2905   bool IsArray = A.MostDerivedIsArrayElement;
2906   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2907     // A is a subobject of the array element.
2908     return false;
2909 
2910   // If A (and B) designates an array element, the last entry will be the array
2911   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2912   // of length 1' case, and the entire path must match.
2913   bool WasArrayIndex;
2914   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2915   return CommonLength >= A.Entries.size() - IsArray;
2916 }
2917 
2918 /// Find the complete object to which an LValue refers.
2919 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2920                                          AccessKinds AK, const LValue &LVal,
2921                                          QualType LValType) {
2922   if (!LVal.Base) {
2923     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
2924     return CompleteObject();
2925   }
2926 
2927   CallStackFrame *Frame = nullptr;
2928   if (LVal.CallIndex) {
2929     Frame = Info.getCallFrame(LVal.CallIndex);
2930     if (!Frame) {
2931       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
2932         << AK << LVal.Base.is<const ValueDecl*>();
2933       NoteLValueLocation(Info, LVal.Base);
2934       return CompleteObject();
2935     }
2936   }
2937 
2938   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2939   // is not a constant expression (even if the object is non-volatile). We also
2940   // apply this rule to C++98, in order to conform to the expected 'volatile'
2941   // semantics.
2942   if (LValType.isVolatileQualified()) {
2943     if (Info.getLangOpts().CPlusPlus)
2944       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
2945         << AK << LValType;
2946     else
2947       Info.FFDiag(E);
2948     return CompleteObject();
2949   }
2950 
2951   // Compute value storage location and type of base object.
2952   APValue *BaseVal = nullptr;
2953   QualType BaseType = getType(LVal.Base);
2954 
2955   if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2956     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2957     // In C++11, constexpr, non-volatile variables initialized with constant
2958     // expressions are constant expressions too. Inside constexpr functions,
2959     // parameters are constant expressions even if they're non-const.
2960     // In C++1y, objects local to a constant expression (those with a Frame) are
2961     // both readable and writable inside constant expressions.
2962     // In C, such things can also be folded, although they are not ICEs.
2963     const VarDecl *VD = dyn_cast<VarDecl>(D);
2964     if (VD) {
2965       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2966         VD = VDef;
2967     }
2968     if (!VD || VD->isInvalidDecl()) {
2969       Info.FFDiag(E);
2970       return CompleteObject();
2971     }
2972 
2973     // Accesses of volatile-qualified objects are not allowed.
2974     if (BaseType.isVolatileQualified()) {
2975       if (Info.getLangOpts().CPlusPlus) {
2976         Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2977           << AK << 1 << VD;
2978         Info.Note(VD->getLocation(), diag::note_declared_at);
2979       } else {
2980         Info.FFDiag(E);
2981       }
2982       return CompleteObject();
2983     }
2984 
2985     // Unless we're looking at a local variable or argument in a constexpr call,
2986     // the variable we're reading must be const.
2987     if (!Frame) {
2988       if (Info.getLangOpts().CPlusPlus14 &&
2989           VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2990         // OK, we can read and modify an object if we're in the process of
2991         // evaluating its initializer, because its lifetime began in this
2992         // evaluation.
2993       } else if (AK != AK_Read) {
2994         // All the remaining cases only permit reading.
2995         Info.FFDiag(E, diag::note_constexpr_modify_global);
2996         return CompleteObject();
2997       } else if (VD->isConstexpr()) {
2998         // OK, we can read this variable.
2999       } else if (BaseType->isIntegralOrEnumerationType()) {
3000         // In OpenCL if a variable is in constant address space it is a const value.
3001         if (!(BaseType.isConstQualified() ||
3002               (Info.getLangOpts().OpenCL &&
3003                BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3004           if (Info.getLangOpts().CPlusPlus) {
3005             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3006             Info.Note(VD->getLocation(), diag::note_declared_at);
3007           } else {
3008             Info.FFDiag(E);
3009           }
3010           return CompleteObject();
3011         }
3012       } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3013         // We support folding of const floating-point types, in order to make
3014         // static const data members of such types (supported as an extension)
3015         // more useful.
3016         if (Info.getLangOpts().CPlusPlus11) {
3017           Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3018           Info.Note(VD->getLocation(), diag::note_declared_at);
3019         } else {
3020           Info.CCEDiag(E);
3021         }
3022       } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3023         Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3024         // Keep evaluating to see what we can do.
3025       } else {
3026         // FIXME: Allow folding of values of any literal type in all languages.
3027         if (Info.checkingPotentialConstantExpression() &&
3028             VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3029           // The definition of this variable could be constexpr. We can't
3030           // access it right now, but may be able to in future.
3031         } else if (Info.getLangOpts().CPlusPlus11) {
3032           Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3033           Info.Note(VD->getLocation(), diag::note_declared_at);
3034         } else {
3035           Info.FFDiag(E);
3036         }
3037         return CompleteObject();
3038       }
3039     }
3040 
3041     if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
3042       return CompleteObject();
3043   } else {
3044     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3045 
3046     if (!Frame) {
3047       if (const MaterializeTemporaryExpr *MTE =
3048               dyn_cast<MaterializeTemporaryExpr>(Base)) {
3049         assert(MTE->getStorageDuration() == SD_Static &&
3050                "should have a frame for a non-global materialized temporary");
3051 
3052         // Per C++1y [expr.const]p2:
3053         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3054         //   - a [...] glvalue of integral or enumeration type that refers to
3055         //     a non-volatile const object [...]
3056         //   [...]
3057         //   - a [...] glvalue of literal type that refers to a non-volatile
3058         //     object whose lifetime began within the evaluation of e.
3059         //
3060         // C++11 misses the 'began within the evaluation of e' check and
3061         // instead allows all temporaries, including things like:
3062         //   int &&r = 1;
3063         //   int x = ++r;
3064         //   constexpr int k = r;
3065         // Therefore we use the C++1y rules in C++11 too.
3066         const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3067         const ValueDecl *ED = MTE->getExtendingDecl();
3068         if (!(BaseType.isConstQualified() &&
3069               BaseType->isIntegralOrEnumerationType()) &&
3070             !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
3071           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3072           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3073           return CompleteObject();
3074         }
3075 
3076         BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3077         assert(BaseVal && "got reference to unevaluated temporary");
3078       } else {
3079         Info.FFDiag(E);
3080         return CompleteObject();
3081       }
3082     } else {
3083       BaseVal = Frame->getTemporary(Base);
3084       assert(BaseVal && "missing value for temporary");
3085     }
3086 
3087     // Volatile temporary objects cannot be accessed in constant expressions.
3088     if (BaseType.isVolatileQualified()) {
3089       if (Info.getLangOpts().CPlusPlus) {
3090         Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3091           << AK << 0;
3092         Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3093       } else {
3094         Info.FFDiag(E);
3095       }
3096       return CompleteObject();
3097     }
3098   }
3099 
3100   // During the construction of an object, it is not yet 'const'.
3101   // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
3102   // and this doesn't do quite the right thing for const subobjects of the
3103   // object under construction.
3104   if (LVal.getLValueBase() == Info.EvaluatingDecl) {
3105     BaseType = Info.Ctx.getCanonicalType(BaseType);
3106     BaseType.removeLocalConst();
3107   }
3108 
3109   // In C++1y, we can't safely access any mutable state when we might be
3110   // evaluating after an unmodeled side effect.
3111   //
3112   // FIXME: Not all local state is mutable. Allow local constant subobjects
3113   // to be read here (but take care with 'mutable' fields).
3114   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3115        Info.EvalStatus.HasSideEffects) ||
3116       (AK != AK_Read && Info.IsSpeculativelyEvaluating))
3117     return CompleteObject();
3118 
3119   return CompleteObject(BaseVal, BaseType);
3120 }
3121 
3122 /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3123 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3124 /// glvalue referred to by an entity of reference type.
3125 ///
3126 /// \param Info - Information about the ongoing evaluation.
3127 /// \param Conv - The expression for which we are performing the conversion.
3128 ///               Used for diagnostics.
3129 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3130 ///               case of a non-class type).
3131 /// \param LVal - The glvalue on which we are attempting to perform this action.
3132 /// \param RVal - The produced value will be placed here.
3133 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
3134                                            QualType Type,
3135                                            const LValue &LVal, APValue &RVal) {
3136   if (LVal.Designator.Invalid)
3137     return false;
3138 
3139   // Check for special cases where there is no existing APValue to look at.
3140   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3141   if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
3142     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3143       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3144       // initializer until now for such expressions. Such an expression can't be
3145       // an ICE in C, so this only matters for fold.
3146       if (Type.isVolatileQualified()) {
3147         Info.FFDiag(Conv);
3148         return false;
3149       }
3150       APValue Lit;
3151       if (!Evaluate(Lit, Info, CLE->getInitializer()))
3152         return false;
3153       CompleteObject LitObj(&Lit, Base->getType());
3154       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
3155     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3156       // We represent a string literal array as an lvalue pointing at the
3157       // corresponding expression, rather than building an array of chars.
3158       // FIXME: Support ObjCEncodeExpr, MakeStringConstant
3159       APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3160       CompleteObject StrObj(&Str, Base->getType());
3161       return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
3162     }
3163   }
3164 
3165   CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3166   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
3167 }
3168 
3169 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3170 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3171                              QualType LValType, APValue &Val) {
3172   if (LVal.Designator.Invalid)
3173     return false;
3174 
3175   if (!Info.getLangOpts().CPlusPlus14) {
3176     Info.FFDiag(E);
3177     return false;
3178   }
3179 
3180   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3181   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3182 }
3183 
3184 static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
3185   return T->isSignedIntegerType() &&
3186          Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
3187 }
3188 
3189 namespace {
3190 struct CompoundAssignSubobjectHandler {
3191   EvalInfo &Info;
3192   const Expr *E;
3193   QualType PromotedLHSType;
3194   BinaryOperatorKind Opcode;
3195   const APValue &RHS;
3196 
3197   static const AccessKinds AccessKind = AK_Assign;
3198 
3199   typedef bool result_type;
3200 
3201   bool checkConst(QualType QT) {
3202     // Assigning to a const object has undefined behavior.
3203     if (QT.isConstQualified()) {
3204       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3205       return false;
3206     }
3207     return true;
3208   }
3209 
3210   bool failed() { return false; }
3211   bool found(APValue &Subobj, QualType SubobjType) {
3212     switch (Subobj.getKind()) {
3213     case APValue::Int:
3214       return found(Subobj.getInt(), SubobjType);
3215     case APValue::Float:
3216       return found(Subobj.getFloat(), SubobjType);
3217     case APValue::ComplexInt:
3218     case APValue::ComplexFloat:
3219       // FIXME: Implement complex compound assignment.
3220       Info.FFDiag(E);
3221       return false;
3222     case APValue::LValue:
3223       return foundPointer(Subobj, SubobjType);
3224     default:
3225       // FIXME: can this happen?
3226       Info.FFDiag(E);
3227       return false;
3228     }
3229   }
3230   bool found(APSInt &Value, QualType SubobjType) {
3231     if (!checkConst(SubobjType))
3232       return false;
3233 
3234     if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3235       // We don't support compound assignment on integer-cast-to-pointer
3236       // values.
3237       Info.FFDiag(E);
3238       return false;
3239     }
3240 
3241     APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3242                                     SubobjType, Value);
3243     if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3244       return false;
3245     Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3246     return true;
3247   }
3248   bool found(APFloat &Value, QualType SubobjType) {
3249     return checkConst(SubobjType) &&
3250            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3251                                   Value) &&
3252            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3253            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3254   }
3255   bool foundPointer(APValue &Subobj, QualType SubobjType) {
3256     if (!checkConst(SubobjType))
3257       return false;
3258 
3259     QualType PointeeType;
3260     if (const PointerType *PT = SubobjType->getAs<PointerType>())
3261       PointeeType = PT->getPointeeType();
3262 
3263     if (PointeeType.isNull() || !RHS.isInt() ||
3264         (Opcode != BO_Add && Opcode != BO_Sub)) {
3265       Info.FFDiag(E);
3266       return false;
3267     }
3268 
3269     APSInt Offset = RHS.getInt();
3270     if (Opcode == BO_Sub)
3271       negateAsSigned(Offset);
3272 
3273     LValue LVal;
3274     LVal.setFrom(Info.Ctx, Subobj);
3275     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3276       return false;
3277     LVal.moveInto(Subobj);
3278     return true;
3279   }
3280   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3281     llvm_unreachable("shouldn't encounter string elements here");
3282   }
3283 };
3284 } // end anonymous namespace
3285 
3286 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3287 
3288 /// Perform a compound assignment of LVal <op>= RVal.
3289 static bool handleCompoundAssignment(
3290     EvalInfo &Info, const Expr *E,
3291     const LValue &LVal, QualType LValType, QualType PromotedLValType,
3292     BinaryOperatorKind Opcode, const APValue &RVal) {
3293   if (LVal.Designator.Invalid)
3294     return false;
3295 
3296   if (!Info.getLangOpts().CPlusPlus14) {
3297     Info.FFDiag(E);
3298     return false;
3299   }
3300 
3301   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3302   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3303                                              RVal };
3304   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3305 }
3306 
3307 namespace {
3308 struct IncDecSubobjectHandler {
3309   EvalInfo &Info;
3310   const Expr *E;
3311   AccessKinds AccessKind;
3312   APValue *Old;
3313 
3314   typedef bool result_type;
3315 
3316   bool checkConst(QualType QT) {
3317     // Assigning to a const object has undefined behavior.
3318     if (QT.isConstQualified()) {
3319       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3320       return false;
3321     }
3322     return true;
3323   }
3324 
3325   bool failed() { return false; }
3326   bool found(APValue &Subobj, QualType SubobjType) {
3327     // Stash the old value. Also clear Old, so we don't clobber it later
3328     // if we're post-incrementing a complex.
3329     if (Old) {
3330       *Old = Subobj;
3331       Old = nullptr;
3332     }
3333 
3334     switch (Subobj.getKind()) {
3335     case APValue::Int:
3336       return found(Subobj.getInt(), SubobjType);
3337     case APValue::Float:
3338       return found(Subobj.getFloat(), SubobjType);
3339     case APValue::ComplexInt:
3340       return found(Subobj.getComplexIntReal(),
3341                    SubobjType->castAs<ComplexType>()->getElementType()
3342                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3343     case APValue::ComplexFloat:
3344       return found(Subobj.getComplexFloatReal(),
3345                    SubobjType->castAs<ComplexType>()->getElementType()
3346                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3347     case APValue::LValue:
3348       return foundPointer(Subobj, SubobjType);
3349     default:
3350       // FIXME: can this happen?
3351       Info.FFDiag(E);
3352       return false;
3353     }
3354   }
3355   bool found(APSInt &Value, QualType SubobjType) {
3356     if (!checkConst(SubobjType))
3357       return false;
3358 
3359     if (!SubobjType->isIntegerType()) {
3360       // We don't support increment / decrement on integer-cast-to-pointer
3361       // values.
3362       Info.FFDiag(E);
3363       return false;
3364     }
3365 
3366     if (Old) *Old = APValue(Value);
3367 
3368     // bool arithmetic promotes to int, and the conversion back to bool
3369     // doesn't reduce mod 2^n, so special-case it.
3370     if (SubobjType->isBooleanType()) {
3371       if (AccessKind == AK_Increment)
3372         Value = 1;
3373       else
3374         Value = !Value;
3375       return true;
3376     }
3377 
3378     bool WasNegative = Value.isNegative();
3379     if (AccessKind == AK_Increment) {
3380       ++Value;
3381 
3382       if (!WasNegative && Value.isNegative() &&
3383           isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3384         APSInt ActualValue(Value, /*IsUnsigned*/true);
3385         return HandleOverflow(Info, E, ActualValue, SubobjType);
3386       }
3387     } else {
3388       --Value;
3389 
3390       if (WasNegative && !Value.isNegative() &&
3391           isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3392         unsigned BitWidth = Value.getBitWidth();
3393         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3394         ActualValue.setBit(BitWidth);
3395         return HandleOverflow(Info, E, ActualValue, SubobjType);
3396       }
3397     }
3398     return true;
3399   }
3400   bool found(APFloat &Value, QualType SubobjType) {
3401     if (!checkConst(SubobjType))
3402       return false;
3403 
3404     if (Old) *Old = APValue(Value);
3405 
3406     APFloat One(Value.getSemantics(), 1);
3407     if (AccessKind == AK_Increment)
3408       Value.add(One, APFloat::rmNearestTiesToEven);
3409     else
3410       Value.subtract(One, APFloat::rmNearestTiesToEven);
3411     return true;
3412   }
3413   bool foundPointer(APValue &Subobj, QualType SubobjType) {
3414     if (!checkConst(SubobjType))
3415       return false;
3416 
3417     QualType PointeeType;
3418     if (const PointerType *PT = SubobjType->getAs<PointerType>())
3419       PointeeType = PT->getPointeeType();
3420     else {
3421       Info.FFDiag(E);
3422       return false;
3423     }
3424 
3425     LValue LVal;
3426     LVal.setFrom(Info.Ctx, Subobj);
3427     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3428                                      AccessKind == AK_Increment ? 1 : -1))
3429       return false;
3430     LVal.moveInto(Subobj);
3431     return true;
3432   }
3433   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3434     llvm_unreachable("shouldn't encounter string elements here");
3435   }
3436 };
3437 } // end anonymous namespace
3438 
3439 /// Perform an increment or decrement on LVal.
3440 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3441                          QualType LValType, bool IsIncrement, APValue *Old) {
3442   if (LVal.Designator.Invalid)
3443     return false;
3444 
3445   if (!Info.getLangOpts().CPlusPlus14) {
3446     Info.FFDiag(E);
3447     return false;
3448   }
3449 
3450   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3451   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3452   IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3453   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3454 }
3455 
3456 /// Build an lvalue for the object argument of a member function call.
3457 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3458                                    LValue &This) {
3459   if (Object->getType()->isPointerType())
3460     return EvaluatePointer(Object, This, Info);
3461 
3462   if (Object->isGLValue())
3463     return EvaluateLValue(Object, This, Info);
3464 
3465   if (Object->getType()->isLiteralType(Info.Ctx))
3466     return EvaluateTemporary(Object, This, Info);
3467 
3468   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3469   return false;
3470 }
3471 
3472 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3473 /// lvalue referring to the result.
3474 ///
3475 /// \param Info - Information about the ongoing evaluation.
3476 /// \param LV - An lvalue referring to the base of the member pointer.
3477 /// \param RHS - The member pointer expression.
3478 /// \param IncludeMember - Specifies whether the member itself is included in
3479 ///        the resulting LValue subobject designator. This is not possible when
3480 ///        creating a bound member function.
3481 /// \return The field or method declaration to which the member pointer refers,
3482 ///         or 0 if evaluation fails.
3483 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3484                                                   QualType LVType,
3485                                                   LValue &LV,
3486                                                   const Expr *RHS,
3487                                                   bool IncludeMember = true) {
3488   MemberPtr MemPtr;
3489   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3490     return nullptr;
3491 
3492   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3493   // member value, the behavior is undefined.
3494   if (!MemPtr.getDecl()) {
3495     // FIXME: Specific diagnostic.
3496     Info.FFDiag(RHS);
3497     return nullptr;
3498   }
3499 
3500   if (MemPtr.isDerivedMember()) {
3501     // This is a member of some derived class. Truncate LV appropriately.
3502     // The end of the derived-to-base path for the base object must match the
3503     // derived-to-base path for the member pointer.
3504     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3505         LV.Designator.Entries.size()) {
3506       Info.FFDiag(RHS);
3507       return nullptr;
3508     }
3509     unsigned PathLengthToMember =
3510         LV.Designator.Entries.size() - MemPtr.Path.size();
3511     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3512       const CXXRecordDecl *LVDecl = getAsBaseClass(
3513           LV.Designator.Entries[PathLengthToMember + I]);
3514       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3515       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3516         Info.FFDiag(RHS);
3517         return nullptr;
3518       }
3519     }
3520 
3521     // Truncate the lvalue to the appropriate derived class.
3522     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3523                             PathLengthToMember))
3524       return nullptr;
3525   } else if (!MemPtr.Path.empty()) {
3526     // Extend the LValue path with the member pointer's path.
3527     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3528                                   MemPtr.Path.size() + IncludeMember);
3529 
3530     // Walk down to the appropriate base class.
3531     if (const PointerType *PT = LVType->getAs<PointerType>())
3532       LVType = PT->getPointeeType();
3533     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3534     assert(RD && "member pointer access on non-class-type expression");
3535     // The first class in the path is that of the lvalue.
3536     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3537       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3538       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3539         return nullptr;
3540       RD = Base;
3541     }
3542     // Finally cast to the class containing the member.
3543     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3544                                 MemPtr.getContainingRecord()))
3545       return nullptr;
3546   }
3547 
3548   // Add the member. Note that we cannot build bound member functions here.
3549   if (IncludeMember) {
3550     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3551       if (!HandleLValueMember(Info, RHS, LV, FD))
3552         return nullptr;
3553     } else if (const IndirectFieldDecl *IFD =
3554                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3555       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3556         return nullptr;
3557     } else {
3558       llvm_unreachable("can't construct reference to bound member function");
3559     }
3560   }
3561 
3562   return MemPtr.getDecl();
3563 }
3564 
3565 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3566                                                   const BinaryOperator *BO,
3567                                                   LValue &LV,
3568                                                   bool IncludeMember = true) {
3569   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3570 
3571   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3572     if (Info.noteFailure()) {
3573       MemberPtr MemPtr;
3574       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3575     }
3576     return nullptr;
3577   }
3578 
3579   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3580                                    BO->getRHS(), IncludeMember);
3581 }
3582 
3583 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3584 /// the provided lvalue, which currently refers to the base object.
3585 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3586                                     LValue &Result) {
3587   SubobjectDesignator &D = Result.Designator;
3588   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3589     return false;
3590 
3591   QualType TargetQT = E->getType();
3592   if (const PointerType *PT = TargetQT->getAs<PointerType>())
3593     TargetQT = PT->getPointeeType();
3594 
3595   // Check this cast lands within the final derived-to-base subobject path.
3596   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3597     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3598       << D.MostDerivedType << TargetQT;
3599     return false;
3600   }
3601 
3602   // Check the type of the final cast. We don't need to check the path,
3603   // since a cast can only be formed if the path is unique.
3604   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3605   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3606   const CXXRecordDecl *FinalType;
3607   if (NewEntriesSize == D.MostDerivedPathLength)
3608     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3609   else
3610     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3611   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3612     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3613       << D.MostDerivedType << TargetQT;
3614     return false;
3615   }
3616 
3617   // Truncate the lvalue to the appropriate derived class.
3618   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3619 }
3620 
3621 namespace {
3622 enum EvalStmtResult {
3623   /// Evaluation failed.
3624   ESR_Failed,
3625   /// Hit a 'return' statement.
3626   ESR_Returned,
3627   /// Evaluation succeeded.
3628   ESR_Succeeded,
3629   /// Hit a 'continue' statement.
3630   ESR_Continue,
3631   /// Hit a 'break' statement.
3632   ESR_Break,
3633   /// Still scanning for 'case' or 'default' statement.
3634   ESR_CaseNotFound
3635 };
3636 }
3637 
3638 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3639   // We don't need to evaluate the initializer for a static local.
3640   if (!VD->hasLocalStorage())
3641     return true;
3642 
3643   LValue Result;
3644   Result.set(VD, Info.CurrentCall->Index);
3645   APValue &Val = Info.CurrentCall->createTemporary(VD, true);
3646 
3647   const Expr *InitE = VD->getInit();
3648   if (!InitE) {
3649     Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3650       << false << VD->getType();
3651     Val = APValue();
3652     return false;
3653   }
3654 
3655   if (InitE->isValueDependent())
3656     return false;
3657 
3658   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3659     // Wipe out any partially-computed value, to allow tracking that this
3660     // evaluation failed.
3661     Val = APValue();
3662     return false;
3663   }
3664 
3665   return true;
3666 }
3667 
3668 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3669   bool OK = true;
3670 
3671   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3672     OK &= EvaluateVarDecl(Info, VD);
3673 
3674   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3675     for (auto *BD : DD->bindings())
3676       if (auto *VD = BD->getHoldingVar())
3677         OK &= EvaluateDecl(Info, VD);
3678 
3679   return OK;
3680 }
3681 
3682 
3683 /// Evaluate a condition (either a variable declaration or an expression).
3684 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3685                          const Expr *Cond, bool &Result) {
3686   FullExpressionRAII Scope(Info);
3687   if (CondDecl && !EvaluateDecl(Info, CondDecl))
3688     return false;
3689   return EvaluateAsBooleanCondition(Cond, Result, Info);
3690 }
3691 
3692 namespace {
3693 /// \brief A location where the result (returned value) of evaluating a
3694 /// statement should be stored.
3695 struct StmtResult {
3696   /// The APValue that should be filled in with the returned value.
3697   APValue &Value;
3698   /// The location containing the result, if any (used to support RVO).
3699   const LValue *Slot;
3700 };
3701 }
3702 
3703 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3704                                    const Stmt *S,
3705                                    const SwitchCase *SC = nullptr);
3706 
3707 /// Evaluate the body of a loop, and translate the result as appropriate.
3708 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
3709                                        const Stmt *Body,
3710                                        const SwitchCase *Case = nullptr) {
3711   BlockScopeRAII Scope(Info);
3712   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3713   case ESR_Break:
3714     return ESR_Succeeded;
3715   case ESR_Succeeded:
3716   case ESR_Continue:
3717     return ESR_Continue;
3718   case ESR_Failed:
3719   case ESR_Returned:
3720   case ESR_CaseNotFound:
3721     return ESR;
3722   }
3723   llvm_unreachable("Invalid EvalStmtResult!");
3724 }
3725 
3726 /// Evaluate a switch statement.
3727 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
3728                                      const SwitchStmt *SS) {
3729   BlockScopeRAII Scope(Info);
3730 
3731   // Evaluate the switch condition.
3732   APSInt Value;
3733   {
3734     FullExpressionRAII Scope(Info);
3735     if (const Stmt *Init = SS->getInit()) {
3736       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3737       if (ESR != ESR_Succeeded)
3738         return ESR;
3739     }
3740     if (SS->getConditionVariable() &&
3741         !EvaluateDecl(Info, SS->getConditionVariable()))
3742       return ESR_Failed;
3743     if (!EvaluateInteger(SS->getCond(), Value, Info))
3744       return ESR_Failed;
3745   }
3746 
3747   // Find the switch case corresponding to the value of the condition.
3748   // FIXME: Cache this lookup.
3749   const SwitchCase *Found = nullptr;
3750   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3751        SC = SC->getNextSwitchCase()) {
3752     if (isa<DefaultStmt>(SC)) {
3753       Found = SC;
3754       continue;
3755     }
3756 
3757     const CaseStmt *CS = cast<CaseStmt>(SC);
3758     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3759     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3760                               : LHS;
3761     if (LHS <= Value && Value <= RHS) {
3762       Found = SC;
3763       break;
3764     }
3765   }
3766 
3767   if (!Found)
3768     return ESR_Succeeded;
3769 
3770   // Search the switch body for the switch case and evaluate it from there.
3771   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3772   case ESR_Break:
3773     return ESR_Succeeded;
3774   case ESR_Succeeded:
3775   case ESR_Continue:
3776   case ESR_Failed:
3777   case ESR_Returned:
3778     return ESR;
3779   case ESR_CaseNotFound:
3780     // This can only happen if the switch case is nested within a statement
3781     // expression. We have no intention of supporting that.
3782     Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3783     return ESR_Failed;
3784   }
3785   llvm_unreachable("Invalid EvalStmtResult!");
3786 }
3787 
3788 // Evaluate a statement.
3789 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3790                                    const Stmt *S, const SwitchCase *Case) {
3791   if (!Info.nextStep(S))
3792     return ESR_Failed;
3793 
3794   // If we're hunting down a 'case' or 'default' label, recurse through
3795   // substatements until we hit the label.
3796   if (Case) {
3797     // FIXME: We don't start the lifetime of objects whose initialization we
3798     // jump over. However, such objects must be of class type with a trivial
3799     // default constructor that initialize all subobjects, so must be empty,
3800     // so this almost never matters.
3801     switch (S->getStmtClass()) {
3802     case Stmt::CompoundStmtClass:
3803       // FIXME: Precompute which substatement of a compound statement we
3804       // would jump to, and go straight there rather than performing a
3805       // linear scan each time.
3806     case Stmt::LabelStmtClass:
3807     case Stmt::AttributedStmtClass:
3808     case Stmt::DoStmtClass:
3809       break;
3810 
3811     case Stmt::CaseStmtClass:
3812     case Stmt::DefaultStmtClass:
3813       if (Case == S)
3814         Case = nullptr;
3815       break;
3816 
3817     case Stmt::IfStmtClass: {
3818       // FIXME: Precompute which side of an 'if' we would jump to, and go
3819       // straight there rather than scanning both sides.
3820       const IfStmt *IS = cast<IfStmt>(S);
3821 
3822       // Wrap the evaluation in a block scope, in case it's a DeclStmt
3823       // preceded by our switch label.
3824       BlockScopeRAII Scope(Info);
3825 
3826       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3827       if (ESR != ESR_CaseNotFound || !IS->getElse())
3828         return ESR;
3829       return EvaluateStmt(Result, Info, IS->getElse(), Case);
3830     }
3831 
3832     case Stmt::WhileStmtClass: {
3833       EvalStmtResult ESR =
3834           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3835       if (ESR != ESR_Continue)
3836         return ESR;
3837       break;
3838     }
3839 
3840     case Stmt::ForStmtClass: {
3841       const ForStmt *FS = cast<ForStmt>(S);
3842       EvalStmtResult ESR =
3843           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3844       if (ESR != ESR_Continue)
3845         return ESR;
3846       if (FS->getInc()) {
3847         FullExpressionRAII IncScope(Info);
3848         if (!EvaluateIgnoredValue(Info, FS->getInc()))
3849           return ESR_Failed;
3850       }
3851       break;
3852     }
3853 
3854     case Stmt::DeclStmtClass:
3855       // FIXME: If the variable has initialization that can't be jumped over,
3856       // bail out of any immediately-surrounding compound-statement too.
3857     default:
3858       return ESR_CaseNotFound;
3859     }
3860   }
3861 
3862   switch (S->getStmtClass()) {
3863   default:
3864     if (const Expr *E = dyn_cast<Expr>(S)) {
3865       // Don't bother evaluating beyond an expression-statement which couldn't
3866       // be evaluated.
3867       FullExpressionRAII Scope(Info);
3868       if (!EvaluateIgnoredValue(Info, E))
3869         return ESR_Failed;
3870       return ESR_Succeeded;
3871     }
3872 
3873     Info.FFDiag(S->getLocStart());
3874     return ESR_Failed;
3875 
3876   case Stmt::NullStmtClass:
3877     return ESR_Succeeded;
3878 
3879   case Stmt::DeclStmtClass: {
3880     const DeclStmt *DS = cast<DeclStmt>(S);
3881     for (const auto *DclIt : DS->decls()) {
3882       // Each declaration initialization is its own full-expression.
3883       // FIXME: This isn't quite right; if we're performing aggregate
3884       // initialization, each braced subexpression is its own full-expression.
3885       FullExpressionRAII Scope(Info);
3886       if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
3887         return ESR_Failed;
3888     }
3889     return ESR_Succeeded;
3890   }
3891 
3892   case Stmt::ReturnStmtClass: {
3893     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
3894     FullExpressionRAII Scope(Info);
3895     if (RetExpr &&
3896         !(Result.Slot
3897               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3898               : Evaluate(Result.Value, Info, RetExpr)))
3899       return ESR_Failed;
3900     return ESR_Returned;
3901   }
3902 
3903   case Stmt::CompoundStmtClass: {
3904     BlockScopeRAII Scope(Info);
3905 
3906     const CompoundStmt *CS = cast<CompoundStmt>(S);
3907     for (const auto *BI : CS->body()) {
3908       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
3909       if (ESR == ESR_Succeeded)
3910         Case = nullptr;
3911       else if (ESR != ESR_CaseNotFound)
3912         return ESR;
3913     }
3914     return Case ? ESR_CaseNotFound : ESR_Succeeded;
3915   }
3916 
3917   case Stmt::IfStmtClass: {
3918     const IfStmt *IS = cast<IfStmt>(S);
3919 
3920     // Evaluate the condition, as either a var decl or as an expression.
3921     BlockScopeRAII Scope(Info);
3922     if (const Stmt *Init = IS->getInit()) {
3923       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3924       if (ESR != ESR_Succeeded)
3925         return ESR;
3926     }
3927     bool Cond;
3928     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
3929       return ESR_Failed;
3930 
3931     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3932       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3933       if (ESR != ESR_Succeeded)
3934         return ESR;
3935     }
3936     return ESR_Succeeded;
3937   }
3938 
3939   case Stmt::WhileStmtClass: {
3940     const WhileStmt *WS = cast<WhileStmt>(S);
3941     while (true) {
3942       BlockScopeRAII Scope(Info);
3943       bool Continue;
3944       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3945                         Continue))
3946         return ESR_Failed;
3947       if (!Continue)
3948         break;
3949 
3950       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3951       if (ESR != ESR_Continue)
3952         return ESR;
3953     }
3954     return ESR_Succeeded;
3955   }
3956 
3957   case Stmt::DoStmtClass: {
3958     const DoStmt *DS = cast<DoStmt>(S);
3959     bool Continue;
3960     do {
3961       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
3962       if (ESR != ESR_Continue)
3963         return ESR;
3964       Case = nullptr;
3965 
3966       FullExpressionRAII CondScope(Info);
3967       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3968         return ESR_Failed;
3969     } while (Continue);
3970     return ESR_Succeeded;
3971   }
3972 
3973   case Stmt::ForStmtClass: {
3974     const ForStmt *FS = cast<ForStmt>(S);
3975     BlockScopeRAII Scope(Info);
3976     if (FS->getInit()) {
3977       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3978       if (ESR != ESR_Succeeded)
3979         return ESR;
3980     }
3981     while (true) {
3982       BlockScopeRAII Scope(Info);
3983       bool Continue = true;
3984       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3985                                          FS->getCond(), Continue))
3986         return ESR_Failed;
3987       if (!Continue)
3988         break;
3989 
3990       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3991       if (ESR != ESR_Continue)
3992         return ESR;
3993 
3994       if (FS->getInc()) {
3995         FullExpressionRAII IncScope(Info);
3996         if (!EvaluateIgnoredValue(Info, FS->getInc()))
3997           return ESR_Failed;
3998       }
3999     }
4000     return ESR_Succeeded;
4001   }
4002 
4003   case Stmt::CXXForRangeStmtClass: {
4004     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4005     BlockScopeRAII Scope(Info);
4006 
4007     // Initialize the __range variable.
4008     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4009     if (ESR != ESR_Succeeded)
4010       return ESR;
4011 
4012     // Create the __begin and __end iterators.
4013     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4014     if (ESR != ESR_Succeeded)
4015       return ESR;
4016     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4017     if (ESR != ESR_Succeeded)
4018       return ESR;
4019 
4020     while (true) {
4021       // Condition: __begin != __end.
4022       {
4023         bool Continue = true;
4024         FullExpressionRAII CondExpr(Info);
4025         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4026           return ESR_Failed;
4027         if (!Continue)
4028           break;
4029       }
4030 
4031       // User's variable declaration, initialized by *__begin.
4032       BlockScopeRAII InnerScope(Info);
4033       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4034       if (ESR != ESR_Succeeded)
4035         return ESR;
4036 
4037       // Loop body.
4038       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4039       if (ESR != ESR_Continue)
4040         return ESR;
4041 
4042       // Increment: ++__begin
4043       if (!EvaluateIgnoredValue(Info, FS->getInc()))
4044         return ESR_Failed;
4045     }
4046 
4047     return ESR_Succeeded;
4048   }
4049 
4050   case Stmt::SwitchStmtClass:
4051     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4052 
4053   case Stmt::ContinueStmtClass:
4054     return ESR_Continue;
4055 
4056   case Stmt::BreakStmtClass:
4057     return ESR_Break;
4058 
4059   case Stmt::LabelStmtClass:
4060     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4061 
4062   case Stmt::AttributedStmtClass:
4063     // As a general principle, C++11 attributes can be ignored without
4064     // any semantic impact.
4065     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4066                         Case);
4067 
4068   case Stmt::CaseStmtClass:
4069   case Stmt::DefaultStmtClass:
4070     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4071   }
4072 }
4073 
4074 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4075 /// default constructor. If so, we'll fold it whether or not it's marked as
4076 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4077 /// so we need special handling.
4078 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4079                                            const CXXConstructorDecl *CD,
4080                                            bool IsValueInitialization) {
4081   if (!CD->isTrivial() || !CD->isDefaultConstructor())
4082     return false;
4083 
4084   // Value-initialization does not call a trivial default constructor, so such a
4085   // call is a core constant expression whether or not the constructor is
4086   // constexpr.
4087   if (!CD->isConstexpr() && !IsValueInitialization) {
4088     if (Info.getLangOpts().CPlusPlus11) {
4089       // FIXME: If DiagDecl is an implicitly-declared special member function,
4090       // we should be much more explicit about why it's not constexpr.
4091       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4092         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4093       Info.Note(CD->getLocation(), diag::note_declared_at);
4094     } else {
4095       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4096     }
4097   }
4098   return true;
4099 }
4100 
4101 /// CheckConstexprFunction - Check that a function can be called in a constant
4102 /// expression.
4103 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4104                                    const FunctionDecl *Declaration,
4105                                    const FunctionDecl *Definition,
4106                                    const Stmt *Body) {
4107   // Potential constant expressions can contain calls to declared, but not yet
4108   // defined, constexpr functions.
4109   if (Info.checkingPotentialConstantExpression() && !Definition &&
4110       Declaration->isConstexpr())
4111     return false;
4112 
4113   // Bail out with no diagnostic if the function declaration itself is invalid.
4114   // We will have produced a relevant diagnostic while parsing it.
4115   if (Declaration->isInvalidDecl())
4116     return false;
4117 
4118   // Can we evaluate this function call?
4119   if (Definition && Definition->isConstexpr() &&
4120       !Definition->isInvalidDecl() && Body)
4121     return true;
4122 
4123   if (Info.getLangOpts().CPlusPlus11) {
4124     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4125 
4126     // If this function is not constexpr because it is an inherited
4127     // non-constexpr constructor, diagnose that directly.
4128     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4129     if (CD && CD->isInheritingConstructor()) {
4130       auto *Inherited = CD->getInheritedConstructor().getConstructor();
4131       if (!Inherited->isConstexpr())
4132         DiagDecl = CD = Inherited;
4133     }
4134 
4135     // FIXME: If DiagDecl is an implicitly-declared special member function
4136     // or an inheriting constructor, we should be much more explicit about why
4137     // it's not constexpr.
4138     if (CD && CD->isInheritingConstructor())
4139       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4140         << CD->getInheritedConstructor().getConstructor()->getParent();
4141     else
4142       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4143         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4144     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4145   } else {
4146     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4147   }
4148   return false;
4149 }
4150 
4151 /// Determine if a class has any fields that might need to be copied by a
4152 /// trivial copy or move operation.
4153 static bool hasFields(const CXXRecordDecl *RD) {
4154   if (!RD || RD->isEmpty())
4155     return false;
4156   for (auto *FD : RD->fields()) {
4157     if (FD->isUnnamedBitfield())
4158       continue;
4159     return true;
4160   }
4161   for (auto &Base : RD->bases())
4162     if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4163       return true;
4164   return false;
4165 }
4166 
4167 namespace {
4168 typedef SmallVector<APValue, 8> ArgVector;
4169 }
4170 
4171 /// EvaluateArgs - Evaluate the arguments to a function call.
4172 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4173                          EvalInfo &Info) {
4174   bool Success = true;
4175   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
4176        I != E; ++I) {
4177     if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4178       // If we're checking for a potential constant expression, evaluate all
4179       // initializers even if some of them fail.
4180       if (!Info.noteFailure())
4181         return false;
4182       Success = false;
4183     }
4184   }
4185   return Success;
4186 }
4187 
4188 /// Evaluate a function call.
4189 static bool HandleFunctionCall(SourceLocation CallLoc,
4190                                const FunctionDecl *Callee, const LValue *This,
4191                                ArrayRef<const Expr*> Args, const Stmt *Body,
4192                                EvalInfo &Info, APValue &Result,
4193                                const LValue *ResultSlot) {
4194   ArgVector ArgValues(Args.size());
4195   if (!EvaluateArgs(Args, ArgValues, Info))
4196     return false;
4197 
4198   if (!Info.CheckCallLimit(CallLoc))
4199     return false;
4200 
4201   CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
4202 
4203   // For a trivial copy or move assignment, perform an APValue copy. This is
4204   // essential for unions, where the operations performed by the assignment
4205   // operator cannot be represented as statements.
4206   //
4207   // Skip this for non-union classes with no fields; in that case, the defaulted
4208   // copy/move does not actually read the object.
4209   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
4210   if (MD && MD->isDefaulted() &&
4211       (MD->getParent()->isUnion() ||
4212        (MD->isTrivial() && hasFields(MD->getParent())))) {
4213     assert(This &&
4214            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4215     LValue RHS;
4216     RHS.setFrom(Info.Ctx, ArgValues[0]);
4217     APValue RHSValue;
4218     if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4219                                         RHS, RHSValue))
4220       return false;
4221     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4222                           RHSValue))
4223       return false;
4224     This->moveInto(Result);
4225     return true;
4226   } else if (MD && isLambdaCallOperator(MD)) {
4227     // We're in a lambda; determine the lambda capture field maps.
4228     MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4229                                       Frame.LambdaThisCaptureField);
4230   }
4231 
4232   StmtResult Ret = {Result, ResultSlot};
4233   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
4234   if (ESR == ESR_Succeeded) {
4235     if (Callee->getReturnType()->isVoidType())
4236       return true;
4237     Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
4238   }
4239   return ESR == ESR_Returned;
4240 }
4241 
4242 /// Evaluate a constructor call.
4243 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4244                                   APValue *ArgValues,
4245                                   const CXXConstructorDecl *Definition,
4246                                   EvalInfo &Info, APValue &Result) {
4247   SourceLocation CallLoc = E->getExprLoc();
4248   if (!Info.CheckCallLimit(CallLoc))
4249     return false;
4250 
4251   const CXXRecordDecl *RD = Definition->getParent();
4252   if (RD->getNumVBases()) {
4253     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
4254     return false;
4255   }
4256 
4257   CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
4258 
4259   // FIXME: Creating an APValue just to hold a nonexistent return value is
4260   // wasteful.
4261   APValue RetVal;
4262   StmtResult Ret = {RetVal, nullptr};
4263 
4264   // If it's a delegating constructor, delegate.
4265   if (Definition->isDelegatingConstructor()) {
4266     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
4267     {
4268       FullExpressionRAII InitScope(Info);
4269       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4270         return false;
4271     }
4272     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4273   }
4274 
4275   // For a trivial copy or move constructor, perform an APValue copy. This is
4276   // essential for unions (or classes with anonymous union members), where the
4277   // operations performed by the constructor cannot be represented by
4278   // ctor-initializers.
4279   //
4280   // Skip this for empty non-union classes; we should not perform an
4281   // lvalue-to-rvalue conversion on them because their copy constructor does not
4282   // actually read them.
4283   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
4284       (Definition->getParent()->isUnion() ||
4285        (Definition->isTrivial() && hasFields(Definition->getParent())))) {
4286     LValue RHS;
4287     RHS.setFrom(Info.Ctx, ArgValues[0]);
4288     return handleLValueToRValueConversion(
4289         Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4290         RHS, Result);
4291   }
4292 
4293   // Reserve space for the struct members.
4294   if (!RD->isUnion() && Result.isUninit())
4295     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4296                      std::distance(RD->field_begin(), RD->field_end()));
4297 
4298   if (RD->isInvalidDecl()) return false;
4299   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4300 
4301   // A scope for temporaries lifetime-extended by reference members.
4302   BlockScopeRAII LifetimeExtendedScope(Info);
4303 
4304   bool Success = true;
4305   unsigned BasesSeen = 0;
4306 #ifndef NDEBUG
4307   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4308 #endif
4309   for (const auto *I : Definition->inits()) {
4310     LValue Subobject = This;
4311     APValue *Value = &Result;
4312 
4313     // Determine the subobject to initialize.
4314     FieldDecl *FD = nullptr;
4315     if (I->isBaseInitializer()) {
4316       QualType BaseType(I->getBaseClass(), 0);
4317 #ifndef NDEBUG
4318       // Non-virtual base classes are initialized in the order in the class
4319       // definition. We have already checked for virtual base classes.
4320       assert(!BaseIt->isVirtual() && "virtual base for literal type");
4321       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4322              "base class initializers not in expected order");
4323       ++BaseIt;
4324 #endif
4325       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
4326                                   BaseType->getAsCXXRecordDecl(), &Layout))
4327         return false;
4328       Value = &Result.getStructBase(BasesSeen++);
4329     } else if ((FD = I->getMember())) {
4330       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
4331         return false;
4332       if (RD->isUnion()) {
4333         Result = APValue(FD);
4334         Value = &Result.getUnionValue();
4335       } else {
4336         Value = &Result.getStructField(FD->getFieldIndex());
4337       }
4338     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
4339       // Walk the indirect field decl's chain to find the object to initialize,
4340       // and make sure we've initialized every step along it.
4341       for (auto *C : IFD->chain()) {
4342         FD = cast<FieldDecl>(C);
4343         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4344         // Switch the union field if it differs. This happens if we had
4345         // preceding zero-initialization, and we're now initializing a union
4346         // subobject other than the first.
4347         // FIXME: In this case, the values of the other subobjects are
4348         // specified, since zero-initialization sets all padding bits to zero.
4349         if (Value->isUninit() ||
4350             (Value->isUnion() && Value->getUnionField() != FD)) {
4351           if (CD->isUnion())
4352             *Value = APValue(FD);
4353           else
4354             *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
4355                              std::distance(CD->field_begin(), CD->field_end()));
4356         }
4357         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
4358           return false;
4359         if (CD->isUnion())
4360           Value = &Value->getUnionValue();
4361         else
4362           Value = &Value->getStructField(FD->getFieldIndex());
4363       }
4364     } else {
4365       llvm_unreachable("unknown base initializer kind");
4366     }
4367 
4368     FullExpressionRAII InitScope(Info);
4369     if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4370         (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
4371                                                           *Value, FD))) {
4372       // If we're checking for a potential constant expression, evaluate all
4373       // initializers even if some of them fail.
4374       if (!Info.noteFailure())
4375         return false;
4376       Success = false;
4377     }
4378   }
4379 
4380   return Success &&
4381          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4382 }
4383 
4384 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4385                                   ArrayRef<const Expr*> Args,
4386                                   const CXXConstructorDecl *Definition,
4387                                   EvalInfo &Info, APValue &Result) {
4388   ArgVector ArgValues(Args.size());
4389   if (!EvaluateArgs(Args, ArgValues, Info))
4390     return false;
4391 
4392   return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4393                                Info, Result);
4394 }
4395 
4396 //===----------------------------------------------------------------------===//
4397 // Generic Evaluation
4398 //===----------------------------------------------------------------------===//
4399 namespace {
4400 
4401 template <class Derived>
4402 class ExprEvaluatorBase
4403   : public ConstStmtVisitor<Derived, bool> {
4404 private:
4405   Derived &getDerived() { return static_cast<Derived&>(*this); }
4406   bool DerivedSuccess(const APValue &V, const Expr *E) {
4407     return getDerived().Success(V, E);
4408   }
4409   bool DerivedZeroInitialization(const Expr *E) {
4410     return getDerived().ZeroInitialization(E);
4411   }
4412 
4413   // Check whether a conditional operator with a non-constant condition is a
4414   // potential constant expression. If neither arm is a potential constant
4415   // expression, then the conditional operator is not either.
4416   template<typename ConditionalOperator>
4417   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
4418     assert(Info.checkingPotentialConstantExpression());
4419 
4420     // Speculatively evaluate both arms.
4421     SmallVector<PartialDiagnosticAt, 8> Diag;
4422     {
4423       SpeculativeEvaluationRAII Speculate(Info, &Diag);
4424       StmtVisitorTy::Visit(E->getFalseExpr());
4425       if (Diag.empty())
4426         return;
4427     }
4428 
4429     {
4430       SpeculativeEvaluationRAII Speculate(Info, &Diag);
4431       Diag.clear();
4432       StmtVisitorTy::Visit(E->getTrueExpr());
4433       if (Diag.empty())
4434         return;
4435     }
4436 
4437     Error(E, diag::note_constexpr_conditional_never_const);
4438   }
4439 
4440 
4441   template<typename ConditionalOperator>
4442   bool HandleConditionalOperator(const ConditionalOperator *E) {
4443     bool BoolResult;
4444     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
4445       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
4446         CheckPotentialConstantConditional(E);
4447         return false;
4448       }
4449       if (Info.noteFailure()) {
4450         StmtVisitorTy::Visit(E->getTrueExpr());
4451         StmtVisitorTy::Visit(E->getFalseExpr());
4452       }
4453       return false;
4454     }
4455 
4456     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4457     return StmtVisitorTy::Visit(EvalExpr);
4458   }
4459 
4460 protected:
4461   EvalInfo &Info;
4462   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
4463   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4464 
4465   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4466     return Info.CCEDiag(E, D);
4467   }
4468 
4469   bool ZeroInitialization(const Expr *E) { return Error(E); }
4470 
4471 public:
4472   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4473 
4474   EvalInfo &getEvalInfo() { return Info; }
4475 
4476   /// Report an evaluation error. This should only be called when an error is
4477   /// first discovered. When propagating an error, just return false.
4478   bool Error(const Expr *E, diag::kind D) {
4479     Info.FFDiag(E, D);
4480     return false;
4481   }
4482   bool Error(const Expr *E) {
4483     return Error(E, diag::note_invalid_subexpr_in_const_expr);
4484   }
4485 
4486   bool VisitStmt(const Stmt *) {
4487     llvm_unreachable("Expression evaluator should not be called on stmts");
4488   }
4489   bool VisitExpr(const Expr *E) {
4490     return Error(E);
4491   }
4492 
4493   bool VisitParenExpr(const ParenExpr *E)
4494     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4495   bool VisitUnaryExtension(const UnaryOperator *E)
4496     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4497   bool VisitUnaryPlus(const UnaryOperator *E)
4498     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4499   bool VisitChooseExpr(const ChooseExpr *E)
4500     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
4501   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
4502     { return StmtVisitorTy::Visit(E->getResultExpr()); }
4503   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
4504     { return StmtVisitorTy::Visit(E->getReplacement()); }
4505   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
4506     { return StmtVisitorTy::Visit(E->getExpr()); }
4507   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
4508     // The initializer may not have been parsed yet, or might be erroneous.
4509     if (!E->getExpr())
4510       return Error(E);
4511     return StmtVisitorTy::Visit(E->getExpr());
4512   }
4513   // We cannot create any objects for which cleanups are required, so there is
4514   // nothing to do here; all cleanups must come from unevaluated subexpressions.
4515   bool VisitExprWithCleanups(const ExprWithCleanups *E)
4516     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4517 
4518   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
4519     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4520     return static_cast<Derived*>(this)->VisitCastExpr(E);
4521   }
4522   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
4523     CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4524     return static_cast<Derived*>(this)->VisitCastExpr(E);
4525   }
4526 
4527   bool VisitBinaryOperator(const BinaryOperator *E) {
4528     switch (E->getOpcode()) {
4529     default:
4530       return Error(E);
4531 
4532     case BO_Comma:
4533       VisitIgnoredValue(E->getLHS());
4534       return StmtVisitorTy::Visit(E->getRHS());
4535 
4536     case BO_PtrMemD:
4537     case BO_PtrMemI: {
4538       LValue Obj;
4539       if (!HandleMemberPointerAccess(Info, E, Obj))
4540         return false;
4541       APValue Result;
4542       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
4543         return false;
4544       return DerivedSuccess(Result, E);
4545     }
4546     }
4547   }
4548 
4549   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
4550     // Evaluate and cache the common expression. We treat it as a temporary,
4551     // even though it's not quite the same thing.
4552     if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
4553                   Info, E->getCommon()))
4554       return false;
4555 
4556     return HandleConditionalOperator(E);
4557   }
4558 
4559   bool VisitConditionalOperator(const ConditionalOperator *E) {
4560     bool IsBcpCall = false;
4561     // If the condition (ignoring parens) is a __builtin_constant_p call,
4562     // the result is a constant expression if it can be folded without
4563     // side-effects. This is an important GNU extension. See GCC PR38377
4564     // for discussion.
4565     if (const CallExpr *CallCE =
4566           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
4567       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
4568         IsBcpCall = true;
4569 
4570     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4571     // constant expression; we can't check whether it's potentially foldable.
4572     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
4573       return false;
4574 
4575     FoldConstant Fold(Info, IsBcpCall);
4576     if (!HandleConditionalOperator(E)) {
4577       Fold.keepDiagnostics();
4578       return false;
4579     }
4580 
4581     return true;
4582   }
4583 
4584   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
4585     if (APValue *Value = Info.CurrentCall->getTemporary(E))
4586       return DerivedSuccess(*Value, E);
4587 
4588     const Expr *Source = E->getSourceExpr();
4589     if (!Source)
4590       return Error(E);
4591     if (Source == E) { // sanity checking.
4592       assert(0 && "OpaqueValueExpr recursively refers to itself");
4593       return Error(E);
4594     }
4595     return StmtVisitorTy::Visit(Source);
4596   }
4597 
4598   bool VisitCallExpr(const CallExpr *E) {
4599     APValue Result;
4600     if (!handleCallExpr(E, Result, nullptr))
4601       return false;
4602     return DerivedSuccess(Result, E);
4603   }
4604 
4605   bool handleCallExpr(const CallExpr *E, APValue &Result,
4606                      const LValue *ResultSlot) {
4607     const Expr *Callee = E->getCallee()->IgnoreParens();
4608     QualType CalleeType = Callee->getType();
4609 
4610     const FunctionDecl *FD = nullptr;
4611     LValue *This = nullptr, ThisVal;
4612     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
4613     bool HasQualifier = false;
4614 
4615     // Extract function decl and 'this' pointer from the callee.
4616     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
4617       const ValueDecl *Member = nullptr;
4618       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4619         // Explicit bound member calls, such as x.f() or p->g();
4620         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
4621           return false;
4622         Member = ME->getMemberDecl();
4623         This = &ThisVal;
4624         HasQualifier = ME->hasQualifier();
4625       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4626         // Indirect bound member calls ('.*' or '->*').
4627         Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4628         if (!Member) return false;
4629         This = &ThisVal;
4630       } else
4631         return Error(Callee);
4632 
4633       FD = dyn_cast<FunctionDecl>(Member);
4634       if (!FD)
4635         return Error(Callee);
4636     } else if (CalleeType->isFunctionPointerType()) {
4637       LValue Call;
4638       if (!EvaluatePointer(Callee, Call, Info))
4639         return false;
4640 
4641       if (!Call.getLValueOffset().isZero())
4642         return Error(Callee);
4643       FD = dyn_cast_or_null<FunctionDecl>(
4644                              Call.getLValueBase().dyn_cast<const ValueDecl*>());
4645       if (!FD)
4646         return Error(Callee);
4647       // Don't call function pointers which have been cast to some other type.
4648       // Per DR (no number yet), the caller and callee can differ in noexcept.
4649       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4650         CalleeType->getPointeeType(), FD->getType())) {
4651         return Error(E);
4652       }
4653 
4654       // Overloaded operator calls to member functions are represented as normal
4655       // calls with '*this' as the first argument.
4656       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4657       if (MD && !MD->isStatic()) {
4658         // FIXME: When selecting an implicit conversion for an overloaded
4659         // operator delete, we sometimes try to evaluate calls to conversion
4660         // operators without a 'this' parameter!
4661         if (Args.empty())
4662           return Error(E);
4663 
4664         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4665           return false;
4666         This = &ThisVal;
4667         Args = Args.slice(1);
4668       } else if (MD && MD->isLambdaStaticInvoker()) {
4669         // Map the static invoker for the lambda back to the call operator.
4670         // Conveniently, we don't have to slice out the 'this' argument (as is
4671         // being done for the non-static case), since a static member function
4672         // doesn't have an implicit argument passed in.
4673         const CXXRecordDecl *ClosureClass = MD->getParent();
4674         assert(
4675             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4676             "Number of captures must be zero for conversion to function-ptr");
4677 
4678         const CXXMethodDecl *LambdaCallOp =
4679             ClosureClass->getLambdaCallOperator();
4680 
4681         // Set 'FD', the function that will be called below, to the call
4682         // operator.  If the closure object represents a generic lambda, find
4683         // the corresponding specialization of the call operator.
4684 
4685         if (ClosureClass->isGenericLambda()) {
4686           assert(MD->isFunctionTemplateSpecialization() &&
4687                  "A generic lambda's static-invoker function must be a "
4688                  "template specialization");
4689           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4690           FunctionTemplateDecl *CallOpTemplate =
4691               LambdaCallOp->getDescribedFunctionTemplate();
4692           void *InsertPos = nullptr;
4693           FunctionDecl *CorrespondingCallOpSpecialization =
4694               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4695           assert(CorrespondingCallOpSpecialization &&
4696                  "We must always have a function call operator specialization "
4697                  "that corresponds to our static invoker specialization");
4698           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4699         } else
4700           FD = LambdaCallOp;
4701       }
4702 
4703 
4704     } else
4705       return Error(E);
4706 
4707     if (This && !This->checkSubobject(Info, E, CSK_This))
4708       return false;
4709 
4710     // DR1358 allows virtual constexpr functions in some cases. Don't allow
4711     // calls to such functions in constant expressions.
4712     if (This && !HasQualifier &&
4713         isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4714       return Error(E, diag::note_constexpr_virtual_call);
4715 
4716     const FunctionDecl *Definition = nullptr;
4717     Stmt *Body = FD->getBody(Definition);
4718 
4719     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4720         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4721                             Result, ResultSlot))
4722       return false;
4723 
4724     return true;
4725   }
4726 
4727   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4728     return StmtVisitorTy::Visit(E->getInitializer());
4729   }
4730   bool VisitInitListExpr(const InitListExpr *E) {
4731     if (E->getNumInits() == 0)
4732       return DerivedZeroInitialization(E);
4733     if (E->getNumInits() == 1)
4734       return StmtVisitorTy::Visit(E->getInit(0));
4735     return Error(E);
4736   }
4737   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
4738     return DerivedZeroInitialization(E);
4739   }
4740   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
4741     return DerivedZeroInitialization(E);
4742   }
4743   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
4744     return DerivedZeroInitialization(E);
4745   }
4746 
4747   /// A member expression where the object is a prvalue is itself a prvalue.
4748   bool VisitMemberExpr(const MemberExpr *E) {
4749     assert(!E->isArrow() && "missing call to bound member function?");
4750 
4751     APValue Val;
4752     if (!Evaluate(Val, Info, E->getBase()))
4753       return false;
4754 
4755     QualType BaseTy = E->getBase()->getType();
4756 
4757     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
4758     if (!FD) return Error(E);
4759     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
4760     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4761            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4762 
4763     CompleteObject Obj(&Val, BaseTy);
4764     SubobjectDesignator Designator(BaseTy);
4765     Designator.addDeclUnchecked(FD);
4766 
4767     APValue Result;
4768     return extractSubobject(Info, E, Obj, Designator, Result) &&
4769            DerivedSuccess(Result, E);
4770   }
4771 
4772   bool VisitCastExpr(const CastExpr *E) {
4773     switch (E->getCastKind()) {
4774     default:
4775       break;
4776 
4777     case CK_AtomicToNonAtomic: {
4778       APValue AtomicVal;
4779       // This does not need to be done in place even for class/array types:
4780       // atomic-to-non-atomic conversion implies copying the object
4781       // representation.
4782       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
4783         return false;
4784       return DerivedSuccess(AtomicVal, E);
4785     }
4786 
4787     case CK_NoOp:
4788     case CK_UserDefinedConversion:
4789       return StmtVisitorTy::Visit(E->getSubExpr());
4790 
4791     case CK_LValueToRValue: {
4792       LValue LVal;
4793       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4794         return false;
4795       APValue RVal;
4796       // Note, we use the subexpression's type in order to retain cv-qualifiers.
4797       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
4798                                           LVal, RVal))
4799         return false;
4800       return DerivedSuccess(RVal, E);
4801     }
4802     }
4803 
4804     return Error(E);
4805   }
4806 
4807   bool VisitUnaryPostInc(const UnaryOperator *UO) {
4808     return VisitUnaryPostIncDec(UO);
4809   }
4810   bool VisitUnaryPostDec(const UnaryOperator *UO) {
4811     return VisitUnaryPostIncDec(UO);
4812   }
4813   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
4814     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4815       return Error(UO);
4816 
4817     LValue LVal;
4818     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4819       return false;
4820     APValue RVal;
4821     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4822                       UO->isIncrementOp(), &RVal))
4823       return false;
4824     return DerivedSuccess(RVal, UO);
4825   }
4826 
4827   bool VisitStmtExpr(const StmtExpr *E) {
4828     // We will have checked the full-expressions inside the statement expression
4829     // when they were completed, and don't need to check them again now.
4830     if (Info.checkingForOverflow())
4831       return Error(E);
4832 
4833     BlockScopeRAII Scope(Info);
4834     const CompoundStmt *CS = E->getSubStmt();
4835     if (CS->body_empty())
4836       return true;
4837 
4838     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4839                                            BE = CS->body_end();
4840          /**/; ++BI) {
4841       if (BI + 1 == BE) {
4842         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4843         if (!FinalExpr) {
4844           Info.FFDiag((*BI)->getLocStart(),
4845                     diag::note_constexpr_stmt_expr_unsupported);
4846           return false;
4847         }
4848         return this->Visit(FinalExpr);
4849       }
4850 
4851       APValue ReturnValue;
4852       StmtResult Result = { ReturnValue, nullptr };
4853       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
4854       if (ESR != ESR_Succeeded) {
4855         // FIXME: If the statement-expression terminated due to 'return',
4856         // 'break', or 'continue', it would be nice to propagate that to
4857         // the outer statement evaluation rather than bailing out.
4858         if (ESR != ESR_Failed)
4859           Info.FFDiag((*BI)->getLocStart(),
4860                     diag::note_constexpr_stmt_expr_unsupported);
4861         return false;
4862       }
4863     }
4864 
4865     llvm_unreachable("Return from function from the loop above.");
4866   }
4867 
4868   /// Visit a value which is evaluated, but whose value is ignored.
4869   void VisitIgnoredValue(const Expr *E) {
4870     EvaluateIgnoredValue(Info, E);
4871   }
4872 
4873   /// Potentially visit a MemberExpr's base expression.
4874   void VisitIgnoredBaseExpression(const Expr *E) {
4875     // While MSVC doesn't evaluate the base expression, it does diagnose the
4876     // presence of side-effecting behavior.
4877     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4878       return;
4879     VisitIgnoredValue(E);
4880   }
4881 };
4882 
4883 }
4884 
4885 //===----------------------------------------------------------------------===//
4886 // Common base class for lvalue and temporary evaluation.
4887 //===----------------------------------------------------------------------===//
4888 namespace {
4889 template<class Derived>
4890 class LValueExprEvaluatorBase
4891   : public ExprEvaluatorBase<Derived> {
4892 protected:
4893   LValue &Result;
4894   bool InvalidBaseOK;
4895   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4896   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
4897 
4898   bool Success(APValue::LValueBase B) {
4899     Result.set(B);
4900     return true;
4901   }
4902 
4903   bool evaluatePointer(const Expr *E, LValue &Result) {
4904     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
4905   }
4906 
4907 public:
4908   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
4909       : ExprEvaluatorBaseTy(Info), Result(Result),
4910         InvalidBaseOK(InvalidBaseOK) {}
4911 
4912   bool Success(const APValue &V, const Expr *E) {
4913     Result.setFrom(this->Info.Ctx, V);
4914     return true;
4915   }
4916 
4917   bool VisitMemberExpr(const MemberExpr *E) {
4918     // Handle non-static data members.
4919     QualType BaseTy;
4920     bool EvalOK;
4921     if (E->isArrow()) {
4922       EvalOK = evaluatePointer(E->getBase(), Result);
4923       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
4924     } else if (E->getBase()->isRValue()) {
4925       assert(E->getBase()->getType()->isRecordType());
4926       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
4927       BaseTy = E->getBase()->getType();
4928     } else {
4929       EvalOK = this->Visit(E->getBase());
4930       BaseTy = E->getBase()->getType();
4931     }
4932     if (!EvalOK) {
4933       if (!InvalidBaseOK)
4934         return false;
4935       Result.setInvalid(E);
4936       return true;
4937     }
4938 
4939     const ValueDecl *MD = E->getMemberDecl();
4940     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4941       assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4942              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4943       (void)BaseTy;
4944       if (!HandleLValueMember(this->Info, E, Result, FD))
4945         return false;
4946     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
4947       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4948         return false;
4949     } else
4950       return this->Error(E);
4951 
4952     if (MD->getType()->isReferenceType()) {
4953       APValue RefValue;
4954       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
4955                                           RefValue))
4956         return false;
4957       return Success(RefValue, E);
4958     }
4959     return true;
4960   }
4961 
4962   bool VisitBinaryOperator(const BinaryOperator *E) {
4963     switch (E->getOpcode()) {
4964     default:
4965       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4966 
4967     case BO_PtrMemD:
4968     case BO_PtrMemI:
4969       return HandleMemberPointerAccess(this->Info, E, Result);
4970     }
4971   }
4972 
4973   bool VisitCastExpr(const CastExpr *E) {
4974     switch (E->getCastKind()) {
4975     default:
4976       return ExprEvaluatorBaseTy::VisitCastExpr(E);
4977 
4978     case CK_DerivedToBase:
4979     case CK_UncheckedDerivedToBase:
4980       if (!this->Visit(E->getSubExpr()))
4981         return false;
4982 
4983       // Now figure out the necessary offset to add to the base LV to get from
4984       // the derived class to the base class.
4985       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4986                                   Result);
4987     }
4988   }
4989 };
4990 }
4991 
4992 //===----------------------------------------------------------------------===//
4993 // LValue Evaluation
4994 //
4995 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4996 // function designators (in C), decl references to void objects (in C), and
4997 // temporaries (if building with -Wno-address-of-temporary).
4998 //
4999 // LValue evaluation produces values comprising a base expression of one of the
5000 // following types:
5001 // - Declarations
5002 //  * VarDecl
5003 //  * FunctionDecl
5004 // - Literals
5005 //  * CompoundLiteralExpr in C (and in global scope in C++)
5006 //  * StringLiteral
5007 //  * CXXTypeidExpr
5008 //  * PredefinedExpr
5009 //  * ObjCStringLiteralExpr
5010 //  * ObjCEncodeExpr
5011 //  * AddrLabelExpr
5012 //  * BlockExpr
5013 //  * CallExpr for a MakeStringConstant builtin
5014 // - Locals and temporaries
5015 //  * MaterializeTemporaryExpr
5016 //  * Any Expr, with a CallIndex indicating the function in which the temporary
5017 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
5018 //    from the AST (FIXME).
5019 //  * A MaterializeTemporaryExpr that has static storage duration, with no
5020 //    CallIndex, for a lifetime-extended temporary.
5021 // plus an offset in bytes.
5022 //===----------------------------------------------------------------------===//
5023 namespace {
5024 class LValueExprEvaluator
5025   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
5026 public:
5027   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5028     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
5029 
5030   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
5031   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
5032 
5033   bool VisitDeclRefExpr(const DeclRefExpr *E);
5034   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
5035   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
5036   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5037   bool VisitMemberExpr(const MemberExpr *E);
5038   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5039   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
5040   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
5041   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
5042   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5043   bool VisitUnaryDeref(const UnaryOperator *E);
5044   bool VisitUnaryReal(const UnaryOperator *E);
5045   bool VisitUnaryImag(const UnaryOperator *E);
5046   bool VisitUnaryPreInc(const UnaryOperator *UO) {
5047     return VisitUnaryPreIncDec(UO);
5048   }
5049   bool VisitUnaryPreDec(const UnaryOperator *UO) {
5050     return VisitUnaryPreIncDec(UO);
5051   }
5052   bool VisitBinAssign(const BinaryOperator *BO);
5053   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
5054 
5055   bool VisitCastExpr(const CastExpr *E) {
5056     switch (E->getCastKind()) {
5057     default:
5058       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5059 
5060     case CK_LValueBitCast:
5061       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5062       if (!Visit(E->getSubExpr()))
5063         return false;
5064       Result.Designator.setInvalid();
5065       return true;
5066 
5067     case CK_BaseToDerived:
5068       if (!Visit(E->getSubExpr()))
5069         return false;
5070       return HandleBaseToDerivedCast(Info, E, Result);
5071     }
5072   }
5073 };
5074 } // end anonymous namespace
5075 
5076 /// Evaluate an expression as an lvalue. This can be legitimately called on
5077 /// expressions which are not glvalues, in three cases:
5078 ///  * function designators in C, and
5079 ///  * "extern void" objects
5080 ///  * @selector() expressions in Objective-C
5081 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5082                            bool InvalidBaseOK) {
5083   assert(E->isGLValue() || E->getType()->isFunctionType() ||
5084          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
5085   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5086 }
5087 
5088 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
5089   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
5090     return Success(FD);
5091   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
5092     return VisitVarDecl(E, VD);
5093   if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
5094     return Visit(BD->getBinding());
5095   return Error(E);
5096 }
5097 
5098 
5099 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
5100 
5101   // If we are within a lambda's call operator, check whether the 'VD' referred
5102   // to within 'E' actually represents a lambda-capture that maps to a
5103   // data-member/field within the closure object, and if so, evaluate to the
5104   // field or what the field refers to.
5105   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee)) {
5106     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5107       if (Info.checkingPotentialConstantExpression())
5108         return false;
5109       // Start with 'Result' referring to the complete closure object...
5110       Result = *Info.CurrentCall->This;
5111       // ... then update it to refer to the field of the closure object
5112       // that represents the capture.
5113       if (!HandleLValueMember(Info, E, Result, FD))
5114         return false;
5115       // And if the field is of reference type, update 'Result' to refer to what
5116       // the field refers to.
5117       if (FD->getType()->isReferenceType()) {
5118         APValue RVal;
5119         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5120                                             RVal))
5121           return false;
5122         Result.setFrom(Info.Ctx, RVal);
5123       }
5124       return true;
5125     }
5126   }
5127   CallStackFrame *Frame = nullptr;
5128   if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5129     // Only if a local variable was declared in the function currently being
5130     // evaluated, do we expect to be able to find its value in the current
5131     // frame. (Otherwise it was likely declared in an enclosing context and
5132     // could either have a valid evaluatable value (for e.g. a constexpr
5133     // variable) or be ill-formed (and trigger an appropriate evaluation
5134     // diagnostic)).
5135     if (Info.CurrentCall->Callee &&
5136         Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5137       Frame = Info.CurrentCall;
5138     }
5139   }
5140 
5141   if (!VD->getType()->isReferenceType()) {
5142     if (Frame) {
5143       Result.set(VD, Frame->Index);
5144       return true;
5145     }
5146     return Success(VD);
5147   }
5148 
5149   APValue *V;
5150   if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
5151     return false;
5152   if (V->isUninit()) {
5153     if (!Info.checkingPotentialConstantExpression())
5154       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
5155     return false;
5156   }
5157   return Success(*V, E);
5158 }
5159 
5160 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5161     const MaterializeTemporaryExpr *E) {
5162   // Walk through the expression to find the materialized temporary itself.
5163   SmallVector<const Expr *, 2> CommaLHSs;
5164   SmallVector<SubobjectAdjustment, 2> Adjustments;
5165   const Expr *Inner = E->GetTemporaryExpr()->
5166       skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
5167 
5168   // If we passed any comma operators, evaluate their LHSs.
5169   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5170     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5171       return false;
5172 
5173   // A materialized temporary with static storage duration can appear within the
5174   // result of a constant expression evaluation, so we need to preserve its
5175   // value for use outside this evaluation.
5176   APValue *Value;
5177   if (E->getStorageDuration() == SD_Static) {
5178     Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
5179     *Value = APValue();
5180     Result.set(E);
5181   } else {
5182     Value = &Info.CurrentCall->
5183         createTemporary(E, E->getStorageDuration() == SD_Automatic);
5184     Result.set(E, Info.CurrentCall->Index);
5185   }
5186 
5187   QualType Type = Inner->getType();
5188 
5189   // Materialize the temporary itself.
5190   if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5191       (E->getStorageDuration() == SD_Static &&
5192        !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5193     *Value = APValue();
5194     return false;
5195   }
5196 
5197   // Adjust our lvalue to refer to the desired subobject.
5198   for (unsigned I = Adjustments.size(); I != 0; /**/) {
5199     --I;
5200     switch (Adjustments[I].Kind) {
5201     case SubobjectAdjustment::DerivedToBaseAdjustment:
5202       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5203                                 Type, Result))
5204         return false;
5205       Type = Adjustments[I].DerivedToBase.BasePath->getType();
5206       break;
5207 
5208     case SubobjectAdjustment::FieldAdjustment:
5209       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5210         return false;
5211       Type = Adjustments[I].Field->getType();
5212       break;
5213 
5214     case SubobjectAdjustment::MemberPointerAdjustment:
5215       if (!HandleMemberPointerAccess(this->Info, Type, Result,
5216                                      Adjustments[I].Ptr.RHS))
5217         return false;
5218       Type = Adjustments[I].Ptr.MPT->getPointeeType();
5219       break;
5220     }
5221   }
5222 
5223   return true;
5224 }
5225 
5226 bool
5227 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
5228   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5229          "lvalue compound literal in c++?");
5230   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5231   // only see this when folding in C, so there's no standard to follow here.
5232   return Success(E);
5233 }
5234 
5235 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
5236   if (!E->isPotentiallyEvaluated())
5237     return Success(E);
5238 
5239   Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
5240     << E->getExprOperand()->getType()
5241     << E->getExprOperand()->getSourceRange();
5242   return false;
5243 }
5244 
5245 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5246   return Success(E);
5247 }
5248 
5249 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
5250   // Handle static data members.
5251   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
5252     VisitIgnoredBaseExpression(E->getBase());
5253     return VisitVarDecl(E, VD);
5254   }
5255 
5256   // Handle static member functions.
5257   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5258     if (MD->isStatic()) {
5259       VisitIgnoredBaseExpression(E->getBase());
5260       return Success(MD);
5261     }
5262   }
5263 
5264   // Handle non-static data members.
5265   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
5266 }
5267 
5268 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
5269   // FIXME: Deal with vectors as array subscript bases.
5270   if (E->getBase()->getType()->isVectorType())
5271     return Error(E);
5272 
5273   bool Success = true;
5274   if (!evaluatePointer(E->getBase(), Result)) {
5275     if (!Info.noteFailure())
5276       return false;
5277     Success = false;
5278   }
5279 
5280   APSInt Index;
5281   if (!EvaluateInteger(E->getIdx(), Index, Info))
5282     return false;
5283 
5284   return Success &&
5285          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
5286 }
5287 
5288 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
5289   return evaluatePointer(E->getSubExpr(), Result);
5290 }
5291 
5292 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5293   if (!Visit(E->getSubExpr()))
5294     return false;
5295   // __real is a no-op on scalar lvalues.
5296   if (E->getSubExpr()->getType()->isAnyComplexType())
5297     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5298   return true;
5299 }
5300 
5301 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5302   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5303          "lvalue __imag__ on scalar?");
5304   if (!Visit(E->getSubExpr()))
5305     return false;
5306   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5307   return true;
5308 }
5309 
5310 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
5311   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5312     return Error(UO);
5313 
5314   if (!this->Visit(UO->getSubExpr()))
5315     return false;
5316 
5317   return handleIncDec(
5318       this->Info, UO, Result, UO->getSubExpr()->getType(),
5319       UO->isIncrementOp(), nullptr);
5320 }
5321 
5322 bool LValueExprEvaluator::VisitCompoundAssignOperator(
5323     const CompoundAssignOperator *CAO) {
5324   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5325     return Error(CAO);
5326 
5327   APValue RHS;
5328 
5329   // The overall lvalue result is the result of evaluating the LHS.
5330   if (!this->Visit(CAO->getLHS())) {
5331     if (Info.noteFailure())
5332       Evaluate(RHS, this->Info, CAO->getRHS());
5333     return false;
5334   }
5335 
5336   if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5337     return false;
5338 
5339   return handleCompoundAssignment(
5340       this->Info, CAO,
5341       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5342       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
5343 }
5344 
5345 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
5346   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5347     return Error(E);
5348 
5349   APValue NewVal;
5350 
5351   if (!this->Visit(E->getLHS())) {
5352     if (Info.noteFailure())
5353       Evaluate(NewVal, this->Info, E->getRHS());
5354     return false;
5355   }
5356 
5357   if (!Evaluate(NewVal, this->Info, E->getRHS()))
5358     return false;
5359 
5360   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
5361                           NewVal);
5362 }
5363 
5364 //===----------------------------------------------------------------------===//
5365 // Pointer Evaluation
5366 //===----------------------------------------------------------------------===//
5367 
5368 /// \brief Attempts to compute the number of bytes available at the pointer
5369 /// returned by a function with the alloc_size attribute. Returns true if we
5370 /// were successful. Places an unsigned number into `Result`.
5371 ///
5372 /// This expects the given CallExpr to be a call to a function with an
5373 /// alloc_size attribute.
5374 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5375                                             const CallExpr *Call,
5376                                             llvm::APInt &Result) {
5377   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5378 
5379   // alloc_size args are 1-indexed, 0 means not present.
5380   assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5381   unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5382   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5383   if (Call->getNumArgs() <= SizeArgNo)
5384     return false;
5385 
5386   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5387     if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5388       return false;
5389     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5390       return false;
5391     Into = Into.zextOrSelf(BitsInSizeT);
5392     return true;
5393   };
5394 
5395   APSInt SizeOfElem;
5396   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5397     return false;
5398 
5399   if (!AllocSize->getNumElemsParam()) {
5400     Result = std::move(SizeOfElem);
5401     return true;
5402   }
5403 
5404   APSInt NumberOfElems;
5405   // Argument numbers start at 1
5406   unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5407   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5408     return false;
5409 
5410   bool Overflow;
5411   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5412   if (Overflow)
5413     return false;
5414 
5415   Result = std::move(BytesAvailable);
5416   return true;
5417 }
5418 
5419 /// \brief Convenience function. LVal's base must be a call to an alloc_size
5420 /// function.
5421 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5422                                             const LValue &LVal,
5423                                             llvm::APInt &Result) {
5424   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5425          "Can't get the size of a non alloc_size function");
5426   const auto *Base = LVal.getLValueBase().get<const Expr *>();
5427   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5428   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5429 }
5430 
5431 /// \brief Attempts to evaluate the given LValueBase as the result of a call to
5432 /// a function with the alloc_size attribute. If it was possible to do so, this
5433 /// function will return true, make Result's Base point to said function call,
5434 /// and mark Result's Base as invalid.
5435 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5436                                       LValue &Result) {
5437   if (Base.isNull())
5438     return false;
5439 
5440   // Because we do no form of static analysis, we only support const variables.
5441   //
5442   // Additionally, we can't support parameters, nor can we support static
5443   // variables (in the latter case, use-before-assign isn't UB; in the former,
5444   // we have no clue what they'll be assigned to).
5445   const auto *VD =
5446       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5447   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5448     return false;
5449 
5450   const Expr *Init = VD->getAnyInitializer();
5451   if (!Init)
5452     return false;
5453 
5454   const Expr *E = Init->IgnoreParens();
5455   if (!tryUnwrapAllocSizeCall(E))
5456     return false;
5457 
5458   // Store E instead of E unwrapped so that the type of the LValue's base is
5459   // what the user wanted.
5460   Result.setInvalid(E);
5461 
5462   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5463   Result.addUnsizedArray(Info, Pointee);
5464   return true;
5465 }
5466 
5467 namespace {
5468 class PointerExprEvaluator
5469   : public ExprEvaluatorBase<PointerExprEvaluator> {
5470   LValue &Result;
5471   bool InvalidBaseOK;
5472 
5473   bool Success(const Expr *E) {
5474     Result.set(E);
5475     return true;
5476   }
5477 
5478   bool evaluateLValue(const Expr *E, LValue &Result) {
5479     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5480   }
5481 
5482   bool evaluatePointer(const Expr *E, LValue &Result) {
5483     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5484   }
5485 
5486   bool visitNonBuiltinCallExpr(const CallExpr *E);
5487 public:
5488 
5489   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5490       : ExprEvaluatorBaseTy(info), Result(Result),
5491         InvalidBaseOK(InvalidBaseOK) {}
5492 
5493   bool Success(const APValue &V, const Expr *E) {
5494     Result.setFrom(Info.Ctx, V);
5495     return true;
5496   }
5497   bool ZeroInitialization(const Expr *E) {
5498     auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5499     Result.setNull(E->getType(), TargetVal);
5500     return true;
5501   }
5502 
5503   bool VisitBinaryOperator(const BinaryOperator *E);
5504   bool VisitCastExpr(const CastExpr* E);
5505   bool VisitUnaryAddrOf(const UnaryOperator *E);
5506   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
5507       { return Success(E); }
5508   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5509     if (Info.noteFailure())
5510       EvaluateIgnoredValue(Info, E->getSubExpr());
5511     return Error(E);
5512   }
5513   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
5514       { return Success(E); }
5515   bool VisitCallExpr(const CallExpr *E);
5516   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
5517   bool VisitBlockExpr(const BlockExpr *E) {
5518     if (!E->getBlockDecl()->hasCaptures())
5519       return Success(E);
5520     return Error(E);
5521   }
5522   bool VisitCXXThisExpr(const CXXThisExpr *E) {
5523     // Can't look at 'this' when checking a potential constant expression.
5524     if (Info.checkingPotentialConstantExpression())
5525       return false;
5526     if (!Info.CurrentCall->This) {
5527       if (Info.getLangOpts().CPlusPlus11)
5528         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
5529       else
5530         Info.FFDiag(E);
5531       return false;
5532     }
5533     Result = *Info.CurrentCall->This;
5534     // If we are inside a lambda's call operator, the 'this' expression refers
5535     // to the enclosing '*this' object (either by value or reference) which is
5536     // either copied into the closure object's field that represents the '*this'
5537     // or refers to '*this'.
5538     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5539       // Update 'Result' to refer to the data member/field of the closure object
5540       // that represents the '*this' capture.
5541       if (!HandleLValueMember(Info, E, Result,
5542                              Info.CurrentCall->LambdaThisCaptureField))
5543         return false;
5544       // If we captured '*this' by reference, replace the field with its referent.
5545       if (Info.CurrentCall->LambdaThisCaptureField->getType()
5546               ->isPointerType()) {
5547         APValue RVal;
5548         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5549                                             RVal))
5550           return false;
5551 
5552         Result.setFrom(Info.Ctx, RVal);
5553       }
5554     }
5555     return true;
5556   }
5557 
5558   // FIXME: Missing: @protocol, @selector
5559 };
5560 } // end anonymous namespace
5561 
5562 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5563                             bool InvalidBaseOK) {
5564   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
5565   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5566 }
5567 
5568 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5569   if (E->getOpcode() != BO_Add &&
5570       E->getOpcode() != BO_Sub)
5571     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5572 
5573   const Expr *PExp = E->getLHS();
5574   const Expr *IExp = E->getRHS();
5575   if (IExp->getType()->isPointerType())
5576     std::swap(PExp, IExp);
5577 
5578   bool EvalPtrOK = evaluatePointer(PExp, Result);
5579   if (!EvalPtrOK && !Info.noteFailure())
5580     return false;
5581 
5582   llvm::APSInt Offset;
5583   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
5584     return false;
5585 
5586   if (E->getOpcode() == BO_Sub)
5587     negateAsSigned(Offset);
5588 
5589   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
5590   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
5591 }
5592 
5593 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5594   return evaluateLValue(E->getSubExpr(), Result);
5595 }
5596 
5597 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5598   const Expr* SubExpr = E->getSubExpr();
5599 
5600   switch (E->getCastKind()) {
5601   default:
5602     break;
5603 
5604   case CK_BitCast:
5605   case CK_CPointerToObjCPointerCast:
5606   case CK_BlockPointerToObjCPointerCast:
5607   case CK_AnyPointerToBlockPointerCast:
5608   case CK_AddressSpaceConversion:
5609     if (!Visit(SubExpr))
5610       return false;
5611     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5612     // permitted in constant expressions in C++11. Bitcasts from cv void* are
5613     // also static_casts, but we disallow them as a resolution to DR1312.
5614     if (!E->getType()->isVoidPointerType()) {
5615       Result.Designator.setInvalid();
5616       if (SubExpr->getType()->isVoidPointerType())
5617         CCEDiag(E, diag::note_constexpr_invalid_cast)
5618           << 3 << SubExpr->getType();
5619       else
5620         CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5621     }
5622     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5623       ZeroInitialization(E);
5624     return true;
5625 
5626   case CK_DerivedToBase:
5627   case CK_UncheckedDerivedToBase:
5628     if (!evaluatePointer(E->getSubExpr(), Result))
5629       return false;
5630     if (!Result.Base && Result.Offset.isZero())
5631       return true;
5632 
5633     // Now figure out the necessary offset to add to the base LV to get from
5634     // the derived class to the base class.
5635     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5636                                   castAs<PointerType>()->getPointeeType(),
5637                                 Result);
5638 
5639   case CK_BaseToDerived:
5640     if (!Visit(E->getSubExpr()))
5641       return false;
5642     if (!Result.Base && Result.Offset.isZero())
5643       return true;
5644     return HandleBaseToDerivedCast(Info, E, Result);
5645 
5646   case CK_NullToPointer:
5647     VisitIgnoredValue(E->getSubExpr());
5648     return ZeroInitialization(E);
5649 
5650   case CK_IntegralToPointer: {
5651     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5652 
5653     APValue Value;
5654     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
5655       break;
5656 
5657     if (Value.isInt()) {
5658       unsigned Size = Info.Ctx.getTypeSize(E->getType());
5659       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
5660       Result.Base = (Expr*)nullptr;
5661       Result.InvalidBase = false;
5662       Result.Offset = CharUnits::fromQuantity(N);
5663       Result.CallIndex = 0;
5664       Result.Designator.setInvalid();
5665       Result.IsNullPtr = false;
5666       return true;
5667     } else {
5668       // Cast is of an lvalue, no need to change value.
5669       Result.setFrom(Info.Ctx, Value);
5670       return true;
5671     }
5672   }
5673   case CK_ArrayToPointerDecay:
5674     if (SubExpr->isGLValue()) {
5675       if (!evaluateLValue(SubExpr, Result))
5676         return false;
5677     } else {
5678       Result.set(SubExpr, Info.CurrentCall->Index);
5679       if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
5680                            Info, Result, SubExpr))
5681         return false;
5682     }
5683     // The result is a pointer to the first element of the array.
5684     if (const ConstantArrayType *CAT
5685           = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5686       Result.addArray(Info, E, CAT);
5687     else
5688       Result.Designator.setInvalid();
5689     return true;
5690 
5691   case CK_FunctionToPointerDecay:
5692     return evaluateLValue(SubExpr, Result);
5693 
5694   case CK_LValueToRValue: {
5695     LValue LVal;
5696     if (!evaluateLValue(E->getSubExpr(), LVal))
5697       return false;
5698 
5699     APValue RVal;
5700     // Note, we use the subexpression's type in order to retain cv-qualifiers.
5701     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5702                                         LVal, RVal))
5703       return InvalidBaseOK &&
5704              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
5705     return Success(RVal, E);
5706   }
5707   }
5708 
5709   return ExprEvaluatorBaseTy::VisitCastExpr(E);
5710 }
5711 
5712 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5713   // C++ [expr.alignof]p3:
5714   //     When alignof is applied to a reference type, the result is the
5715   //     alignment of the referenced type.
5716   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5717     T = Ref->getPointeeType();
5718 
5719   // __alignof is defined to return the preferred alignment.
5720   if (T.getQualifiers().hasUnaligned())
5721     return CharUnits::One();
5722   return Info.Ctx.toCharUnitsFromBits(
5723     Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5724 }
5725 
5726 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5727   E = E->IgnoreParens();
5728 
5729   // The kinds of expressions that we have special-case logic here for
5730   // should be kept up to date with the special checks for those
5731   // expressions in Sema.
5732 
5733   // alignof decl is always accepted, even if it doesn't make sense: we default
5734   // to 1 in those cases.
5735   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5736     return Info.Ctx.getDeclAlign(DRE->getDecl(),
5737                                  /*RefAsPointee*/true);
5738 
5739   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5740     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5741                                  /*RefAsPointee*/true);
5742 
5743   return GetAlignOfType(Info, E->getType());
5744 }
5745 
5746 // To be clear: this happily visits unsupported builtins. Better name welcomed.
5747 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5748   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5749     return true;
5750 
5751   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
5752     return false;
5753 
5754   Result.setInvalid(E);
5755   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
5756   Result.addUnsizedArray(Info, PointeeTy);
5757   return true;
5758 }
5759 
5760 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
5761   if (IsStringLiteralCall(E))
5762     return Success(E);
5763 
5764   if (unsigned BuiltinOp = E->getBuiltinCallee())
5765     return VisitBuiltinCallExpr(E, BuiltinOp);
5766 
5767   return visitNonBuiltinCallExpr(E);
5768 }
5769 
5770 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5771                                                 unsigned BuiltinOp) {
5772   switch (BuiltinOp) {
5773   case Builtin::BI__builtin_addressof:
5774     return evaluateLValue(E->getArg(0), Result);
5775   case Builtin::BI__builtin_assume_aligned: {
5776     // We need to be very careful here because: if the pointer does not have the
5777     // asserted alignment, then the behavior is undefined, and undefined
5778     // behavior is non-constant.
5779     if (!evaluatePointer(E->getArg(0), Result))
5780       return false;
5781 
5782     LValue OffsetResult(Result);
5783     APSInt Alignment;
5784     if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5785       return false;
5786     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
5787 
5788     if (E->getNumArgs() > 2) {
5789       APSInt Offset;
5790       if (!EvaluateInteger(E->getArg(2), Offset, Info))
5791         return false;
5792 
5793       int64_t AdditionalOffset = -Offset.getZExtValue();
5794       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5795     }
5796 
5797     // If there is a base object, then it must have the correct alignment.
5798     if (OffsetResult.Base) {
5799       CharUnits BaseAlignment;
5800       if (const ValueDecl *VD =
5801           OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5802         BaseAlignment = Info.Ctx.getDeclAlign(VD);
5803       } else {
5804         BaseAlignment =
5805           GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5806       }
5807 
5808       if (BaseAlignment < Align) {
5809         Result.Designator.setInvalid();
5810         // FIXME: Add support to Diagnostic for long / long long.
5811         CCEDiag(E->getArg(0),
5812                 diag::note_constexpr_baa_insufficient_alignment) << 0
5813           << (unsigned)BaseAlignment.getQuantity()
5814           << (unsigned)Align.getQuantity();
5815         return false;
5816       }
5817     }
5818 
5819     // The offset must also have the correct alignment.
5820     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
5821       Result.Designator.setInvalid();
5822 
5823       (OffsetResult.Base
5824            ? CCEDiag(E->getArg(0),
5825                      diag::note_constexpr_baa_insufficient_alignment) << 1
5826            : CCEDiag(E->getArg(0),
5827                      diag::note_constexpr_baa_value_insufficient_alignment))
5828         << (int)OffsetResult.Offset.getQuantity()
5829         << (unsigned)Align.getQuantity();
5830       return false;
5831     }
5832 
5833     return true;
5834   }
5835 
5836   case Builtin::BIstrchr:
5837   case Builtin::BIwcschr:
5838   case Builtin::BImemchr:
5839   case Builtin::BIwmemchr:
5840     if (Info.getLangOpts().CPlusPlus11)
5841       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5842         << /*isConstexpr*/0 << /*isConstructor*/0
5843         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
5844     else
5845       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5846     // Fall through.
5847   case Builtin::BI__builtin_strchr:
5848   case Builtin::BI__builtin_wcschr:
5849   case Builtin::BI__builtin_memchr:
5850   case Builtin::BI__builtin_char_memchr:
5851   case Builtin::BI__builtin_wmemchr: {
5852     if (!Visit(E->getArg(0)))
5853       return false;
5854     APSInt Desired;
5855     if (!EvaluateInteger(E->getArg(1), Desired, Info))
5856       return false;
5857     uint64_t MaxLength = uint64_t(-1);
5858     if (BuiltinOp != Builtin::BIstrchr &&
5859         BuiltinOp != Builtin::BIwcschr &&
5860         BuiltinOp != Builtin::BI__builtin_strchr &&
5861         BuiltinOp != Builtin::BI__builtin_wcschr) {
5862       APSInt N;
5863       if (!EvaluateInteger(E->getArg(2), N, Info))
5864         return false;
5865       MaxLength = N.getExtValue();
5866     }
5867 
5868     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
5869 
5870     // Figure out what value we're actually looking for (after converting to
5871     // the corresponding unsigned type if necessary).
5872     uint64_t DesiredVal;
5873     bool StopAtNull = false;
5874     switch (BuiltinOp) {
5875     case Builtin::BIstrchr:
5876     case Builtin::BI__builtin_strchr:
5877       // strchr compares directly to the passed integer, and therefore
5878       // always fails if given an int that is not a char.
5879       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5880                                                   E->getArg(1)->getType(),
5881                                                   Desired),
5882                                Desired))
5883         return ZeroInitialization(E);
5884       StopAtNull = true;
5885       // Fall through.
5886     case Builtin::BImemchr:
5887     case Builtin::BI__builtin_memchr:
5888     case Builtin::BI__builtin_char_memchr:
5889       // memchr compares by converting both sides to unsigned char. That's also
5890       // correct for strchr if we get this far (to cope with plain char being
5891       // unsigned in the strchr case).
5892       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5893       break;
5894 
5895     case Builtin::BIwcschr:
5896     case Builtin::BI__builtin_wcschr:
5897       StopAtNull = true;
5898       // Fall through.
5899     case Builtin::BIwmemchr:
5900     case Builtin::BI__builtin_wmemchr:
5901       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5902       DesiredVal = Desired.getZExtValue();
5903       break;
5904     }
5905 
5906     for (; MaxLength; --MaxLength) {
5907       APValue Char;
5908       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5909           !Char.isInt())
5910         return false;
5911       if (Char.getInt().getZExtValue() == DesiredVal)
5912         return true;
5913       if (StopAtNull && !Char.getInt())
5914         break;
5915       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5916         return false;
5917     }
5918     // Not found: return nullptr.
5919     return ZeroInitialization(E);
5920   }
5921 
5922   default:
5923     return visitNonBuiltinCallExpr(E);
5924   }
5925 }
5926 
5927 //===----------------------------------------------------------------------===//
5928 // Member Pointer Evaluation
5929 //===----------------------------------------------------------------------===//
5930 
5931 namespace {
5932 class MemberPointerExprEvaluator
5933   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
5934   MemberPtr &Result;
5935 
5936   bool Success(const ValueDecl *D) {
5937     Result = MemberPtr(D);
5938     return true;
5939   }
5940 public:
5941 
5942   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5943     : ExprEvaluatorBaseTy(Info), Result(Result) {}
5944 
5945   bool Success(const APValue &V, const Expr *E) {
5946     Result.setFrom(V);
5947     return true;
5948   }
5949   bool ZeroInitialization(const Expr *E) {
5950     return Success((const ValueDecl*)nullptr);
5951   }
5952 
5953   bool VisitCastExpr(const CastExpr *E);
5954   bool VisitUnaryAddrOf(const UnaryOperator *E);
5955 };
5956 } // end anonymous namespace
5957 
5958 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5959                                   EvalInfo &Info) {
5960   assert(E->isRValue() && E->getType()->isMemberPointerType());
5961   return MemberPointerExprEvaluator(Info, Result).Visit(E);
5962 }
5963 
5964 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5965   switch (E->getCastKind()) {
5966   default:
5967     return ExprEvaluatorBaseTy::VisitCastExpr(E);
5968 
5969   case CK_NullToMemberPointer:
5970     VisitIgnoredValue(E->getSubExpr());
5971     return ZeroInitialization(E);
5972 
5973   case CK_BaseToDerivedMemberPointer: {
5974     if (!Visit(E->getSubExpr()))
5975       return false;
5976     if (E->path_empty())
5977       return true;
5978     // Base-to-derived member pointer casts store the path in derived-to-base
5979     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5980     // the wrong end of the derived->base arc, so stagger the path by one class.
5981     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5982     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5983          PathI != PathE; ++PathI) {
5984       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5985       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5986       if (!Result.castToDerived(Derived))
5987         return Error(E);
5988     }
5989     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5990     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
5991       return Error(E);
5992     return true;
5993   }
5994 
5995   case CK_DerivedToBaseMemberPointer:
5996     if (!Visit(E->getSubExpr()))
5997       return false;
5998     for (CastExpr::path_const_iterator PathI = E->path_begin(),
5999          PathE = E->path_end(); PathI != PathE; ++PathI) {
6000       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6001       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6002       if (!Result.castToBase(Base))
6003         return Error(E);
6004     }
6005     return true;
6006   }
6007 }
6008 
6009 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6010   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6011   // member can be formed.
6012   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6013 }
6014 
6015 //===----------------------------------------------------------------------===//
6016 // Record Evaluation
6017 //===----------------------------------------------------------------------===//
6018 
6019 namespace {
6020   class RecordExprEvaluator
6021   : public ExprEvaluatorBase<RecordExprEvaluator> {
6022     const LValue &This;
6023     APValue &Result;
6024   public:
6025 
6026     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6027       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6028 
6029     bool Success(const APValue &V, const Expr *E) {
6030       Result = V;
6031       return true;
6032     }
6033     bool ZeroInitialization(const Expr *E) {
6034       return ZeroInitialization(E, E->getType());
6035     }
6036     bool ZeroInitialization(const Expr *E, QualType T);
6037 
6038     bool VisitCallExpr(const CallExpr *E) {
6039       return handleCallExpr(E, Result, &This);
6040     }
6041     bool VisitCastExpr(const CastExpr *E);
6042     bool VisitInitListExpr(const InitListExpr *E);
6043     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6044       return VisitCXXConstructExpr(E, E->getType());
6045     }
6046     bool VisitLambdaExpr(const LambdaExpr *E);
6047     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
6048     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
6049     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
6050   };
6051 }
6052 
6053 /// Perform zero-initialization on an object of non-union class type.
6054 /// C++11 [dcl.init]p5:
6055 ///  To zero-initialize an object or reference of type T means:
6056 ///    [...]
6057 ///    -- if T is a (possibly cv-qualified) non-union class type,
6058 ///       each non-static data member and each base-class subobject is
6059 ///       zero-initialized
6060 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6061                                           const RecordDecl *RD,
6062                                           const LValue &This, APValue &Result) {
6063   assert(!RD->isUnion() && "Expected non-union class type");
6064   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6065   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
6066                    std::distance(RD->field_begin(), RD->field_end()));
6067 
6068   if (RD->isInvalidDecl()) return false;
6069   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6070 
6071   if (CD) {
6072     unsigned Index = 0;
6073     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
6074            End = CD->bases_end(); I != End; ++I, ++Index) {
6075       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6076       LValue Subobject = This;
6077       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6078         return false;
6079       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
6080                                          Result.getStructBase(Index)))
6081         return false;
6082     }
6083   }
6084 
6085   for (const auto *I : RD->fields()) {
6086     // -- if T is a reference type, no initialization is performed.
6087     if (I->getType()->isReferenceType())
6088       continue;
6089 
6090     LValue Subobject = This;
6091     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
6092       return false;
6093 
6094     ImplicitValueInitExpr VIE(I->getType());
6095     if (!EvaluateInPlace(
6096           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
6097       return false;
6098   }
6099 
6100   return true;
6101 }
6102 
6103 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6104   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
6105   if (RD->isInvalidDecl()) return false;
6106   if (RD->isUnion()) {
6107     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6108     // object's first non-static named data member is zero-initialized
6109     RecordDecl::field_iterator I = RD->field_begin();
6110     if (I == RD->field_end()) {
6111       Result = APValue((const FieldDecl*)nullptr);
6112       return true;
6113     }
6114 
6115     LValue Subobject = This;
6116     if (!HandleLValueMember(Info, E, Subobject, *I))
6117       return false;
6118     Result = APValue(*I);
6119     ImplicitValueInitExpr VIE(I->getType());
6120     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
6121   }
6122 
6123   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
6124     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
6125     return false;
6126   }
6127 
6128   return HandleClassZeroInitialization(Info, E, RD, This, Result);
6129 }
6130 
6131 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6132   switch (E->getCastKind()) {
6133   default:
6134     return ExprEvaluatorBaseTy::VisitCastExpr(E);
6135 
6136   case CK_ConstructorConversion:
6137     return Visit(E->getSubExpr());
6138 
6139   case CK_DerivedToBase:
6140   case CK_UncheckedDerivedToBase: {
6141     APValue DerivedObject;
6142     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
6143       return false;
6144     if (!DerivedObject.isStruct())
6145       return Error(E->getSubExpr());
6146 
6147     // Derived-to-base rvalue conversion: just slice off the derived part.
6148     APValue *Value = &DerivedObject;
6149     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6150     for (CastExpr::path_const_iterator PathI = E->path_begin(),
6151          PathE = E->path_end(); PathI != PathE; ++PathI) {
6152       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6153       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6154       Value = &Value->getStructBase(getBaseIndex(RD, Base));
6155       RD = Base;
6156     }
6157     Result = *Value;
6158     return true;
6159   }
6160   }
6161 }
6162 
6163 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6164   if (E->isTransparent())
6165     return Visit(E->getInit(0));
6166 
6167   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
6168   if (RD->isInvalidDecl()) return false;
6169   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6170 
6171   if (RD->isUnion()) {
6172     const FieldDecl *Field = E->getInitializedFieldInUnion();
6173     Result = APValue(Field);
6174     if (!Field)
6175       return true;
6176 
6177     // If the initializer list for a union does not contain any elements, the
6178     // first element of the union is value-initialized.
6179     // FIXME: The element should be initialized from an initializer list.
6180     //        Is this difference ever observable for initializer lists which
6181     //        we don't build?
6182     ImplicitValueInitExpr VIE(Field->getType());
6183     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6184 
6185     LValue Subobject = This;
6186     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6187       return false;
6188 
6189     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6190     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6191                                   isa<CXXDefaultInitExpr>(InitExpr));
6192 
6193     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
6194   }
6195 
6196   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
6197   if (Result.isUninit())
6198     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6199                      std::distance(RD->field_begin(), RD->field_end()));
6200   unsigned ElementNo = 0;
6201   bool Success = true;
6202 
6203   // Initialize base classes.
6204   if (CXXRD) {
6205     for (const auto &Base : CXXRD->bases()) {
6206       assert(ElementNo < E->getNumInits() && "missing init for base class");
6207       const Expr *Init = E->getInit(ElementNo);
6208 
6209       LValue Subobject = This;
6210       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6211         return false;
6212 
6213       APValue &FieldVal = Result.getStructBase(ElementNo);
6214       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
6215         if (!Info.noteFailure())
6216           return false;
6217         Success = false;
6218       }
6219       ++ElementNo;
6220     }
6221   }
6222 
6223   // Initialize members.
6224   for (const auto *Field : RD->fields()) {
6225     // Anonymous bit-fields are not considered members of the class for
6226     // purposes of aggregate initialization.
6227     if (Field->isUnnamedBitfield())
6228       continue;
6229 
6230     LValue Subobject = This;
6231 
6232     bool HaveInit = ElementNo < E->getNumInits();
6233 
6234     // FIXME: Diagnostics here should point to the end of the initializer
6235     // list, not the start.
6236     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
6237                             Subobject, Field, &Layout))
6238       return false;
6239 
6240     // Perform an implicit value-initialization for members beyond the end of
6241     // the initializer list.
6242     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
6243     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
6244 
6245     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6246     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6247                                   isa<CXXDefaultInitExpr>(Init));
6248 
6249     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6250     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6251         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
6252                                                        FieldVal, Field))) {
6253       if (!Info.noteFailure())
6254         return false;
6255       Success = false;
6256     }
6257   }
6258 
6259   return Success;
6260 }
6261 
6262 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6263                                                 QualType T) {
6264   // Note that E's type is not necessarily the type of our class here; we might
6265   // be initializing an array element instead.
6266   const CXXConstructorDecl *FD = E->getConstructor();
6267   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6268 
6269   bool ZeroInit = E->requiresZeroInitialization();
6270   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
6271     // If we've already performed zero-initialization, we're already done.
6272     if (!Result.isUninit())
6273       return true;
6274 
6275     // We can get here in two different ways:
6276     //  1) We're performing value-initialization, and should zero-initialize
6277     //     the object, or
6278     //  2) We're performing default-initialization of an object with a trivial
6279     //     constexpr default constructor, in which case we should start the
6280     //     lifetimes of all the base subobjects (there can be no data member
6281     //     subobjects in this case) per [basic.life]p1.
6282     // Either way, ZeroInitialization is appropriate.
6283     return ZeroInitialization(E, T);
6284   }
6285 
6286   const FunctionDecl *Definition = nullptr;
6287   auto Body = FD->getBody(Definition);
6288 
6289   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6290     return false;
6291 
6292   // Avoid materializing a temporary for an elidable copy/move constructor.
6293   if (E->isElidable() && !ZeroInit)
6294     if (const MaterializeTemporaryExpr *ME
6295           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6296       return Visit(ME->GetTemporaryExpr());
6297 
6298   if (ZeroInit && !ZeroInitialization(E, T))
6299     return false;
6300 
6301   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
6302   return HandleConstructorCall(E, This, Args,
6303                                cast<CXXConstructorDecl>(Definition), Info,
6304                                Result);
6305 }
6306 
6307 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6308     const CXXInheritedCtorInitExpr *E) {
6309   if (!Info.CurrentCall) {
6310     assert(Info.checkingPotentialConstantExpression());
6311     return false;
6312   }
6313 
6314   const CXXConstructorDecl *FD = E->getConstructor();
6315   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6316     return false;
6317 
6318   const FunctionDecl *Definition = nullptr;
6319   auto Body = FD->getBody(Definition);
6320 
6321   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6322     return false;
6323 
6324   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
6325                                cast<CXXConstructorDecl>(Definition), Info,
6326                                Result);
6327 }
6328 
6329 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6330     const CXXStdInitializerListExpr *E) {
6331   const ConstantArrayType *ArrayType =
6332       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6333 
6334   LValue Array;
6335   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6336     return false;
6337 
6338   // Get a pointer to the first element of the array.
6339   Array.addArray(Info, E, ArrayType);
6340 
6341   // FIXME: Perform the checks on the field types in SemaInit.
6342   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6343   RecordDecl::field_iterator Field = Record->field_begin();
6344   if (Field == Record->field_end())
6345     return Error(E);
6346 
6347   // Start pointer.
6348   if (!Field->getType()->isPointerType() ||
6349       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6350                             ArrayType->getElementType()))
6351     return Error(E);
6352 
6353   // FIXME: What if the initializer_list type has base classes, etc?
6354   Result = APValue(APValue::UninitStruct(), 0, 2);
6355   Array.moveInto(Result.getStructField(0));
6356 
6357   if (++Field == Record->field_end())
6358     return Error(E);
6359 
6360   if (Field->getType()->isPointerType() &&
6361       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6362                            ArrayType->getElementType())) {
6363     // End pointer.
6364     if (!HandleLValueArrayAdjustment(Info, E, Array,
6365                                      ArrayType->getElementType(),
6366                                      ArrayType->getSize().getZExtValue()))
6367       return false;
6368     Array.moveInto(Result.getStructField(1));
6369   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6370     // Length.
6371     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6372   else
6373     return Error(E);
6374 
6375   if (++Field != Record->field_end())
6376     return Error(E);
6377 
6378   return true;
6379 }
6380 
6381 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6382   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6383   if (ClosureClass->isInvalidDecl()) return false;
6384 
6385   if (Info.checkingPotentialConstantExpression()) return true;
6386 
6387   const size_t NumFields =
6388       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
6389 
6390   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6391                                             E->capture_init_end()) &&
6392          "The number of lambda capture initializers should equal the number of "
6393          "fields within the closure type");
6394 
6395   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6396   // Iterate through all the lambda's closure object's fields and initialize
6397   // them.
6398   auto *CaptureInitIt = E->capture_init_begin();
6399   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6400   bool Success = true;
6401   for (const auto *Field : ClosureClass->fields()) {
6402     assert(CaptureInitIt != E->capture_init_end());
6403     // Get the initializer for this field
6404     Expr *const CurFieldInit = *CaptureInitIt++;
6405 
6406     // If there is no initializer, either this is a VLA or an error has
6407     // occurred.
6408     if (!CurFieldInit)
6409       return Error(E);
6410 
6411     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6412     if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6413       if (!Info.keepEvaluatingAfterFailure())
6414         return false;
6415       Success = false;
6416     }
6417     ++CaptureIt;
6418   }
6419   return Success;
6420 }
6421 
6422 static bool EvaluateRecord(const Expr *E, const LValue &This,
6423                            APValue &Result, EvalInfo &Info) {
6424   assert(E->isRValue() && E->getType()->isRecordType() &&
6425          "can't evaluate expression as a record rvalue");
6426   return RecordExprEvaluator(Info, This, Result).Visit(E);
6427 }
6428 
6429 //===----------------------------------------------------------------------===//
6430 // Temporary Evaluation
6431 //
6432 // Temporaries are represented in the AST as rvalues, but generally behave like
6433 // lvalues. The full-object of which the temporary is a subobject is implicitly
6434 // materialized so that a reference can bind to it.
6435 //===----------------------------------------------------------------------===//
6436 namespace {
6437 class TemporaryExprEvaluator
6438   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6439 public:
6440   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
6441     LValueExprEvaluatorBaseTy(Info, Result, false) {}
6442 
6443   /// Visit an expression which constructs the value of this temporary.
6444   bool VisitConstructExpr(const Expr *E) {
6445     Result.set(E, Info.CurrentCall->Index);
6446     return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6447                            Info, Result, E);
6448   }
6449 
6450   bool VisitCastExpr(const CastExpr *E) {
6451     switch (E->getCastKind()) {
6452     default:
6453       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6454 
6455     case CK_ConstructorConversion:
6456       return VisitConstructExpr(E->getSubExpr());
6457     }
6458   }
6459   bool VisitInitListExpr(const InitListExpr *E) {
6460     return VisitConstructExpr(E);
6461   }
6462   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6463     return VisitConstructExpr(E);
6464   }
6465   bool VisitCallExpr(const CallExpr *E) {
6466     return VisitConstructExpr(E);
6467   }
6468   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6469     return VisitConstructExpr(E);
6470   }
6471   bool VisitLambdaExpr(const LambdaExpr *E) {
6472     return VisitConstructExpr(E);
6473   }
6474 };
6475 } // end anonymous namespace
6476 
6477 /// Evaluate an expression of record type as a temporary.
6478 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
6479   assert(E->isRValue() && E->getType()->isRecordType());
6480   return TemporaryExprEvaluator(Info, Result).Visit(E);
6481 }
6482 
6483 //===----------------------------------------------------------------------===//
6484 // Vector Evaluation
6485 //===----------------------------------------------------------------------===//
6486 
6487 namespace {
6488   class VectorExprEvaluator
6489   : public ExprEvaluatorBase<VectorExprEvaluator> {
6490     APValue &Result;
6491   public:
6492 
6493     VectorExprEvaluator(EvalInfo &info, APValue &Result)
6494       : ExprEvaluatorBaseTy(info), Result(Result) {}
6495 
6496     bool Success(ArrayRef<APValue> V, const Expr *E) {
6497       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6498       // FIXME: remove this APValue copy.
6499       Result = APValue(V.data(), V.size());
6500       return true;
6501     }
6502     bool Success(const APValue &V, const Expr *E) {
6503       assert(V.isVector());
6504       Result = V;
6505       return true;
6506     }
6507     bool ZeroInitialization(const Expr *E);
6508 
6509     bool VisitUnaryReal(const UnaryOperator *E)
6510       { return Visit(E->getSubExpr()); }
6511     bool VisitCastExpr(const CastExpr* E);
6512     bool VisitInitListExpr(const InitListExpr *E);
6513     bool VisitUnaryImag(const UnaryOperator *E);
6514     // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
6515     //                 binary comparisons, binary and/or/xor,
6516     //                 shufflevector, ExtVectorElementExpr
6517   };
6518 } // end anonymous namespace
6519 
6520 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
6521   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
6522   return VectorExprEvaluator(Info, Result).Visit(E);
6523 }
6524 
6525 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
6526   const VectorType *VTy = E->getType()->castAs<VectorType>();
6527   unsigned NElts = VTy->getNumElements();
6528 
6529   const Expr *SE = E->getSubExpr();
6530   QualType SETy = SE->getType();
6531 
6532   switch (E->getCastKind()) {
6533   case CK_VectorSplat: {
6534     APValue Val = APValue();
6535     if (SETy->isIntegerType()) {
6536       APSInt IntResult;
6537       if (!EvaluateInteger(SE, IntResult, Info))
6538         return false;
6539       Val = APValue(std::move(IntResult));
6540     } else if (SETy->isRealFloatingType()) {
6541       APFloat FloatResult(0.0);
6542       if (!EvaluateFloat(SE, FloatResult, Info))
6543         return false;
6544       Val = APValue(std::move(FloatResult));
6545     } else {
6546       return Error(E);
6547     }
6548 
6549     // Splat and create vector APValue.
6550     SmallVector<APValue, 4> Elts(NElts, Val);
6551     return Success(Elts, E);
6552   }
6553   case CK_BitCast: {
6554     // Evaluate the operand into an APInt we can extract from.
6555     llvm::APInt SValInt;
6556     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6557       return false;
6558     // Extract the elements
6559     QualType EltTy = VTy->getElementType();
6560     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6561     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6562     SmallVector<APValue, 4> Elts;
6563     if (EltTy->isRealFloatingType()) {
6564       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
6565       unsigned FloatEltSize = EltSize;
6566       if (&Sem == &APFloat::x87DoubleExtended())
6567         FloatEltSize = 80;
6568       for (unsigned i = 0; i < NElts; i++) {
6569         llvm::APInt Elt;
6570         if (BigEndian)
6571           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6572         else
6573           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
6574         Elts.push_back(APValue(APFloat(Sem, Elt)));
6575       }
6576     } else if (EltTy->isIntegerType()) {
6577       for (unsigned i = 0; i < NElts; i++) {
6578         llvm::APInt Elt;
6579         if (BigEndian)
6580           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6581         else
6582           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6583         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6584       }
6585     } else {
6586       return Error(E);
6587     }
6588     return Success(Elts, E);
6589   }
6590   default:
6591     return ExprEvaluatorBaseTy::VisitCastExpr(E);
6592   }
6593 }
6594 
6595 bool
6596 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6597   const VectorType *VT = E->getType()->castAs<VectorType>();
6598   unsigned NumInits = E->getNumInits();
6599   unsigned NumElements = VT->getNumElements();
6600 
6601   QualType EltTy = VT->getElementType();
6602   SmallVector<APValue, 4> Elements;
6603 
6604   // The number of initializers can be less than the number of
6605   // vector elements. For OpenCL, this can be due to nested vector
6606   // initialization. For GCC compatibility, missing trailing elements
6607   // should be initialized with zeroes.
6608   unsigned CountInits = 0, CountElts = 0;
6609   while (CountElts < NumElements) {
6610     // Handle nested vector initialization.
6611     if (CountInits < NumInits
6612         && E->getInit(CountInits)->getType()->isVectorType()) {
6613       APValue v;
6614       if (!EvaluateVector(E->getInit(CountInits), v, Info))
6615         return Error(E);
6616       unsigned vlen = v.getVectorLength();
6617       for (unsigned j = 0; j < vlen; j++)
6618         Elements.push_back(v.getVectorElt(j));
6619       CountElts += vlen;
6620     } else if (EltTy->isIntegerType()) {
6621       llvm::APSInt sInt(32);
6622       if (CountInits < NumInits) {
6623         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
6624           return false;
6625       } else // trailing integer zero.
6626         sInt = Info.Ctx.MakeIntValue(0, EltTy);
6627       Elements.push_back(APValue(sInt));
6628       CountElts++;
6629     } else {
6630       llvm::APFloat f(0.0);
6631       if (CountInits < NumInits) {
6632         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
6633           return false;
6634       } else // trailing float zero.
6635         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6636       Elements.push_back(APValue(f));
6637       CountElts++;
6638     }
6639     CountInits++;
6640   }
6641   return Success(Elements, E);
6642 }
6643 
6644 bool
6645 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
6646   const VectorType *VT = E->getType()->getAs<VectorType>();
6647   QualType EltTy = VT->getElementType();
6648   APValue ZeroElement;
6649   if (EltTy->isIntegerType())
6650     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6651   else
6652     ZeroElement =
6653         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6654 
6655   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
6656   return Success(Elements, E);
6657 }
6658 
6659 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6660   VisitIgnoredValue(E->getSubExpr());
6661   return ZeroInitialization(E);
6662 }
6663 
6664 //===----------------------------------------------------------------------===//
6665 // Array Evaluation
6666 //===----------------------------------------------------------------------===//
6667 
6668 namespace {
6669   class ArrayExprEvaluator
6670   : public ExprEvaluatorBase<ArrayExprEvaluator> {
6671     const LValue &This;
6672     APValue &Result;
6673   public:
6674 
6675     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6676       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
6677 
6678     bool Success(const APValue &V, const Expr *E) {
6679       assert((V.isArray() || V.isLValue()) &&
6680              "expected array or string literal");
6681       Result = V;
6682       return true;
6683     }
6684 
6685     bool ZeroInitialization(const Expr *E) {
6686       const ConstantArrayType *CAT =
6687           Info.Ctx.getAsConstantArrayType(E->getType());
6688       if (!CAT)
6689         return Error(E);
6690 
6691       Result = APValue(APValue::UninitArray(), 0,
6692                        CAT->getSize().getZExtValue());
6693       if (!Result.hasArrayFiller()) return true;
6694 
6695       // Zero-initialize all elements.
6696       LValue Subobject = This;
6697       Subobject.addArray(Info, E, CAT);
6698       ImplicitValueInitExpr VIE(CAT->getElementType());
6699       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
6700     }
6701 
6702     bool VisitCallExpr(const CallExpr *E) {
6703       return handleCallExpr(E, Result, &This);
6704     }
6705     bool VisitInitListExpr(const InitListExpr *E);
6706     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
6707     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
6708     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6709                                const LValue &Subobject,
6710                                APValue *Value, QualType Type);
6711   };
6712 } // end anonymous namespace
6713 
6714 static bool EvaluateArray(const Expr *E, const LValue &This,
6715                           APValue &Result, EvalInfo &Info) {
6716   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
6717   return ArrayExprEvaluator(Info, This, Result).Visit(E);
6718 }
6719 
6720 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6721   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6722   if (!CAT)
6723     return Error(E);
6724 
6725   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6726   // an appropriately-typed string literal enclosed in braces.
6727   if (E->isStringLiteralInit()) {
6728     LValue LV;
6729     if (!EvaluateLValue(E->getInit(0), LV, Info))
6730       return false;
6731     APValue Val;
6732     LV.moveInto(Val);
6733     return Success(Val, E);
6734   }
6735 
6736   bool Success = true;
6737 
6738   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6739          "zero-initialized array shouldn't have any initialized elts");
6740   APValue Filler;
6741   if (Result.isArray() && Result.hasArrayFiller())
6742     Filler = Result.getArrayFiller();
6743 
6744   unsigned NumEltsToInit = E->getNumInits();
6745   unsigned NumElts = CAT->getSize().getZExtValue();
6746   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
6747 
6748   // If the initializer might depend on the array index, run it for each
6749   // array element. For now, just whitelist non-class value-initialization.
6750   if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6751     NumEltsToInit = NumElts;
6752 
6753   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
6754 
6755   // If the array was previously zero-initialized, preserve the
6756   // zero-initialized values.
6757   if (!Filler.isUninit()) {
6758     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6759       Result.getArrayInitializedElt(I) = Filler;
6760     if (Result.hasArrayFiller())
6761       Result.getArrayFiller() = Filler;
6762   }
6763 
6764   LValue Subobject = This;
6765   Subobject.addArray(Info, E, CAT);
6766   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6767     const Expr *Init =
6768         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
6769     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6770                          Info, Subobject, Init) ||
6771         !HandleLValueArrayAdjustment(Info, Init, Subobject,
6772                                      CAT->getElementType(), 1)) {
6773       if (!Info.noteFailure())
6774         return false;
6775       Success = false;
6776     }
6777   }
6778 
6779   if (!Result.hasArrayFiller())
6780     return Success;
6781 
6782   // If we get here, we have a trivial filler, which we can just evaluate
6783   // once and splat over the rest of the array elements.
6784   assert(FillerExpr && "no array filler for incomplete init list");
6785   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6786                          FillerExpr) && Success;
6787 }
6788 
6789 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6790   if (E->getCommonExpr() &&
6791       !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6792                 Info, E->getCommonExpr()->getSourceExpr()))
6793     return false;
6794 
6795   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6796 
6797   uint64_t Elements = CAT->getSize().getZExtValue();
6798   Result = APValue(APValue::UninitArray(), Elements, Elements);
6799 
6800   LValue Subobject = This;
6801   Subobject.addArray(Info, E, CAT);
6802 
6803   bool Success = true;
6804   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6805     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6806                          Info, Subobject, E->getSubExpr()) ||
6807         !HandleLValueArrayAdjustment(Info, E, Subobject,
6808                                      CAT->getElementType(), 1)) {
6809       if (!Info.noteFailure())
6810         return false;
6811       Success = false;
6812     }
6813   }
6814 
6815   return Success;
6816 }
6817 
6818 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
6819   return VisitCXXConstructExpr(E, This, &Result, E->getType());
6820 }
6821 
6822 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6823                                                const LValue &Subobject,
6824                                                APValue *Value,
6825                                                QualType Type) {
6826   bool HadZeroInit = !Value->isUninit();
6827 
6828   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6829     unsigned N = CAT->getSize().getZExtValue();
6830 
6831     // Preserve the array filler if we had prior zero-initialization.
6832     APValue Filler =
6833       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6834                                              : APValue();
6835 
6836     *Value = APValue(APValue::UninitArray(), N, N);
6837 
6838     if (HadZeroInit)
6839       for (unsigned I = 0; I != N; ++I)
6840         Value->getArrayInitializedElt(I) = Filler;
6841 
6842     // Initialize the elements.
6843     LValue ArrayElt = Subobject;
6844     ArrayElt.addArray(Info, E, CAT);
6845     for (unsigned I = 0; I != N; ++I)
6846       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6847                                  CAT->getElementType()) ||
6848           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6849                                        CAT->getElementType(), 1))
6850         return false;
6851 
6852     return true;
6853   }
6854 
6855   if (!Type->isRecordType())
6856     return Error(E);
6857 
6858   return RecordExprEvaluator(Info, Subobject, *Value)
6859              .VisitCXXConstructExpr(E, Type);
6860 }
6861 
6862 //===----------------------------------------------------------------------===//
6863 // Integer Evaluation
6864 //
6865 // As a GNU extension, we support casting pointers to sufficiently-wide integer
6866 // types and back in constant folding. Integer values are thus represented
6867 // either as an integer-valued APValue, or as an lvalue-valued APValue.
6868 //===----------------------------------------------------------------------===//
6869 
6870 namespace {
6871 class IntExprEvaluator
6872   : public ExprEvaluatorBase<IntExprEvaluator> {
6873   APValue &Result;
6874 public:
6875   IntExprEvaluator(EvalInfo &info, APValue &result)
6876     : ExprEvaluatorBaseTy(info), Result(result) {}
6877 
6878   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
6879     assert(E->getType()->isIntegralOrEnumerationType() &&
6880            "Invalid evaluation result.");
6881     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
6882            "Invalid evaluation result.");
6883     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
6884            "Invalid evaluation result.");
6885     Result = APValue(SI);
6886     return true;
6887   }
6888   bool Success(const llvm::APSInt &SI, const Expr *E) {
6889     return Success(SI, E, Result);
6890   }
6891 
6892   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
6893     assert(E->getType()->isIntegralOrEnumerationType() &&
6894            "Invalid evaluation result.");
6895     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
6896            "Invalid evaluation result.");
6897     Result = APValue(APSInt(I));
6898     Result.getInt().setIsUnsigned(
6899                             E->getType()->isUnsignedIntegerOrEnumerationType());
6900     return true;
6901   }
6902   bool Success(const llvm::APInt &I, const Expr *E) {
6903     return Success(I, E, Result);
6904   }
6905 
6906   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6907     assert(E->getType()->isIntegralOrEnumerationType() &&
6908            "Invalid evaluation result.");
6909     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
6910     return true;
6911   }
6912   bool Success(uint64_t Value, const Expr *E) {
6913     return Success(Value, E, Result);
6914   }
6915 
6916   bool Success(CharUnits Size, const Expr *E) {
6917     return Success(Size.getQuantity(), E);
6918   }
6919 
6920   bool Success(const APValue &V, const Expr *E) {
6921     if (V.isLValue() || V.isAddrLabelDiff()) {
6922       Result = V;
6923       return true;
6924     }
6925     return Success(V.getInt(), E);
6926   }
6927 
6928   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
6929 
6930   //===--------------------------------------------------------------------===//
6931   //                            Visitor Methods
6932   //===--------------------------------------------------------------------===//
6933 
6934   bool VisitIntegerLiteral(const IntegerLiteral *E) {
6935     return Success(E->getValue(), E);
6936   }
6937   bool VisitCharacterLiteral(const CharacterLiteral *E) {
6938     return Success(E->getValue(), E);
6939   }
6940 
6941   bool CheckReferencedDecl(const Expr *E, const Decl *D);
6942   bool VisitDeclRefExpr(const DeclRefExpr *E) {
6943     if (CheckReferencedDecl(E, E->getDecl()))
6944       return true;
6945 
6946     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
6947   }
6948   bool VisitMemberExpr(const MemberExpr *E) {
6949     if (CheckReferencedDecl(E, E->getMemberDecl())) {
6950       VisitIgnoredBaseExpression(E->getBase());
6951       return true;
6952     }
6953 
6954     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
6955   }
6956 
6957   bool VisitCallExpr(const CallExpr *E);
6958   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
6959   bool VisitBinaryOperator(const BinaryOperator *E);
6960   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
6961   bool VisitUnaryOperator(const UnaryOperator *E);
6962 
6963   bool VisitCastExpr(const CastExpr* E);
6964   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
6965 
6966   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
6967     return Success(E->getValue(), E);
6968   }
6969 
6970   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6971     return Success(E->getValue(), E);
6972   }
6973 
6974   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
6975     if (Info.ArrayInitIndex == uint64_t(-1)) {
6976       // We were asked to evaluate this subexpression independent of the
6977       // enclosing ArrayInitLoopExpr. We can't do that.
6978       Info.FFDiag(E);
6979       return false;
6980     }
6981     return Success(Info.ArrayInitIndex, E);
6982   }
6983 
6984   // Note, GNU defines __null as an integer, not a pointer.
6985   bool VisitGNUNullExpr(const GNUNullExpr *E) {
6986     return ZeroInitialization(E);
6987   }
6988 
6989   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6990     return Success(E->getValue(), E);
6991   }
6992 
6993   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6994     return Success(E->getValue(), E);
6995   }
6996 
6997   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6998     return Success(E->getValue(), E);
6999   }
7000 
7001   bool VisitUnaryReal(const UnaryOperator *E);
7002   bool VisitUnaryImag(const UnaryOperator *E);
7003 
7004   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
7005   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
7006 
7007   // FIXME: Missing: array subscript of vector, member of vector
7008 };
7009 } // end anonymous namespace
7010 
7011 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7012 /// produce either the integer value or a pointer.
7013 ///
7014 /// GCC has a heinous extension which folds casts between pointer types and
7015 /// pointer-sized integral types. We support this by allowing the evaluation of
7016 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7017 /// Some simple arithmetic on such values is supported (they are treated much
7018 /// like char*).
7019 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
7020                                     EvalInfo &Info) {
7021   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
7022   return IntExprEvaluator(Info, Result).Visit(E);
7023 }
7024 
7025 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
7026   APValue Val;
7027   if (!EvaluateIntegerOrLValue(E, Val, Info))
7028     return false;
7029   if (!Val.isInt()) {
7030     // FIXME: It would be better to produce the diagnostic for casting
7031     //        a pointer to an integer.
7032     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
7033     return false;
7034   }
7035   Result = Val.getInt();
7036   return true;
7037 }
7038 
7039 /// Check whether the given declaration can be directly converted to an integral
7040 /// rvalue. If not, no diagnostic is produced; there are other things we can
7041 /// try.
7042 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
7043   // Enums are integer constant exprs.
7044   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
7045     // Check for signedness/width mismatches between E type and ECD value.
7046     bool SameSign = (ECD->getInitVal().isSigned()
7047                      == E->getType()->isSignedIntegerOrEnumerationType());
7048     bool SameWidth = (ECD->getInitVal().getBitWidth()
7049                       == Info.Ctx.getIntWidth(E->getType()));
7050     if (SameSign && SameWidth)
7051       return Success(ECD->getInitVal(), E);
7052     else {
7053       // Get rid of mismatch (otherwise Success assertions will fail)
7054       // by computing a new value matching the type of E.
7055       llvm::APSInt Val = ECD->getInitVal();
7056       if (!SameSign)
7057         Val.setIsSigned(!ECD->getInitVal().isSigned());
7058       if (!SameWidth)
7059         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7060       return Success(Val, E);
7061     }
7062   }
7063   return false;
7064 }
7065 
7066 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7067 /// as GCC.
7068 static int EvaluateBuiltinClassifyType(const CallExpr *E,
7069                                        const LangOptions &LangOpts) {
7070   // The following enum mimics the values returned by GCC.
7071   // FIXME: Does GCC differ between lvalue and rvalue references here?
7072   enum gcc_type_class {
7073     no_type_class = -1,
7074     void_type_class, integer_type_class, char_type_class,
7075     enumeral_type_class, boolean_type_class,
7076     pointer_type_class, reference_type_class, offset_type_class,
7077     real_type_class, complex_type_class,
7078     function_type_class, method_type_class,
7079     record_type_class, union_type_class,
7080     array_type_class, string_type_class,
7081     lang_type_class
7082   };
7083 
7084   // If no argument was supplied, default to "no_type_class". This isn't
7085   // ideal, however it is what gcc does.
7086   if (E->getNumArgs() == 0)
7087     return no_type_class;
7088 
7089   QualType CanTy = E->getArg(0)->getType().getCanonicalType();
7090   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7091 
7092   switch (CanTy->getTypeClass()) {
7093 #define TYPE(ID, BASE)
7094 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7095 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7096 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7097 #include "clang/AST/TypeNodes.def"
7098       llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7099 
7100   case Type::Builtin:
7101     switch (BT->getKind()) {
7102 #define BUILTIN_TYPE(ID, SINGLETON_ID)
7103 #define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
7104 #define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
7105 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
7106 #include "clang/AST/BuiltinTypes.def"
7107     case BuiltinType::Void:
7108       return void_type_class;
7109 
7110     case BuiltinType::Bool:
7111       return boolean_type_class;
7112 
7113     case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
7114     case BuiltinType::UChar:
7115     case BuiltinType::UShort:
7116     case BuiltinType::UInt:
7117     case BuiltinType::ULong:
7118     case BuiltinType::ULongLong:
7119     case BuiltinType::UInt128:
7120       return integer_type_class;
7121 
7122     case BuiltinType::NullPtr:
7123       return pointer_type_class;
7124 
7125     case BuiltinType::WChar_U:
7126     case BuiltinType::Char16:
7127     case BuiltinType::Char32:
7128     case BuiltinType::ObjCId:
7129     case BuiltinType::ObjCClass:
7130     case BuiltinType::ObjCSel:
7131 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7132     case BuiltinType::Id:
7133 #include "clang/Basic/OpenCLImageTypes.def"
7134     case BuiltinType::OCLSampler:
7135     case BuiltinType::OCLEvent:
7136     case BuiltinType::OCLClkEvent:
7137     case BuiltinType::OCLQueue:
7138     case BuiltinType::OCLReserveID:
7139     case BuiltinType::Dependent:
7140       llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7141     };
7142 
7143   case Type::Enum:
7144     return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7145     break;
7146 
7147   case Type::Pointer:
7148     return pointer_type_class;
7149     break;
7150 
7151   case Type::MemberPointer:
7152     if (CanTy->isMemberDataPointerType())
7153       return offset_type_class;
7154     else {
7155       // We expect member pointers to be either data or function pointers,
7156       // nothing else.
7157       assert(CanTy->isMemberFunctionPointerType());
7158       return method_type_class;
7159     }
7160 
7161   case Type::Complex:
7162     return complex_type_class;
7163 
7164   case Type::FunctionNoProto:
7165   case Type::FunctionProto:
7166     return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7167 
7168   case Type::Record:
7169     if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7170       switch (RT->getDecl()->getTagKind()) {
7171       case TagTypeKind::TTK_Struct:
7172       case TagTypeKind::TTK_Class:
7173       case TagTypeKind::TTK_Interface:
7174         return record_type_class;
7175 
7176       case TagTypeKind::TTK_Enum:
7177         return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7178 
7179       case TagTypeKind::TTK_Union:
7180         return union_type_class;
7181       }
7182     }
7183     llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7184 
7185   case Type::ConstantArray:
7186   case Type::VariableArray:
7187   case Type::IncompleteArray:
7188     return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7189 
7190   case Type::BlockPointer:
7191   case Type::LValueReference:
7192   case Type::RValueReference:
7193   case Type::Vector:
7194   case Type::ExtVector:
7195   case Type::Auto:
7196   case Type::DeducedTemplateSpecialization:
7197   case Type::ObjCObject:
7198   case Type::ObjCInterface:
7199   case Type::ObjCObjectPointer:
7200   case Type::Pipe:
7201   case Type::Atomic:
7202     llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7203   }
7204 
7205   llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7206 }
7207 
7208 /// EvaluateBuiltinConstantPForLValue - Determine the result of
7209 /// __builtin_constant_p when applied to the given lvalue.
7210 ///
7211 /// An lvalue is only "constant" if it is a pointer or reference to the first
7212 /// character of a string literal.
7213 template<typename LValue>
7214 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
7215   const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
7216   return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7217 }
7218 
7219 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7220 /// GCC as we can manage.
7221 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7222   QualType ArgType = Arg->getType();
7223 
7224   // __builtin_constant_p always has one operand. The rules which gcc follows
7225   // are not precisely documented, but are as follows:
7226   //
7227   //  - If the operand is of integral, floating, complex or enumeration type,
7228   //    and can be folded to a known value of that type, it returns 1.
7229   //  - If the operand and can be folded to a pointer to the first character
7230   //    of a string literal (or such a pointer cast to an integral type), it
7231   //    returns 1.
7232   //
7233   // Otherwise, it returns 0.
7234   //
7235   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7236   // its support for this does not currently work.
7237   if (ArgType->isIntegralOrEnumerationType()) {
7238     Expr::EvalResult Result;
7239     if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7240       return false;
7241 
7242     APValue &V = Result.Val;
7243     if (V.getKind() == APValue::Int)
7244       return true;
7245     if (V.getKind() == APValue::LValue)
7246       return EvaluateBuiltinConstantPForLValue(V);
7247   } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7248     return Arg->isEvaluatable(Ctx);
7249   } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7250     LValue LV;
7251     Expr::EvalStatus Status;
7252     EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
7253     if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7254                           : EvaluatePointer(Arg, LV, Info)) &&
7255         !Status.HasSideEffects)
7256       return EvaluateBuiltinConstantPForLValue(LV);
7257   }
7258 
7259   // Anything else isn't considered to be sufficiently constant.
7260   return false;
7261 }
7262 
7263 /// Retrieves the "underlying object type" of the given expression,
7264 /// as used by __builtin_object_size.
7265 static QualType getObjectType(APValue::LValueBase B) {
7266   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7267     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
7268       return VD->getType();
7269   } else if (const Expr *E = B.get<const Expr*>()) {
7270     if (isa<CompoundLiteralExpr>(E))
7271       return E->getType();
7272   }
7273 
7274   return QualType();
7275 }
7276 
7277 /// A more selective version of E->IgnoreParenCasts for
7278 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
7279 /// to change the type of E.
7280 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7281 ///
7282 /// Always returns an RValue with a pointer representation.
7283 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7284   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7285 
7286   auto *NoParens = E->IgnoreParens();
7287   auto *Cast = dyn_cast<CastExpr>(NoParens);
7288   if (Cast == nullptr)
7289     return NoParens;
7290 
7291   // We only conservatively allow a few kinds of casts, because this code is
7292   // inherently a simple solution that seeks to support the common case.
7293   auto CastKind = Cast->getCastKind();
7294   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7295       CastKind != CK_AddressSpaceConversion)
7296     return NoParens;
7297 
7298   auto *SubExpr = Cast->getSubExpr();
7299   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7300     return NoParens;
7301   return ignorePointerCastsAndParens(SubExpr);
7302 }
7303 
7304 /// Checks to see if the given LValue's Designator is at the end of the LValue's
7305 /// record layout. e.g.
7306 ///   struct { struct { int a, b; } fst, snd; } obj;
7307 ///   obj.fst   // no
7308 ///   obj.snd   // yes
7309 ///   obj.fst.a // no
7310 ///   obj.fst.b // no
7311 ///   obj.snd.a // no
7312 ///   obj.snd.b // yes
7313 ///
7314 /// Please note: this function is specialized for how __builtin_object_size
7315 /// views "objects".
7316 ///
7317 /// If this encounters an invalid RecordDecl, it will always return true.
7318 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7319   assert(!LVal.Designator.Invalid);
7320 
7321   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7322     const RecordDecl *Parent = FD->getParent();
7323     Invalid = Parent->isInvalidDecl();
7324     if (Invalid || Parent->isUnion())
7325       return true;
7326     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
7327     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7328   };
7329 
7330   auto &Base = LVal.getLValueBase();
7331   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7332     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
7333       bool Invalid;
7334       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7335         return Invalid;
7336     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
7337       for (auto *FD : IFD->chain()) {
7338         bool Invalid;
7339         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7340           return Invalid;
7341       }
7342     }
7343   }
7344 
7345   unsigned I = 0;
7346   QualType BaseType = getType(Base);
7347   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7348     assert(isBaseAnAllocSizeCall(Base) &&
7349            "Unsized array in non-alloc_size call?");
7350     // If this is an alloc_size base, we should ignore the initial array index
7351     ++I;
7352     BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7353   }
7354 
7355   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7356     const auto &Entry = LVal.Designator.Entries[I];
7357     if (BaseType->isArrayType()) {
7358       // Because __builtin_object_size treats arrays as objects, we can ignore
7359       // the index iff this is the last array in the Designator.
7360       if (I + 1 == E)
7361         return true;
7362       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7363       uint64_t Index = Entry.ArrayIndex;
7364       if (Index + 1 != CAT->getSize())
7365         return false;
7366       BaseType = CAT->getElementType();
7367     } else if (BaseType->isAnyComplexType()) {
7368       const auto *CT = BaseType->castAs<ComplexType>();
7369       uint64_t Index = Entry.ArrayIndex;
7370       if (Index != 1)
7371         return false;
7372       BaseType = CT->getElementType();
7373     } else if (auto *FD = getAsField(Entry)) {
7374       bool Invalid;
7375       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7376         return Invalid;
7377       BaseType = FD->getType();
7378     } else {
7379       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
7380       return false;
7381     }
7382   }
7383   return true;
7384 }
7385 
7386 /// Tests to see if the LValue has a user-specified designator (that isn't
7387 /// necessarily valid). Note that this always returns 'true' if the LValue has
7388 /// an unsized array as its first designator entry, because there's currently no
7389 /// way to tell if the user typed *foo or foo[0].
7390 static bool refersToCompleteObject(const LValue &LVal) {
7391   if (LVal.Designator.Invalid)
7392     return false;
7393 
7394   if (!LVal.Designator.Entries.empty())
7395     return LVal.Designator.isMostDerivedAnUnsizedArray();
7396 
7397   if (!LVal.InvalidBase)
7398     return true;
7399 
7400   // If `E` is a MemberExpr, then the first part of the designator is hiding in
7401   // the LValueBase.
7402   const auto *E = LVal.Base.dyn_cast<const Expr *>();
7403   return !E || !isa<MemberExpr>(E);
7404 }
7405 
7406 /// Attempts to detect a user writing into a piece of memory that's impossible
7407 /// to figure out the size of by just using types.
7408 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7409   const SubobjectDesignator &Designator = LVal.Designator;
7410   // Notes:
7411   // - Users can only write off of the end when we have an invalid base. Invalid
7412   //   bases imply we don't know where the memory came from.
7413   // - We used to be a bit more aggressive here; we'd only be conservative if
7414   //   the array at the end was flexible, or if it had 0 or 1 elements. This
7415   //   broke some common standard library extensions (PR30346), but was
7416   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
7417   //   with some sort of whitelist. OTOH, it seems that GCC is always
7418   //   conservative with the last element in structs (if it's an array), so our
7419   //   current behavior is more compatible than a whitelisting approach would
7420   //   be.
7421   return LVal.InvalidBase &&
7422          Designator.Entries.size() == Designator.MostDerivedPathLength &&
7423          Designator.MostDerivedIsArrayElement &&
7424          isDesignatorAtObjectEnd(Ctx, LVal);
7425 }
7426 
7427 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7428 /// Fails if the conversion would cause loss of precision.
7429 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7430                                             CharUnits &Result) {
7431   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7432   if (Int.ugt(CharUnitsMax))
7433     return false;
7434   Result = CharUnits::fromQuantity(Int.getZExtValue());
7435   return true;
7436 }
7437 
7438 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7439 /// determine how many bytes exist from the beginning of the object to either
7440 /// the end of the current subobject, or the end of the object itself, depending
7441 /// on what the LValue looks like + the value of Type.
7442 ///
7443 /// If this returns false, the value of Result is undefined.
7444 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7445                                unsigned Type, const LValue &LVal,
7446                                CharUnits &EndOffset) {
7447   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
7448 
7449   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7450     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7451       return false;
7452     return HandleSizeof(Info, ExprLoc, Ty, Result);
7453   };
7454 
7455   // We want to evaluate the size of the entire object. This is a valid fallback
7456   // for when Type=1 and the designator is invalid, because we're asked for an
7457   // upper-bound.
7458   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7459     // Type=3 wants a lower bound, so we can't fall back to this.
7460     if (Type == 3 && !DetermineForCompleteObject)
7461       return false;
7462 
7463     llvm::APInt APEndOffset;
7464     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7465         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7466       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7467 
7468     if (LVal.InvalidBase)
7469       return false;
7470 
7471     QualType BaseTy = getObjectType(LVal.getLValueBase());
7472     return CheckedHandleSizeof(BaseTy, EndOffset);
7473   }
7474 
7475   // We want to evaluate the size of a subobject.
7476   const SubobjectDesignator &Designator = LVal.Designator;
7477 
7478   // The following is a moderately common idiom in C:
7479   //
7480   // struct Foo { int a; char c[1]; };
7481   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7482   // strcpy(&F->c[0], Bar);
7483   //
7484   // In order to not break too much legacy code, we need to support it.
7485   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7486     // If we can resolve this to an alloc_size call, we can hand that back,
7487     // because we know for certain how many bytes there are to write to.
7488     llvm::APInt APEndOffset;
7489     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7490         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7491       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7492 
7493     // If we cannot determine the size of the initial allocation, then we can't
7494     // given an accurate upper-bound. However, we are still able to give
7495     // conservative lower-bounds for Type=3.
7496     if (Type == 1)
7497       return false;
7498   }
7499 
7500   CharUnits BytesPerElem;
7501   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
7502     return false;
7503 
7504   // According to the GCC documentation, we want the size of the subobject
7505   // denoted by the pointer. But that's not quite right -- what we actually
7506   // want is the size of the immediately-enclosing array, if there is one.
7507   int64_t ElemsRemaining;
7508   if (Designator.MostDerivedIsArrayElement &&
7509       Designator.Entries.size() == Designator.MostDerivedPathLength) {
7510     uint64_t ArraySize = Designator.getMostDerivedArraySize();
7511     uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7512     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7513   } else {
7514     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7515   }
7516 
7517   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7518   return true;
7519 }
7520 
7521 /// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7522 /// returns true and stores the result in @p Size.
7523 ///
7524 /// If @p WasError is non-null, this will report whether the failure to evaluate
7525 /// is to be treated as an Error in IntExprEvaluator.
7526 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7527                                          EvalInfo &Info, uint64_t &Size) {
7528   // Determine the denoted object.
7529   LValue LVal;
7530   {
7531     // The operand of __builtin_object_size is never evaluated for side-effects.
7532     // If there are any, but we can determine the pointed-to object anyway, then
7533     // ignore the side-effects.
7534     SpeculativeEvaluationRAII SpeculativeEval(Info);
7535     FoldOffsetRAII Fold(Info);
7536 
7537     if (E->isGLValue()) {
7538       // It's possible for us to be given GLValues if we're called via
7539       // Expr::tryEvaluateObjectSize.
7540       APValue RVal;
7541       if (!EvaluateAsRValue(Info, E, RVal))
7542         return false;
7543       LVal.setFrom(Info.Ctx, RVal);
7544     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7545                                 /*InvalidBaseOK=*/true))
7546       return false;
7547   }
7548 
7549   // If we point to before the start of the object, there are no accessible
7550   // bytes.
7551   if (LVal.getLValueOffset().isNegative()) {
7552     Size = 0;
7553     return true;
7554   }
7555 
7556   CharUnits EndOffset;
7557   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7558     return false;
7559 
7560   // If we've fallen outside of the end offset, just pretend there's nothing to
7561   // write to/read from.
7562   if (EndOffset <= LVal.getLValueOffset())
7563     Size = 0;
7564   else
7565     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7566   return true;
7567 }
7568 
7569 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
7570   if (unsigned BuiltinOp = E->getBuiltinCallee())
7571     return VisitBuiltinCallExpr(E, BuiltinOp);
7572 
7573   return ExprEvaluatorBaseTy::VisitCallExpr(E);
7574 }
7575 
7576 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7577                                             unsigned BuiltinOp) {
7578   switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
7579   default:
7580     return ExprEvaluatorBaseTy::VisitCallExpr(E);
7581 
7582   case Builtin::BI__builtin_object_size: {
7583     // The type was checked when we built the expression.
7584     unsigned Type =
7585         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7586     assert(Type <= 3 && "unexpected type");
7587 
7588     uint64_t Size;
7589     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7590       return Success(Size, E);
7591 
7592     if (E->getArg(0)->HasSideEffects(Info.Ctx))
7593       return Success((Type & 2) ? 0 : -1, E);
7594 
7595     // Expression had no side effects, but we couldn't statically determine the
7596     // size of the referenced object.
7597     switch (Info.EvalMode) {
7598     case EvalInfo::EM_ConstantExpression:
7599     case EvalInfo::EM_PotentialConstantExpression:
7600     case EvalInfo::EM_ConstantFold:
7601     case EvalInfo::EM_EvaluateForOverflow:
7602     case EvalInfo::EM_IgnoreSideEffects:
7603     case EvalInfo::EM_OffsetFold:
7604       // Leave it to IR generation.
7605       return Error(E);
7606     case EvalInfo::EM_ConstantExpressionUnevaluated:
7607     case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
7608       // Reduce it to a constant now.
7609       return Success((Type & 2) ? 0 : -1, E);
7610     }
7611 
7612     llvm_unreachable("unexpected EvalMode");
7613   }
7614 
7615   case Builtin::BI__builtin_bswap16:
7616   case Builtin::BI__builtin_bswap32:
7617   case Builtin::BI__builtin_bswap64: {
7618     APSInt Val;
7619     if (!EvaluateInteger(E->getArg(0), Val, Info))
7620       return false;
7621 
7622     return Success(Val.byteSwap(), E);
7623   }
7624 
7625   case Builtin::BI__builtin_classify_type:
7626     return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
7627 
7628   // FIXME: BI__builtin_clrsb
7629   // FIXME: BI__builtin_clrsbl
7630   // FIXME: BI__builtin_clrsbll
7631 
7632   case Builtin::BI__builtin_clz:
7633   case Builtin::BI__builtin_clzl:
7634   case Builtin::BI__builtin_clzll:
7635   case Builtin::BI__builtin_clzs: {
7636     APSInt Val;
7637     if (!EvaluateInteger(E->getArg(0), Val, Info))
7638       return false;
7639     if (!Val)
7640       return Error(E);
7641 
7642     return Success(Val.countLeadingZeros(), E);
7643   }
7644 
7645   case Builtin::BI__builtin_constant_p:
7646     return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7647 
7648   case Builtin::BI__builtin_ctz:
7649   case Builtin::BI__builtin_ctzl:
7650   case Builtin::BI__builtin_ctzll:
7651   case Builtin::BI__builtin_ctzs: {
7652     APSInt Val;
7653     if (!EvaluateInteger(E->getArg(0), Val, Info))
7654       return false;
7655     if (!Val)
7656       return Error(E);
7657 
7658     return Success(Val.countTrailingZeros(), E);
7659   }
7660 
7661   case Builtin::BI__builtin_eh_return_data_regno: {
7662     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7663     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7664     return Success(Operand, E);
7665   }
7666 
7667   case Builtin::BI__builtin_expect:
7668     return Visit(E->getArg(0));
7669 
7670   case Builtin::BI__builtin_ffs:
7671   case Builtin::BI__builtin_ffsl:
7672   case Builtin::BI__builtin_ffsll: {
7673     APSInt Val;
7674     if (!EvaluateInteger(E->getArg(0), Val, Info))
7675       return false;
7676 
7677     unsigned N = Val.countTrailingZeros();
7678     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7679   }
7680 
7681   case Builtin::BI__builtin_fpclassify: {
7682     APFloat Val(0.0);
7683     if (!EvaluateFloat(E->getArg(5), Val, Info))
7684       return false;
7685     unsigned Arg;
7686     switch (Val.getCategory()) {
7687     case APFloat::fcNaN: Arg = 0; break;
7688     case APFloat::fcInfinity: Arg = 1; break;
7689     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7690     case APFloat::fcZero: Arg = 4; break;
7691     }
7692     return Visit(E->getArg(Arg));
7693   }
7694 
7695   case Builtin::BI__builtin_isinf_sign: {
7696     APFloat Val(0.0);
7697     return EvaluateFloat(E->getArg(0), Val, Info) &&
7698            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7699   }
7700 
7701   case Builtin::BI__builtin_isinf: {
7702     APFloat Val(0.0);
7703     return EvaluateFloat(E->getArg(0), Val, Info) &&
7704            Success(Val.isInfinity() ? 1 : 0, E);
7705   }
7706 
7707   case Builtin::BI__builtin_isfinite: {
7708     APFloat Val(0.0);
7709     return EvaluateFloat(E->getArg(0), Val, Info) &&
7710            Success(Val.isFinite() ? 1 : 0, E);
7711   }
7712 
7713   case Builtin::BI__builtin_isnan: {
7714     APFloat Val(0.0);
7715     return EvaluateFloat(E->getArg(0), Val, Info) &&
7716            Success(Val.isNaN() ? 1 : 0, E);
7717   }
7718 
7719   case Builtin::BI__builtin_isnormal: {
7720     APFloat Val(0.0);
7721     return EvaluateFloat(E->getArg(0), Val, Info) &&
7722            Success(Val.isNormal() ? 1 : 0, E);
7723   }
7724 
7725   case Builtin::BI__builtin_parity:
7726   case Builtin::BI__builtin_parityl:
7727   case Builtin::BI__builtin_parityll: {
7728     APSInt Val;
7729     if (!EvaluateInteger(E->getArg(0), Val, Info))
7730       return false;
7731 
7732     return Success(Val.countPopulation() % 2, E);
7733   }
7734 
7735   case Builtin::BI__builtin_popcount:
7736   case Builtin::BI__builtin_popcountl:
7737   case Builtin::BI__builtin_popcountll: {
7738     APSInt Val;
7739     if (!EvaluateInteger(E->getArg(0), Val, Info))
7740       return false;
7741 
7742     return Success(Val.countPopulation(), E);
7743   }
7744 
7745   case Builtin::BIstrlen:
7746   case Builtin::BIwcslen:
7747     // A call to strlen is not a constant expression.
7748     if (Info.getLangOpts().CPlusPlus11)
7749       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7750         << /*isConstexpr*/0 << /*isConstructor*/0
7751         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7752     else
7753       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7754     // Fall through.
7755   case Builtin::BI__builtin_strlen:
7756   case Builtin::BI__builtin_wcslen: {
7757     // As an extension, we support __builtin_strlen() as a constant expression,
7758     // and support folding strlen() to a constant.
7759     LValue String;
7760     if (!EvaluatePointer(E->getArg(0), String, Info))
7761       return false;
7762 
7763     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7764 
7765     // Fast path: if it's a string literal, search the string value.
7766     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7767             String.getLValueBase().dyn_cast<const Expr *>())) {
7768       // The string literal may have embedded null characters. Find the first
7769       // one and truncate there.
7770       StringRef Str = S->getBytes();
7771       int64_t Off = String.Offset.getQuantity();
7772       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
7773           S->getCharByteWidth() == 1 &&
7774           // FIXME: Add fast-path for wchar_t too.
7775           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
7776         Str = Str.substr(Off);
7777 
7778         StringRef::size_type Pos = Str.find(0);
7779         if (Pos != StringRef::npos)
7780           Str = Str.substr(0, Pos);
7781 
7782         return Success(Str.size(), E);
7783       }
7784 
7785       // Fall through to slow path to issue appropriate diagnostic.
7786     }
7787 
7788     // Slow path: scan the bytes of the string looking for the terminating 0.
7789     for (uint64_t Strlen = 0; /**/; ++Strlen) {
7790       APValue Char;
7791       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7792           !Char.isInt())
7793         return false;
7794       if (!Char.getInt())
7795         return Success(Strlen, E);
7796       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7797         return false;
7798     }
7799   }
7800 
7801   case Builtin::BIstrcmp:
7802   case Builtin::BIwcscmp:
7803   case Builtin::BIstrncmp:
7804   case Builtin::BIwcsncmp:
7805   case Builtin::BImemcmp:
7806   case Builtin::BIwmemcmp:
7807     // A call to strlen is not a constant expression.
7808     if (Info.getLangOpts().CPlusPlus11)
7809       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7810         << /*isConstexpr*/0 << /*isConstructor*/0
7811         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7812     else
7813       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7814     // Fall through.
7815   case Builtin::BI__builtin_strcmp:
7816   case Builtin::BI__builtin_wcscmp:
7817   case Builtin::BI__builtin_strncmp:
7818   case Builtin::BI__builtin_wcsncmp:
7819   case Builtin::BI__builtin_memcmp:
7820   case Builtin::BI__builtin_wmemcmp: {
7821     LValue String1, String2;
7822     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7823         !EvaluatePointer(E->getArg(1), String2, Info))
7824       return false;
7825 
7826     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7827 
7828     uint64_t MaxLength = uint64_t(-1);
7829     if (BuiltinOp != Builtin::BIstrcmp &&
7830         BuiltinOp != Builtin::BIwcscmp &&
7831         BuiltinOp != Builtin::BI__builtin_strcmp &&
7832         BuiltinOp != Builtin::BI__builtin_wcscmp) {
7833       APSInt N;
7834       if (!EvaluateInteger(E->getArg(2), N, Info))
7835         return false;
7836       MaxLength = N.getExtValue();
7837     }
7838     bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
7839                        BuiltinOp != Builtin::BIwmemcmp &&
7840                        BuiltinOp != Builtin::BI__builtin_memcmp &&
7841                        BuiltinOp != Builtin::BI__builtin_wmemcmp);
7842     for (; MaxLength; --MaxLength) {
7843       APValue Char1, Char2;
7844       if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7845           !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7846           !Char1.isInt() || !Char2.isInt())
7847         return false;
7848       if (Char1.getInt() != Char2.getInt())
7849         return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7850       if (StopAtNull && !Char1.getInt())
7851         return Success(0, E);
7852       assert(!(StopAtNull && !Char2.getInt()));
7853       if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7854           !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7855         return false;
7856     }
7857     // We hit the strncmp / memcmp limit.
7858     return Success(0, E);
7859   }
7860 
7861   case Builtin::BI__atomic_always_lock_free:
7862   case Builtin::BI__atomic_is_lock_free:
7863   case Builtin::BI__c11_atomic_is_lock_free: {
7864     APSInt SizeVal;
7865     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7866       return false;
7867 
7868     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7869     // of two less than the maximum inline atomic width, we know it is
7870     // lock-free.  If the size isn't a power of two, or greater than the
7871     // maximum alignment where we promote atomics, we know it is not lock-free
7872     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
7873     // the answer can only be determined at runtime; for example, 16-byte
7874     // atomics have lock-free implementations on some, but not all,
7875     // x86-64 processors.
7876 
7877     // Check power-of-two.
7878     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
7879     if (Size.isPowerOfTwo()) {
7880       // Check against inlining width.
7881       unsigned InlineWidthBits =
7882           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7883       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7884         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7885             Size == CharUnits::One() ||
7886             E->getArg(1)->isNullPointerConstant(Info.Ctx,
7887                                                 Expr::NPC_NeverValueDependent))
7888           // OK, we will inline appropriately-aligned operations of this size,
7889           // and _Atomic(T) is appropriately-aligned.
7890           return Success(1, E);
7891 
7892         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7893           castAs<PointerType>()->getPointeeType();
7894         if (!PointeeType->isIncompleteType() &&
7895             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7896           // OK, we will inline operations on this object.
7897           return Success(1, E);
7898         }
7899       }
7900     }
7901 
7902     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7903         Success(0, E) : Error(E);
7904   }
7905   }
7906 }
7907 
7908 static bool HasSameBase(const LValue &A, const LValue &B) {
7909   if (!A.getLValueBase())
7910     return !B.getLValueBase();
7911   if (!B.getLValueBase())
7912     return false;
7913 
7914   if (A.getLValueBase().getOpaqueValue() !=
7915       B.getLValueBase().getOpaqueValue()) {
7916     const Decl *ADecl = GetLValueBaseDecl(A);
7917     if (!ADecl)
7918       return false;
7919     const Decl *BDecl = GetLValueBaseDecl(B);
7920     if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
7921       return false;
7922   }
7923 
7924   return IsGlobalLValue(A.getLValueBase()) ||
7925          A.getLValueCallIndex() == B.getLValueCallIndex();
7926 }
7927 
7928 /// \brief Determine whether this is a pointer past the end of the complete
7929 /// object referred to by the lvalue.
7930 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7931                                             const LValue &LV) {
7932   // A null pointer can be viewed as being "past the end" but we don't
7933   // choose to look at it that way here.
7934   if (!LV.getLValueBase())
7935     return false;
7936 
7937   // If the designator is valid and refers to a subobject, we're not pointing
7938   // past the end.
7939   if (!LV.getLValueDesignator().Invalid &&
7940       !LV.getLValueDesignator().isOnePastTheEnd())
7941     return false;
7942 
7943   // A pointer to an incomplete type might be past-the-end if the type's size is
7944   // zero.  We cannot tell because the type is incomplete.
7945   QualType Ty = getType(LV.getLValueBase());
7946   if (Ty->isIncompleteType())
7947     return true;
7948 
7949   // We're a past-the-end pointer if we point to the byte after the object,
7950   // no matter what our type or path is.
7951   auto Size = Ctx.getTypeSizeInChars(Ty);
7952   return LV.getLValueOffset() == Size;
7953 }
7954 
7955 namespace {
7956 
7957 /// \brief Data recursive integer evaluator of certain binary operators.
7958 ///
7959 /// We use a data recursive algorithm for binary operators so that we are able
7960 /// to handle extreme cases of chained binary operators without causing stack
7961 /// overflow.
7962 class DataRecursiveIntBinOpEvaluator {
7963   struct EvalResult {
7964     APValue Val;
7965     bool Failed;
7966 
7967     EvalResult() : Failed(false) { }
7968 
7969     void swap(EvalResult &RHS) {
7970       Val.swap(RHS.Val);
7971       Failed = RHS.Failed;
7972       RHS.Failed = false;
7973     }
7974   };
7975 
7976   struct Job {
7977     const Expr *E;
7978     EvalResult LHSResult; // meaningful only for binary operator expression.
7979     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
7980 
7981     Job() = default;
7982     Job(Job &&) = default;
7983 
7984     void startSpeculativeEval(EvalInfo &Info) {
7985       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
7986     }
7987 
7988   private:
7989     SpeculativeEvaluationRAII SpecEvalRAII;
7990   };
7991 
7992   SmallVector<Job, 16> Queue;
7993 
7994   IntExprEvaluator &IntEval;
7995   EvalInfo &Info;
7996   APValue &FinalResult;
7997 
7998 public:
7999   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8000     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8001 
8002   /// \brief True if \param E is a binary operator that we are going to handle
8003   /// data recursively.
8004   /// We handle binary operators that are comma, logical, or that have operands
8005   /// with integral or enumeration type.
8006   static bool shouldEnqueue(const BinaryOperator *E) {
8007     return E->getOpcode() == BO_Comma ||
8008            E->isLogicalOp() ||
8009            (E->isRValue() &&
8010             E->getType()->isIntegralOrEnumerationType() &&
8011             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8012             E->getRHS()->getType()->isIntegralOrEnumerationType());
8013   }
8014 
8015   bool Traverse(const BinaryOperator *E) {
8016     enqueue(E);
8017     EvalResult PrevResult;
8018     while (!Queue.empty())
8019       process(PrevResult);
8020 
8021     if (PrevResult.Failed) return false;
8022 
8023     FinalResult.swap(PrevResult.Val);
8024     return true;
8025   }
8026 
8027 private:
8028   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8029     return IntEval.Success(Value, E, Result);
8030   }
8031   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8032     return IntEval.Success(Value, E, Result);
8033   }
8034   bool Error(const Expr *E) {
8035     return IntEval.Error(E);
8036   }
8037   bool Error(const Expr *E, diag::kind D) {
8038     return IntEval.Error(E, D);
8039   }
8040 
8041   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8042     return Info.CCEDiag(E, D);
8043   }
8044 
8045   // \brief Returns true if visiting the RHS is necessary, false otherwise.
8046   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
8047                          bool &SuppressRHSDiags);
8048 
8049   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8050                   const BinaryOperator *E, APValue &Result);
8051 
8052   void EvaluateExpr(const Expr *E, EvalResult &Result) {
8053     Result.Failed = !Evaluate(Result.Val, Info, E);
8054     if (Result.Failed)
8055       Result.Val = APValue();
8056   }
8057 
8058   void process(EvalResult &Result);
8059 
8060   void enqueue(const Expr *E) {
8061     E = E->IgnoreParens();
8062     Queue.resize(Queue.size()+1);
8063     Queue.back().E = E;
8064     Queue.back().Kind = Job::AnyExprKind;
8065   }
8066 };
8067 
8068 }
8069 
8070 bool DataRecursiveIntBinOpEvaluator::
8071        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
8072                          bool &SuppressRHSDiags) {
8073   if (E->getOpcode() == BO_Comma) {
8074     // Ignore LHS but note if we could not evaluate it.
8075     if (LHSResult.Failed)
8076       return Info.noteSideEffect();
8077     return true;
8078   }
8079 
8080   if (E->isLogicalOp()) {
8081     bool LHSAsBool;
8082     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
8083       // We were able to evaluate the LHS, see if we can get away with not
8084       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
8085       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8086         Success(LHSAsBool, E, LHSResult.Val);
8087         return false; // Ignore RHS
8088       }
8089     } else {
8090       LHSResult.Failed = true;
8091 
8092       // Since we weren't able to evaluate the left hand side, it
8093       // might have had side effects.
8094       if (!Info.noteSideEffect())
8095         return false;
8096 
8097       // We can't evaluate the LHS; however, sometimes the result
8098       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8099       // Don't ignore RHS and suppress diagnostics from this arm.
8100       SuppressRHSDiags = true;
8101     }
8102 
8103     return true;
8104   }
8105 
8106   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8107          E->getRHS()->getType()->isIntegralOrEnumerationType());
8108 
8109   if (LHSResult.Failed && !Info.noteFailure())
8110     return false; // Ignore RHS;
8111 
8112   return true;
8113 }
8114 
8115 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8116                                     bool IsSub) {
8117   // Compute the new offset in the appropriate width, wrapping at 64 bits.
8118   // FIXME: When compiling for a 32-bit target, we should use 32-bit
8119   // offsets.
8120   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8121   CharUnits &Offset = LVal.getLValueOffset();
8122   uint64_t Offset64 = Offset.getQuantity();
8123   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8124   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8125                                          : Offset64 + Index64);
8126 }
8127 
8128 bool DataRecursiveIntBinOpEvaluator::
8129        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8130                   const BinaryOperator *E, APValue &Result) {
8131   if (E->getOpcode() == BO_Comma) {
8132     if (RHSResult.Failed)
8133       return false;
8134     Result = RHSResult.Val;
8135     return true;
8136   }
8137 
8138   if (E->isLogicalOp()) {
8139     bool lhsResult, rhsResult;
8140     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8141     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
8142 
8143     if (LHSIsOK) {
8144       if (RHSIsOK) {
8145         if (E->getOpcode() == BO_LOr)
8146           return Success(lhsResult || rhsResult, E, Result);
8147         else
8148           return Success(lhsResult && rhsResult, E, Result);
8149       }
8150     } else {
8151       if (RHSIsOK) {
8152         // We can't evaluate the LHS; however, sometimes the result
8153         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8154         if (rhsResult == (E->getOpcode() == BO_LOr))
8155           return Success(rhsResult, E, Result);
8156       }
8157     }
8158 
8159     return false;
8160   }
8161 
8162   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8163          E->getRHS()->getType()->isIntegralOrEnumerationType());
8164 
8165   if (LHSResult.Failed || RHSResult.Failed)
8166     return false;
8167 
8168   const APValue &LHSVal = LHSResult.Val;
8169   const APValue &RHSVal = RHSResult.Val;
8170 
8171   // Handle cases like (unsigned long)&a + 4.
8172   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8173     Result = LHSVal;
8174     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
8175     return true;
8176   }
8177 
8178   // Handle cases like 4 + (unsigned long)&a
8179   if (E->getOpcode() == BO_Add &&
8180       RHSVal.isLValue() && LHSVal.isInt()) {
8181     Result = RHSVal;
8182     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
8183     return true;
8184   }
8185 
8186   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8187     // Handle (intptr_t)&&A - (intptr_t)&&B.
8188     if (!LHSVal.getLValueOffset().isZero() ||
8189         !RHSVal.getLValueOffset().isZero())
8190       return false;
8191     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8192     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8193     if (!LHSExpr || !RHSExpr)
8194       return false;
8195     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8196     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8197     if (!LHSAddrExpr || !RHSAddrExpr)
8198       return false;
8199     // Make sure both labels come from the same function.
8200     if (LHSAddrExpr->getLabel()->getDeclContext() !=
8201         RHSAddrExpr->getLabel()->getDeclContext())
8202       return false;
8203     Result = APValue(LHSAddrExpr, RHSAddrExpr);
8204     return true;
8205   }
8206 
8207   // All the remaining cases expect both operands to be an integer
8208   if (!LHSVal.isInt() || !RHSVal.isInt())
8209     return Error(E);
8210 
8211   // Set up the width and signedness manually, in case it can't be deduced
8212   // from the operation we're performing.
8213   // FIXME: Don't do this in the cases where we can deduce it.
8214   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8215                E->getType()->isUnsignedIntegerOrEnumerationType());
8216   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8217                          RHSVal.getInt(), Value))
8218     return false;
8219   return Success(Value, E, Result);
8220 }
8221 
8222 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
8223   Job &job = Queue.back();
8224 
8225   switch (job.Kind) {
8226     case Job::AnyExprKind: {
8227       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8228         if (shouldEnqueue(Bop)) {
8229           job.Kind = Job::BinOpKind;
8230           enqueue(Bop->getLHS());
8231           return;
8232         }
8233       }
8234 
8235       EvaluateExpr(job.E, Result);
8236       Queue.pop_back();
8237       return;
8238     }
8239 
8240     case Job::BinOpKind: {
8241       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8242       bool SuppressRHSDiags = false;
8243       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
8244         Queue.pop_back();
8245         return;
8246       }
8247       if (SuppressRHSDiags)
8248         job.startSpeculativeEval(Info);
8249       job.LHSResult.swap(Result);
8250       job.Kind = Job::BinOpVisitedLHSKind;
8251       enqueue(Bop->getRHS());
8252       return;
8253     }
8254 
8255     case Job::BinOpVisitedLHSKind: {
8256       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8257       EvalResult RHS;
8258       RHS.swap(Result);
8259       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
8260       Queue.pop_back();
8261       return;
8262     }
8263   }
8264 
8265   llvm_unreachable("Invalid Job::Kind!");
8266 }
8267 
8268 namespace {
8269 /// Used when we determine that we should fail, but can keep evaluating prior to
8270 /// noting that we had a failure.
8271 class DelayedNoteFailureRAII {
8272   EvalInfo &Info;
8273   bool NoteFailure;
8274 
8275 public:
8276   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8277       : Info(Info), NoteFailure(NoteFailure) {}
8278   ~DelayedNoteFailureRAII() {
8279     if (NoteFailure) {
8280       bool ContinueAfterFailure = Info.noteFailure();
8281       (void)ContinueAfterFailure;
8282       assert(ContinueAfterFailure &&
8283              "Shouldn't have kept evaluating on failure.");
8284     }
8285   }
8286 };
8287 }
8288 
8289 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8290   // We don't call noteFailure immediately because the assignment happens after
8291   // we evaluate LHS and RHS.
8292   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
8293     return Error(E);
8294 
8295   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
8296   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8297     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
8298 
8299   QualType LHSTy = E->getLHS()->getType();
8300   QualType RHSTy = E->getRHS()->getType();
8301 
8302   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
8303     ComplexValue LHS, RHS;
8304     bool LHSOK;
8305     if (E->isAssignmentOp()) {
8306       LValue LV;
8307       EvaluateLValue(E->getLHS(), LV, Info);
8308       LHSOK = false;
8309     } else if (LHSTy->isRealFloatingType()) {
8310       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8311       if (LHSOK) {
8312         LHS.makeComplexFloat();
8313         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8314       }
8315     } else {
8316       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8317     }
8318     if (!LHSOK && !Info.noteFailure())
8319       return false;
8320 
8321     if (E->getRHS()->getType()->isRealFloatingType()) {
8322       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8323         return false;
8324       RHS.makeComplexFloat();
8325       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8326     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
8327       return false;
8328 
8329     if (LHS.isComplexFloat()) {
8330       APFloat::cmpResult CR_r =
8331         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
8332       APFloat::cmpResult CR_i =
8333         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8334 
8335       if (E->getOpcode() == BO_EQ)
8336         return Success((CR_r == APFloat::cmpEqual &&
8337                         CR_i == APFloat::cmpEqual), E);
8338       else {
8339         assert(E->getOpcode() == BO_NE &&
8340                "Invalid complex comparison.");
8341         return Success(((CR_r == APFloat::cmpGreaterThan ||
8342                          CR_r == APFloat::cmpLessThan ||
8343                          CR_r == APFloat::cmpUnordered) ||
8344                         (CR_i == APFloat::cmpGreaterThan ||
8345                          CR_i == APFloat::cmpLessThan ||
8346                          CR_i == APFloat::cmpUnordered)), E);
8347       }
8348     } else {
8349       if (E->getOpcode() == BO_EQ)
8350         return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8351                         LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8352       else {
8353         assert(E->getOpcode() == BO_NE &&
8354                "Invalid compex comparison.");
8355         return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8356                         LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8357       }
8358     }
8359   }
8360 
8361   if (LHSTy->isRealFloatingType() &&
8362       RHSTy->isRealFloatingType()) {
8363     APFloat RHS(0.0), LHS(0.0);
8364 
8365     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
8366     if (!LHSOK && !Info.noteFailure())
8367       return false;
8368 
8369     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
8370       return false;
8371 
8372     APFloat::cmpResult CR = LHS.compare(RHS);
8373 
8374     switch (E->getOpcode()) {
8375     default:
8376       llvm_unreachable("Invalid binary operator!");
8377     case BO_LT:
8378       return Success(CR == APFloat::cmpLessThan, E);
8379     case BO_GT:
8380       return Success(CR == APFloat::cmpGreaterThan, E);
8381     case BO_LE:
8382       return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
8383     case BO_GE:
8384       return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
8385                      E);
8386     case BO_EQ:
8387       return Success(CR == APFloat::cmpEqual, E);
8388     case BO_NE:
8389       return Success(CR == APFloat::cmpGreaterThan
8390                      || CR == APFloat::cmpLessThan
8391                      || CR == APFloat::cmpUnordered, E);
8392     }
8393   }
8394 
8395   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
8396     if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
8397       LValue LHSValue, RHSValue;
8398 
8399       bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
8400       if (!LHSOK && !Info.noteFailure())
8401         return false;
8402 
8403       if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8404         return false;
8405 
8406       // Reject differing bases from the normal codepath; we special-case
8407       // comparisons to null.
8408       if (!HasSameBase(LHSValue, RHSValue)) {
8409         if (E->getOpcode() == BO_Sub) {
8410           // Handle &&A - &&B.
8411           if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
8412             return Error(E);
8413           const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
8414           const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
8415           if (!LHSExpr || !RHSExpr)
8416             return Error(E);
8417           const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8418           const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8419           if (!LHSAddrExpr || !RHSAddrExpr)
8420             return Error(E);
8421           // Make sure both labels come from the same function.
8422           if (LHSAddrExpr->getLabel()->getDeclContext() !=
8423               RHSAddrExpr->getLabel()->getDeclContext())
8424             return Error(E);
8425           return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
8426         }
8427         // Inequalities and subtractions between unrelated pointers have
8428         // unspecified or undefined behavior.
8429         if (!E->isEqualityOp())
8430           return Error(E);
8431         // A constant address may compare equal to the address of a symbol.
8432         // The one exception is that address of an object cannot compare equal
8433         // to a null pointer constant.
8434         if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8435             (!RHSValue.Base && !RHSValue.Offset.isZero()))
8436           return Error(E);
8437         // It's implementation-defined whether distinct literals will have
8438         // distinct addresses. In clang, the result of such a comparison is
8439         // unspecified, so it is not a constant expression. However, we do know
8440         // that the address of a literal will be non-null.
8441         if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8442             LHSValue.Base && RHSValue.Base)
8443           return Error(E);
8444         // We can't tell whether weak symbols will end up pointing to the same
8445         // object.
8446         if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
8447           return Error(E);
8448         // We can't compare the address of the start of one object with the
8449         // past-the-end address of another object, per C++ DR1652.
8450         if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8451              isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8452             (RHSValue.Base && RHSValue.Offset.isZero() &&
8453              isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8454           return Error(E);
8455         // We can't tell whether an object is at the same address as another
8456         // zero sized object.
8457         if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8458             (LHSValue.Base && isZeroSized(RHSValue)))
8459           return Error(E);
8460         // Pointers with different bases cannot represent the same object.
8461         // (Note that clang defaults to -fmerge-all-constants, which can
8462         // lead to inconsistent results for comparisons involving the address
8463         // of a constant; this generally doesn't matter in practice.)
8464         return Success(E->getOpcode() == BO_NE, E);
8465       }
8466 
8467       const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8468       const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8469 
8470       SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8471       SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8472 
8473       if (E->getOpcode() == BO_Sub) {
8474         // C++11 [expr.add]p6:
8475         //   Unless both pointers point to elements of the same array object, or
8476         //   one past the last element of the array object, the behavior is
8477         //   undefined.
8478         if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8479             !AreElementsOfSameArray(getType(LHSValue.Base),
8480                                     LHSDesignator, RHSDesignator))
8481           CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8482 
8483         QualType Type = E->getLHS()->getType();
8484         QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
8485 
8486         CharUnits ElementSize;
8487         if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
8488           return false;
8489 
8490         // As an extension, a type may have zero size (empty struct or union in
8491         // C, array of zero length). Pointer subtraction in such cases has
8492         // undefined behavior, so is not constant.
8493         if (ElementSize.isZero()) {
8494           Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
8495             << ElementType;
8496           return false;
8497         }
8498 
8499         // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8500         // and produce incorrect results when it overflows. Such behavior
8501         // appears to be non-conforming, but is common, so perhaps we should
8502         // assume the standard intended for such cases to be undefined behavior
8503         // and check for them.
8504 
8505         // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8506         // overflow in the final conversion to ptrdiff_t.
8507         APSInt LHS(
8508           llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8509         APSInt RHS(
8510           llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8511         APSInt ElemSize(
8512           llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8513         APSInt TrueResult = (LHS - RHS) / ElemSize;
8514         APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8515 
8516         if (Result.extend(65) != TrueResult &&
8517             !HandleOverflow(Info, E, TrueResult, E->getType()))
8518           return false;
8519         return Success(Result, E);
8520       }
8521 
8522       // C++11 [expr.rel]p3:
8523       //   Pointers to void (after pointer conversions) can be compared, with a
8524       //   result defined as follows: If both pointers represent the same
8525       //   address or are both the null pointer value, the result is true if the
8526       //   operator is <= or >= and false otherwise; otherwise the result is
8527       //   unspecified.
8528       // We interpret this as applying to pointers to *cv* void.
8529       if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
8530           E->isRelationalOp())
8531         CCEDiag(E, diag::note_constexpr_void_comparison);
8532 
8533       // C++11 [expr.rel]p2:
8534       // - If two pointers point to non-static data members of the same object,
8535       //   or to subobjects or array elements fo such members, recursively, the
8536       //   pointer to the later declared member compares greater provided the
8537       //   two members have the same access control and provided their class is
8538       //   not a union.
8539       //   [...]
8540       // - Otherwise pointer comparisons are unspecified.
8541       if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8542           E->isRelationalOp()) {
8543         bool WasArrayIndex;
8544         unsigned Mismatch =
8545           FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8546                                  RHSDesignator, WasArrayIndex);
8547         // At the point where the designators diverge, the comparison has a
8548         // specified value if:
8549         //  - we are comparing array indices
8550         //  - we are comparing fields of a union, or fields with the same access
8551         // Otherwise, the result is unspecified and thus the comparison is not a
8552         // constant expression.
8553         if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8554             Mismatch < RHSDesignator.Entries.size()) {
8555           const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8556           const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8557           if (!LF && !RF)
8558             CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8559           else if (!LF)
8560             CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8561               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8562               << RF->getParent() << RF;
8563           else if (!RF)
8564             CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8565               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8566               << LF->getParent() << LF;
8567           else if (!LF->getParent()->isUnion() &&
8568                    LF->getAccess() != RF->getAccess())
8569             CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8570               << LF << LF->getAccess() << RF << RF->getAccess()
8571               << LF->getParent();
8572         }
8573       }
8574 
8575       // The comparison here must be unsigned, and performed with the same
8576       // width as the pointer.
8577       unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8578       uint64_t CompareLHS = LHSOffset.getQuantity();
8579       uint64_t CompareRHS = RHSOffset.getQuantity();
8580       assert(PtrSize <= 64 && "Unexpected pointer width");
8581       uint64_t Mask = ~0ULL >> (64 - PtrSize);
8582       CompareLHS &= Mask;
8583       CompareRHS &= Mask;
8584 
8585       // If there is a base and this is a relational operator, we can only
8586       // compare pointers within the object in question; otherwise, the result
8587       // depends on where the object is located in memory.
8588       if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8589         QualType BaseTy = getType(LHSValue.Base);
8590         if (BaseTy->isIncompleteType())
8591           return Error(E);
8592         CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8593         uint64_t OffsetLimit = Size.getQuantity();
8594         if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8595           return Error(E);
8596       }
8597 
8598       switch (E->getOpcode()) {
8599       default: llvm_unreachable("missing comparison operator");
8600       case BO_LT: return Success(CompareLHS < CompareRHS, E);
8601       case BO_GT: return Success(CompareLHS > CompareRHS, E);
8602       case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8603       case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8604       case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8605       case BO_NE: return Success(CompareLHS != CompareRHS, E);
8606       }
8607     }
8608   }
8609 
8610   if (LHSTy->isMemberPointerType()) {
8611     assert(E->isEqualityOp() && "unexpected member pointer operation");
8612     assert(RHSTy->isMemberPointerType() && "invalid comparison");
8613 
8614     MemberPtr LHSValue, RHSValue;
8615 
8616     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
8617     if (!LHSOK && !Info.noteFailure())
8618       return false;
8619 
8620     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8621       return false;
8622 
8623     // C++11 [expr.eq]p2:
8624     //   If both operands are null, they compare equal. Otherwise if only one is
8625     //   null, they compare unequal.
8626     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8627       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8628       return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8629     }
8630 
8631     //   Otherwise if either is a pointer to a virtual member function, the
8632     //   result is unspecified.
8633     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8634       if (MD->isVirtual())
8635         CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8636     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8637       if (MD->isVirtual())
8638         CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8639 
8640     //   Otherwise they compare equal if and only if they would refer to the
8641     //   same member of the same most derived object or the same subobject if
8642     //   they were dereferenced with a hypothetical object of the associated
8643     //   class type.
8644     bool Equal = LHSValue == RHSValue;
8645     return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8646   }
8647 
8648   if (LHSTy->isNullPtrType()) {
8649     assert(E->isComparisonOp() && "unexpected nullptr operation");
8650     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8651     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8652     // are compared, the result is true of the operator is <=, >= or ==, and
8653     // false otherwise.
8654     BinaryOperator::Opcode Opcode = E->getOpcode();
8655     return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8656   }
8657 
8658   assert((!LHSTy->isIntegralOrEnumerationType() ||
8659           !RHSTy->isIntegralOrEnumerationType()) &&
8660          "DataRecursiveIntBinOpEvaluator should have handled integral types");
8661   // We can't continue from here for non-integral types.
8662   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8663 }
8664 
8665 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8666 /// a result as the expression's type.
8667 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8668                                     const UnaryExprOrTypeTraitExpr *E) {
8669   switch(E->getKind()) {
8670   case UETT_AlignOf: {
8671     if (E->isArgumentType())
8672       return Success(GetAlignOfType(Info, E->getArgumentType()), E);
8673     else
8674       return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
8675   }
8676 
8677   case UETT_VecStep: {
8678     QualType Ty = E->getTypeOfArgument();
8679 
8680     if (Ty->isVectorType()) {
8681       unsigned n = Ty->castAs<VectorType>()->getNumElements();
8682 
8683       // The vec_step built-in functions that take a 3-component
8684       // vector return 4. (OpenCL 1.1 spec 6.11.12)
8685       if (n == 3)
8686         n = 4;
8687 
8688       return Success(n, E);
8689     } else
8690       return Success(1, E);
8691   }
8692 
8693   case UETT_SizeOf: {
8694     QualType SrcTy = E->getTypeOfArgument();
8695     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8696     //   the result is the size of the referenced type."
8697     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8698       SrcTy = Ref->getPointeeType();
8699 
8700     CharUnits Sizeof;
8701     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
8702       return false;
8703     return Success(Sizeof, E);
8704   }
8705   case UETT_OpenMPRequiredSimdAlign:
8706     assert(E->isArgumentType());
8707     return Success(
8708         Info.Ctx.toCharUnitsFromBits(
8709                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8710             .getQuantity(),
8711         E);
8712   }
8713 
8714   llvm_unreachable("unknown expr/type trait");
8715 }
8716 
8717 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
8718   CharUnits Result;
8719   unsigned n = OOE->getNumComponents();
8720   if (n == 0)
8721     return Error(OOE);
8722   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
8723   for (unsigned i = 0; i != n; ++i) {
8724     OffsetOfNode ON = OOE->getComponent(i);
8725     switch (ON.getKind()) {
8726     case OffsetOfNode::Array: {
8727       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
8728       APSInt IdxResult;
8729       if (!EvaluateInteger(Idx, IdxResult, Info))
8730         return false;
8731       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8732       if (!AT)
8733         return Error(OOE);
8734       CurrentType = AT->getElementType();
8735       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8736       Result += IdxResult.getSExtValue() * ElementSize;
8737       break;
8738     }
8739 
8740     case OffsetOfNode::Field: {
8741       FieldDecl *MemberDecl = ON.getField();
8742       const RecordType *RT = CurrentType->getAs<RecordType>();
8743       if (!RT)
8744         return Error(OOE);
8745       RecordDecl *RD = RT->getDecl();
8746       if (RD->isInvalidDecl()) return false;
8747       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8748       unsigned i = MemberDecl->getFieldIndex();
8749       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
8750       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
8751       CurrentType = MemberDecl->getType().getNonReferenceType();
8752       break;
8753     }
8754 
8755     case OffsetOfNode::Identifier:
8756       llvm_unreachable("dependent __builtin_offsetof");
8757 
8758     case OffsetOfNode::Base: {
8759       CXXBaseSpecifier *BaseSpec = ON.getBase();
8760       if (BaseSpec->isVirtual())
8761         return Error(OOE);
8762 
8763       // Find the layout of the class whose base we are looking into.
8764       const RecordType *RT = CurrentType->getAs<RecordType>();
8765       if (!RT)
8766         return Error(OOE);
8767       RecordDecl *RD = RT->getDecl();
8768       if (RD->isInvalidDecl()) return false;
8769       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8770 
8771       // Find the base class itself.
8772       CurrentType = BaseSpec->getType();
8773       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8774       if (!BaseRT)
8775         return Error(OOE);
8776 
8777       // Add the offset to the base.
8778       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
8779       break;
8780     }
8781     }
8782   }
8783   return Success(Result, OOE);
8784 }
8785 
8786 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8787   switch (E->getOpcode()) {
8788   default:
8789     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8790     // See C99 6.6p3.
8791     return Error(E);
8792   case UO_Extension:
8793     // FIXME: Should extension allow i-c-e extension expressions in its scope?
8794     // If so, we could clear the diagnostic ID.
8795     return Visit(E->getSubExpr());
8796   case UO_Plus:
8797     // The result is just the value.
8798     return Visit(E->getSubExpr());
8799   case UO_Minus: {
8800     if (!Visit(E->getSubExpr()))
8801       return false;
8802     if (!Result.isInt()) return Error(E);
8803     const APSInt &Value = Result.getInt();
8804     if (Value.isSigned() && Value.isMinSignedValue() &&
8805         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8806                         E->getType()))
8807       return false;
8808     return Success(-Value, E);
8809   }
8810   case UO_Not: {
8811     if (!Visit(E->getSubExpr()))
8812       return false;
8813     if (!Result.isInt()) return Error(E);
8814     return Success(~Result.getInt(), E);
8815   }
8816   case UO_LNot: {
8817     bool bres;
8818     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
8819       return false;
8820     return Success(!bres, E);
8821   }
8822   }
8823 }
8824 
8825 /// HandleCast - This is used to evaluate implicit or explicit casts where the
8826 /// result type is integer.
8827 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8828   const Expr *SubExpr = E->getSubExpr();
8829   QualType DestType = E->getType();
8830   QualType SrcType = SubExpr->getType();
8831 
8832   switch (E->getCastKind()) {
8833   case CK_BaseToDerived:
8834   case CK_DerivedToBase:
8835   case CK_UncheckedDerivedToBase:
8836   case CK_Dynamic:
8837   case CK_ToUnion:
8838   case CK_ArrayToPointerDecay:
8839   case CK_FunctionToPointerDecay:
8840   case CK_NullToPointer:
8841   case CK_NullToMemberPointer:
8842   case CK_BaseToDerivedMemberPointer:
8843   case CK_DerivedToBaseMemberPointer:
8844   case CK_ReinterpretMemberPointer:
8845   case CK_ConstructorConversion:
8846   case CK_IntegralToPointer:
8847   case CK_ToVoid:
8848   case CK_VectorSplat:
8849   case CK_IntegralToFloating:
8850   case CK_FloatingCast:
8851   case CK_CPointerToObjCPointerCast:
8852   case CK_BlockPointerToObjCPointerCast:
8853   case CK_AnyPointerToBlockPointerCast:
8854   case CK_ObjCObjectLValueCast:
8855   case CK_FloatingRealToComplex:
8856   case CK_FloatingComplexToReal:
8857   case CK_FloatingComplexCast:
8858   case CK_FloatingComplexToIntegralComplex:
8859   case CK_IntegralRealToComplex:
8860   case CK_IntegralComplexCast:
8861   case CK_IntegralComplexToFloatingComplex:
8862   case CK_BuiltinFnToFnPtr:
8863   case CK_ZeroToOCLEvent:
8864   case CK_ZeroToOCLQueue:
8865   case CK_NonAtomicToAtomic:
8866   case CK_AddressSpaceConversion:
8867   case CK_IntToOCLSampler:
8868     llvm_unreachable("invalid cast kind for integral value");
8869 
8870   case CK_BitCast:
8871   case CK_Dependent:
8872   case CK_LValueBitCast:
8873   case CK_ARCProduceObject:
8874   case CK_ARCConsumeObject:
8875   case CK_ARCReclaimReturnedObject:
8876   case CK_ARCExtendBlockObject:
8877   case CK_CopyAndAutoreleaseBlockObject:
8878     return Error(E);
8879 
8880   case CK_UserDefinedConversion:
8881   case CK_LValueToRValue:
8882   case CK_AtomicToNonAtomic:
8883   case CK_NoOp:
8884     return ExprEvaluatorBaseTy::VisitCastExpr(E);
8885 
8886   case CK_MemberPointerToBoolean:
8887   case CK_PointerToBoolean:
8888   case CK_IntegralToBoolean:
8889   case CK_FloatingToBoolean:
8890   case CK_BooleanToSignedIntegral:
8891   case CK_FloatingComplexToBoolean:
8892   case CK_IntegralComplexToBoolean: {
8893     bool BoolResult;
8894     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
8895       return false;
8896     uint64_t IntResult = BoolResult;
8897     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8898       IntResult = (uint64_t)-1;
8899     return Success(IntResult, E);
8900   }
8901 
8902   case CK_IntegralCast: {
8903     if (!Visit(SubExpr))
8904       return false;
8905 
8906     if (!Result.isInt()) {
8907       // Allow casts of address-of-label differences if they are no-ops
8908       // or narrowing.  (The narrowing case isn't actually guaranteed to
8909       // be constant-evaluatable except in some narrow cases which are hard
8910       // to detect here.  We let it through on the assumption the user knows
8911       // what they are doing.)
8912       if (Result.isAddrLabelDiff())
8913         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
8914       // Only allow casts of lvalues if they are lossless.
8915       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8916     }
8917 
8918     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8919                                       Result.getInt()), E);
8920   }
8921 
8922   case CK_PointerToIntegral: {
8923     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8924 
8925     LValue LV;
8926     if (!EvaluatePointer(SubExpr, LV, Info))
8927       return false;
8928 
8929     if (LV.getLValueBase()) {
8930       // Only allow based lvalue casts if they are lossless.
8931       // FIXME: Allow a larger integer size than the pointer size, and allow
8932       // narrowing back down to pointer width in subsequent integral casts.
8933       // FIXME: Check integer type's active bits, not its type size.
8934       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
8935         return Error(E);
8936 
8937       LV.Designator.setInvalid();
8938       LV.moveInto(Result);
8939       return true;
8940     }
8941 
8942     uint64_t V;
8943     if (LV.isNullPointer())
8944       V = Info.Ctx.getTargetNullPointerValue(SrcType);
8945     else
8946       V = LV.getLValueOffset().getQuantity();
8947 
8948     APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
8949     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
8950   }
8951 
8952   case CK_IntegralComplexToReal: {
8953     ComplexValue C;
8954     if (!EvaluateComplex(SubExpr, C, Info))
8955       return false;
8956     return Success(C.getComplexIntReal(), E);
8957   }
8958 
8959   case CK_FloatingToIntegral: {
8960     APFloat F(0.0);
8961     if (!EvaluateFloat(SubExpr, F, Info))
8962       return false;
8963 
8964     APSInt Value;
8965     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8966       return false;
8967     return Success(Value, E);
8968   }
8969   }
8970 
8971   llvm_unreachable("unknown cast resulting in integral value");
8972 }
8973 
8974 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8975   if (E->getSubExpr()->getType()->isAnyComplexType()) {
8976     ComplexValue LV;
8977     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8978       return false;
8979     if (!LV.isComplexInt())
8980       return Error(E);
8981     return Success(LV.getComplexIntReal(), E);
8982   }
8983 
8984   return Visit(E->getSubExpr());
8985 }
8986 
8987 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8988   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
8989     ComplexValue LV;
8990     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8991       return false;
8992     if (!LV.isComplexInt())
8993       return Error(E);
8994     return Success(LV.getComplexIntImag(), E);
8995   }
8996 
8997   VisitIgnoredValue(E->getSubExpr());
8998   return Success(0, E);
8999 }
9000 
9001 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9002   return Success(E->getPackLength(), E);
9003 }
9004 
9005 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9006   return Success(E->getValue(), E);
9007 }
9008 
9009 //===----------------------------------------------------------------------===//
9010 // Float Evaluation
9011 //===----------------------------------------------------------------------===//
9012 
9013 namespace {
9014 class FloatExprEvaluator
9015   : public ExprEvaluatorBase<FloatExprEvaluator> {
9016   APFloat &Result;
9017 public:
9018   FloatExprEvaluator(EvalInfo &info, APFloat &result)
9019     : ExprEvaluatorBaseTy(info), Result(result) {}
9020 
9021   bool Success(const APValue &V, const Expr *e) {
9022     Result = V.getFloat();
9023     return true;
9024   }
9025 
9026   bool ZeroInitialization(const Expr *E) {
9027     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9028     return true;
9029   }
9030 
9031   bool VisitCallExpr(const CallExpr *E);
9032 
9033   bool VisitUnaryOperator(const UnaryOperator *E);
9034   bool VisitBinaryOperator(const BinaryOperator *E);
9035   bool VisitFloatingLiteral(const FloatingLiteral *E);
9036   bool VisitCastExpr(const CastExpr *E);
9037 
9038   bool VisitUnaryReal(const UnaryOperator *E);
9039   bool VisitUnaryImag(const UnaryOperator *E);
9040 
9041   // FIXME: Missing: array subscript of vector, member of vector
9042 };
9043 } // end anonymous namespace
9044 
9045 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
9046   assert(E->isRValue() && E->getType()->isRealFloatingType());
9047   return FloatExprEvaluator(Info, Result).Visit(E);
9048 }
9049 
9050 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
9051                                   QualType ResultTy,
9052                                   const Expr *Arg,
9053                                   bool SNaN,
9054                                   llvm::APFloat &Result) {
9055   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9056   if (!S) return false;
9057 
9058   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9059 
9060   llvm::APInt fill;
9061 
9062   // Treat empty strings as if they were zero.
9063   if (S->getString().empty())
9064     fill = llvm::APInt(32, 0);
9065   else if (S->getString().getAsInteger(0, fill))
9066     return false;
9067 
9068   if (Context.getTargetInfo().isNan2008()) {
9069     if (SNaN)
9070       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9071     else
9072       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9073   } else {
9074     // Prior to IEEE 754-2008, architectures were allowed to choose whether
9075     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9076     // a different encoding to what became a standard in 2008, and for pre-
9077     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9078     // sNaN. This is now known as "legacy NaN" encoding.
9079     if (SNaN)
9080       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9081     else
9082       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9083   }
9084 
9085   return true;
9086 }
9087 
9088 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
9089   switch (E->getBuiltinCallee()) {
9090   default:
9091     return ExprEvaluatorBaseTy::VisitCallExpr(E);
9092 
9093   case Builtin::BI__builtin_huge_val:
9094   case Builtin::BI__builtin_huge_valf:
9095   case Builtin::BI__builtin_huge_vall:
9096   case Builtin::BI__builtin_inf:
9097   case Builtin::BI__builtin_inff:
9098   case Builtin::BI__builtin_infl: {
9099     const llvm::fltSemantics &Sem =
9100       Info.Ctx.getFloatTypeSemantics(E->getType());
9101     Result = llvm::APFloat::getInf(Sem);
9102     return true;
9103   }
9104 
9105   case Builtin::BI__builtin_nans:
9106   case Builtin::BI__builtin_nansf:
9107   case Builtin::BI__builtin_nansl:
9108     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9109                                true, Result))
9110       return Error(E);
9111     return true;
9112 
9113   case Builtin::BI__builtin_nan:
9114   case Builtin::BI__builtin_nanf:
9115   case Builtin::BI__builtin_nanl:
9116     // If this is __builtin_nan() turn this into a nan, otherwise we
9117     // can't constant fold it.
9118     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9119                                false, Result))
9120       return Error(E);
9121     return true;
9122 
9123   case Builtin::BI__builtin_fabs:
9124   case Builtin::BI__builtin_fabsf:
9125   case Builtin::BI__builtin_fabsl:
9126     if (!EvaluateFloat(E->getArg(0), Result, Info))
9127       return false;
9128 
9129     if (Result.isNegative())
9130       Result.changeSign();
9131     return true;
9132 
9133   // FIXME: Builtin::BI__builtin_powi
9134   // FIXME: Builtin::BI__builtin_powif
9135   // FIXME: Builtin::BI__builtin_powil
9136 
9137   case Builtin::BI__builtin_copysign:
9138   case Builtin::BI__builtin_copysignf:
9139   case Builtin::BI__builtin_copysignl: {
9140     APFloat RHS(0.);
9141     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9142         !EvaluateFloat(E->getArg(1), RHS, Info))
9143       return false;
9144     Result.copySign(RHS);
9145     return true;
9146   }
9147   }
9148 }
9149 
9150 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9151   if (E->getSubExpr()->getType()->isAnyComplexType()) {
9152     ComplexValue CV;
9153     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9154       return false;
9155     Result = CV.FloatReal;
9156     return true;
9157   }
9158 
9159   return Visit(E->getSubExpr());
9160 }
9161 
9162 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9163   if (E->getSubExpr()->getType()->isAnyComplexType()) {
9164     ComplexValue CV;
9165     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9166       return false;
9167     Result = CV.FloatImag;
9168     return true;
9169   }
9170 
9171   VisitIgnoredValue(E->getSubExpr());
9172   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9173   Result = llvm::APFloat::getZero(Sem);
9174   return true;
9175 }
9176 
9177 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9178   switch (E->getOpcode()) {
9179   default: return Error(E);
9180   case UO_Plus:
9181     return EvaluateFloat(E->getSubExpr(), Result, Info);
9182   case UO_Minus:
9183     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9184       return false;
9185     Result.changeSign();
9186     return true;
9187   }
9188 }
9189 
9190 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9191   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9192     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9193 
9194   APFloat RHS(0.0);
9195   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
9196   if (!LHSOK && !Info.noteFailure())
9197     return false;
9198   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9199          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
9200 }
9201 
9202 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9203   Result = E->getValue();
9204   return true;
9205 }
9206 
9207 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9208   const Expr* SubExpr = E->getSubExpr();
9209 
9210   switch (E->getCastKind()) {
9211   default:
9212     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9213 
9214   case CK_IntegralToFloating: {
9215     APSInt IntResult;
9216     return EvaluateInteger(SubExpr, IntResult, Info) &&
9217            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9218                                 E->getType(), Result);
9219   }
9220 
9221   case CK_FloatingCast: {
9222     if (!Visit(SubExpr))
9223       return false;
9224     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9225                                   Result);
9226   }
9227 
9228   case CK_FloatingComplexToReal: {
9229     ComplexValue V;
9230     if (!EvaluateComplex(SubExpr, V, Info))
9231       return false;
9232     Result = V.getComplexFloatReal();
9233     return true;
9234   }
9235   }
9236 }
9237 
9238 //===----------------------------------------------------------------------===//
9239 // Complex Evaluation (for float and integer)
9240 //===----------------------------------------------------------------------===//
9241 
9242 namespace {
9243 class ComplexExprEvaluator
9244   : public ExprEvaluatorBase<ComplexExprEvaluator> {
9245   ComplexValue &Result;
9246 
9247 public:
9248   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
9249     : ExprEvaluatorBaseTy(info), Result(Result) {}
9250 
9251   bool Success(const APValue &V, const Expr *e) {
9252     Result.setFrom(V);
9253     return true;
9254   }
9255 
9256   bool ZeroInitialization(const Expr *E);
9257 
9258   //===--------------------------------------------------------------------===//
9259   //                            Visitor Methods
9260   //===--------------------------------------------------------------------===//
9261 
9262   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
9263   bool VisitCastExpr(const CastExpr *E);
9264   bool VisitBinaryOperator(const BinaryOperator *E);
9265   bool VisitUnaryOperator(const UnaryOperator *E);
9266   bool VisitInitListExpr(const InitListExpr *E);
9267 };
9268 } // end anonymous namespace
9269 
9270 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9271                             EvalInfo &Info) {
9272   assert(E->isRValue() && E->getType()->isAnyComplexType());
9273   return ComplexExprEvaluator(Info, Result).Visit(E);
9274 }
9275 
9276 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
9277   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
9278   if (ElemTy->isRealFloatingType()) {
9279     Result.makeComplexFloat();
9280     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9281     Result.FloatReal = Zero;
9282     Result.FloatImag = Zero;
9283   } else {
9284     Result.makeComplexInt();
9285     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9286     Result.IntReal = Zero;
9287     Result.IntImag = Zero;
9288   }
9289   return true;
9290 }
9291 
9292 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9293   const Expr* SubExpr = E->getSubExpr();
9294 
9295   if (SubExpr->getType()->isRealFloatingType()) {
9296     Result.makeComplexFloat();
9297     APFloat &Imag = Result.FloatImag;
9298     if (!EvaluateFloat(SubExpr, Imag, Info))
9299       return false;
9300 
9301     Result.FloatReal = APFloat(Imag.getSemantics());
9302     return true;
9303   } else {
9304     assert(SubExpr->getType()->isIntegerType() &&
9305            "Unexpected imaginary literal.");
9306 
9307     Result.makeComplexInt();
9308     APSInt &Imag = Result.IntImag;
9309     if (!EvaluateInteger(SubExpr, Imag, Info))
9310       return false;
9311 
9312     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9313     return true;
9314   }
9315 }
9316 
9317 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
9318 
9319   switch (E->getCastKind()) {
9320   case CK_BitCast:
9321   case CK_BaseToDerived:
9322   case CK_DerivedToBase:
9323   case CK_UncheckedDerivedToBase:
9324   case CK_Dynamic:
9325   case CK_ToUnion:
9326   case CK_ArrayToPointerDecay:
9327   case CK_FunctionToPointerDecay:
9328   case CK_NullToPointer:
9329   case CK_NullToMemberPointer:
9330   case CK_BaseToDerivedMemberPointer:
9331   case CK_DerivedToBaseMemberPointer:
9332   case CK_MemberPointerToBoolean:
9333   case CK_ReinterpretMemberPointer:
9334   case CK_ConstructorConversion:
9335   case CK_IntegralToPointer:
9336   case CK_PointerToIntegral:
9337   case CK_PointerToBoolean:
9338   case CK_ToVoid:
9339   case CK_VectorSplat:
9340   case CK_IntegralCast:
9341   case CK_BooleanToSignedIntegral:
9342   case CK_IntegralToBoolean:
9343   case CK_IntegralToFloating:
9344   case CK_FloatingToIntegral:
9345   case CK_FloatingToBoolean:
9346   case CK_FloatingCast:
9347   case CK_CPointerToObjCPointerCast:
9348   case CK_BlockPointerToObjCPointerCast:
9349   case CK_AnyPointerToBlockPointerCast:
9350   case CK_ObjCObjectLValueCast:
9351   case CK_FloatingComplexToReal:
9352   case CK_FloatingComplexToBoolean:
9353   case CK_IntegralComplexToReal:
9354   case CK_IntegralComplexToBoolean:
9355   case CK_ARCProduceObject:
9356   case CK_ARCConsumeObject:
9357   case CK_ARCReclaimReturnedObject:
9358   case CK_ARCExtendBlockObject:
9359   case CK_CopyAndAutoreleaseBlockObject:
9360   case CK_BuiltinFnToFnPtr:
9361   case CK_ZeroToOCLEvent:
9362   case CK_ZeroToOCLQueue:
9363   case CK_NonAtomicToAtomic:
9364   case CK_AddressSpaceConversion:
9365   case CK_IntToOCLSampler:
9366     llvm_unreachable("invalid cast kind for complex value");
9367 
9368   case CK_LValueToRValue:
9369   case CK_AtomicToNonAtomic:
9370   case CK_NoOp:
9371     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9372 
9373   case CK_Dependent:
9374   case CK_LValueBitCast:
9375   case CK_UserDefinedConversion:
9376     return Error(E);
9377 
9378   case CK_FloatingRealToComplex: {
9379     APFloat &Real = Result.FloatReal;
9380     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
9381       return false;
9382 
9383     Result.makeComplexFloat();
9384     Result.FloatImag = APFloat(Real.getSemantics());
9385     return true;
9386   }
9387 
9388   case CK_FloatingComplexCast: {
9389     if (!Visit(E->getSubExpr()))
9390       return false;
9391 
9392     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9393     QualType From
9394       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9395 
9396     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9397            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
9398   }
9399 
9400   case CK_FloatingComplexToIntegralComplex: {
9401     if (!Visit(E->getSubExpr()))
9402       return false;
9403 
9404     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9405     QualType From
9406       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9407     Result.makeComplexInt();
9408     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9409                                 To, Result.IntReal) &&
9410            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9411                                 To, Result.IntImag);
9412   }
9413 
9414   case CK_IntegralRealToComplex: {
9415     APSInt &Real = Result.IntReal;
9416     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9417       return false;
9418 
9419     Result.makeComplexInt();
9420     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9421     return true;
9422   }
9423 
9424   case CK_IntegralComplexCast: {
9425     if (!Visit(E->getSubExpr()))
9426       return false;
9427 
9428     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9429     QualType From
9430       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9431 
9432     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9433     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
9434     return true;
9435   }
9436 
9437   case CK_IntegralComplexToFloatingComplex: {
9438     if (!Visit(E->getSubExpr()))
9439       return false;
9440 
9441     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
9442     QualType From
9443       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
9444     Result.makeComplexFloat();
9445     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9446                                 To, Result.FloatReal) &&
9447            HandleIntToFloatCast(Info, E, From, Result.IntImag,
9448                                 To, Result.FloatImag);
9449   }
9450   }
9451 
9452   llvm_unreachable("unknown cast resulting in complex value");
9453 }
9454 
9455 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9456   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9457     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9458 
9459   // Track whether the LHS or RHS is real at the type system level. When this is
9460   // the case we can simplify our evaluation strategy.
9461   bool LHSReal = false, RHSReal = false;
9462 
9463   bool LHSOK;
9464   if (E->getLHS()->getType()->isRealFloatingType()) {
9465     LHSReal = true;
9466     APFloat &Real = Result.FloatReal;
9467     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9468     if (LHSOK) {
9469       Result.makeComplexFloat();
9470       Result.FloatImag = APFloat(Real.getSemantics());
9471     }
9472   } else {
9473     LHSOK = Visit(E->getLHS());
9474   }
9475   if (!LHSOK && !Info.noteFailure())
9476     return false;
9477 
9478   ComplexValue RHS;
9479   if (E->getRHS()->getType()->isRealFloatingType()) {
9480     RHSReal = true;
9481     APFloat &Real = RHS.FloatReal;
9482     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9483       return false;
9484     RHS.makeComplexFloat();
9485     RHS.FloatImag = APFloat(Real.getSemantics());
9486   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
9487     return false;
9488 
9489   assert(!(LHSReal && RHSReal) &&
9490          "Cannot have both operands of a complex operation be real.");
9491   switch (E->getOpcode()) {
9492   default: return Error(E);
9493   case BO_Add:
9494     if (Result.isComplexFloat()) {
9495       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9496                                        APFloat::rmNearestTiesToEven);
9497       if (LHSReal)
9498         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9499       else if (!RHSReal)
9500         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9501                                          APFloat::rmNearestTiesToEven);
9502     } else {
9503       Result.getComplexIntReal() += RHS.getComplexIntReal();
9504       Result.getComplexIntImag() += RHS.getComplexIntImag();
9505     }
9506     break;
9507   case BO_Sub:
9508     if (Result.isComplexFloat()) {
9509       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9510                                             APFloat::rmNearestTiesToEven);
9511       if (LHSReal) {
9512         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9513         Result.getComplexFloatImag().changeSign();
9514       } else if (!RHSReal) {
9515         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9516                                               APFloat::rmNearestTiesToEven);
9517       }
9518     } else {
9519       Result.getComplexIntReal() -= RHS.getComplexIntReal();
9520       Result.getComplexIntImag() -= RHS.getComplexIntImag();
9521     }
9522     break;
9523   case BO_Mul:
9524     if (Result.isComplexFloat()) {
9525       // This is an implementation of complex multiplication according to the
9526       // constraints laid out in C11 Annex G. The implemention uses the
9527       // following naming scheme:
9528       //   (a + ib) * (c + id)
9529       ComplexValue LHS = Result;
9530       APFloat &A = LHS.getComplexFloatReal();
9531       APFloat &B = LHS.getComplexFloatImag();
9532       APFloat &C = RHS.getComplexFloatReal();
9533       APFloat &D = RHS.getComplexFloatImag();
9534       APFloat &ResR = Result.getComplexFloatReal();
9535       APFloat &ResI = Result.getComplexFloatImag();
9536       if (LHSReal) {
9537         assert(!RHSReal && "Cannot have two real operands for a complex op!");
9538         ResR = A * C;
9539         ResI = A * D;
9540       } else if (RHSReal) {
9541         ResR = C * A;
9542         ResI = C * B;
9543       } else {
9544         // In the fully general case, we need to handle NaNs and infinities
9545         // robustly.
9546         APFloat AC = A * C;
9547         APFloat BD = B * D;
9548         APFloat AD = A * D;
9549         APFloat BC = B * C;
9550         ResR = AC - BD;
9551         ResI = AD + BC;
9552         if (ResR.isNaN() && ResI.isNaN()) {
9553           bool Recalc = false;
9554           if (A.isInfinity() || B.isInfinity()) {
9555             A = APFloat::copySign(
9556                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9557             B = APFloat::copySign(
9558                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9559             if (C.isNaN())
9560               C = APFloat::copySign(APFloat(C.getSemantics()), C);
9561             if (D.isNaN())
9562               D = APFloat::copySign(APFloat(D.getSemantics()), D);
9563             Recalc = true;
9564           }
9565           if (C.isInfinity() || D.isInfinity()) {
9566             C = APFloat::copySign(
9567                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9568             D = APFloat::copySign(
9569                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9570             if (A.isNaN())
9571               A = APFloat::copySign(APFloat(A.getSemantics()), A);
9572             if (B.isNaN())
9573               B = APFloat::copySign(APFloat(B.getSemantics()), B);
9574             Recalc = true;
9575           }
9576           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9577                           AD.isInfinity() || BC.isInfinity())) {
9578             if (A.isNaN())
9579               A = APFloat::copySign(APFloat(A.getSemantics()), A);
9580             if (B.isNaN())
9581               B = APFloat::copySign(APFloat(B.getSemantics()), B);
9582             if (C.isNaN())
9583               C = APFloat::copySign(APFloat(C.getSemantics()), C);
9584             if (D.isNaN())
9585               D = APFloat::copySign(APFloat(D.getSemantics()), D);
9586             Recalc = true;
9587           }
9588           if (Recalc) {
9589             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9590             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9591           }
9592         }
9593       }
9594     } else {
9595       ComplexValue LHS = Result;
9596       Result.getComplexIntReal() =
9597         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9598          LHS.getComplexIntImag() * RHS.getComplexIntImag());
9599       Result.getComplexIntImag() =
9600         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9601          LHS.getComplexIntImag() * RHS.getComplexIntReal());
9602     }
9603     break;
9604   case BO_Div:
9605     if (Result.isComplexFloat()) {
9606       // This is an implementation of complex division according to the
9607       // constraints laid out in C11 Annex G. The implemention uses the
9608       // following naming scheme:
9609       //   (a + ib) / (c + id)
9610       ComplexValue LHS = Result;
9611       APFloat &A = LHS.getComplexFloatReal();
9612       APFloat &B = LHS.getComplexFloatImag();
9613       APFloat &C = RHS.getComplexFloatReal();
9614       APFloat &D = RHS.getComplexFloatImag();
9615       APFloat &ResR = Result.getComplexFloatReal();
9616       APFloat &ResI = Result.getComplexFloatImag();
9617       if (RHSReal) {
9618         ResR = A / C;
9619         ResI = B / C;
9620       } else {
9621         if (LHSReal) {
9622           // No real optimizations we can do here, stub out with zero.
9623           B = APFloat::getZero(A.getSemantics());
9624         }
9625         int DenomLogB = 0;
9626         APFloat MaxCD = maxnum(abs(C), abs(D));
9627         if (MaxCD.isFinite()) {
9628           DenomLogB = ilogb(MaxCD);
9629           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9630           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
9631         }
9632         APFloat Denom = C * C + D * D;
9633         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9634                       APFloat::rmNearestTiesToEven);
9635         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9636                       APFloat::rmNearestTiesToEven);
9637         if (ResR.isNaN() && ResI.isNaN()) {
9638           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9639             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9640             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9641           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9642                      D.isFinite()) {
9643             A = APFloat::copySign(
9644                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9645             B = APFloat::copySign(
9646                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9647             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9648             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9649           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9650             C = APFloat::copySign(
9651                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9652             D = APFloat::copySign(
9653                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9654             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9655             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9656           }
9657         }
9658       }
9659     } else {
9660       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9661         return Error(E, diag::note_expr_divide_by_zero);
9662 
9663       ComplexValue LHS = Result;
9664       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9665         RHS.getComplexIntImag() * RHS.getComplexIntImag();
9666       Result.getComplexIntReal() =
9667         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9668          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9669       Result.getComplexIntImag() =
9670         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9671          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9672     }
9673     break;
9674   }
9675 
9676   return true;
9677 }
9678 
9679 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9680   // Get the operand value into 'Result'.
9681   if (!Visit(E->getSubExpr()))
9682     return false;
9683 
9684   switch (E->getOpcode()) {
9685   default:
9686     return Error(E);
9687   case UO_Extension:
9688     return true;
9689   case UO_Plus:
9690     // The result is always just the subexpr.
9691     return true;
9692   case UO_Minus:
9693     if (Result.isComplexFloat()) {
9694       Result.getComplexFloatReal().changeSign();
9695       Result.getComplexFloatImag().changeSign();
9696     }
9697     else {
9698       Result.getComplexIntReal() = -Result.getComplexIntReal();
9699       Result.getComplexIntImag() = -Result.getComplexIntImag();
9700     }
9701     return true;
9702   case UO_Not:
9703     if (Result.isComplexFloat())
9704       Result.getComplexFloatImag().changeSign();
9705     else
9706       Result.getComplexIntImag() = -Result.getComplexIntImag();
9707     return true;
9708   }
9709 }
9710 
9711 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9712   if (E->getNumInits() == 2) {
9713     if (E->getType()->isComplexType()) {
9714       Result.makeComplexFloat();
9715       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9716         return false;
9717       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9718         return false;
9719     } else {
9720       Result.makeComplexInt();
9721       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9722         return false;
9723       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9724         return false;
9725     }
9726     return true;
9727   }
9728   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9729 }
9730 
9731 //===----------------------------------------------------------------------===//
9732 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9733 // implicit conversion.
9734 //===----------------------------------------------------------------------===//
9735 
9736 namespace {
9737 class AtomicExprEvaluator :
9738     public ExprEvaluatorBase<AtomicExprEvaluator> {
9739   const LValue *This;
9740   APValue &Result;
9741 public:
9742   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
9743       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
9744 
9745   bool Success(const APValue &V, const Expr *E) {
9746     Result = V;
9747     return true;
9748   }
9749 
9750   bool ZeroInitialization(const Expr *E) {
9751     ImplicitValueInitExpr VIE(
9752         E->getType()->castAs<AtomicType>()->getValueType());
9753     // For atomic-qualified class (and array) types in C++, initialize the
9754     // _Atomic-wrapped subobject directly, in-place.
9755     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
9756                 : Evaluate(Result, Info, &VIE);
9757   }
9758 
9759   bool VisitCastExpr(const CastExpr *E) {
9760     switch (E->getCastKind()) {
9761     default:
9762       return ExprEvaluatorBaseTy::VisitCastExpr(E);
9763     case CK_NonAtomicToAtomic:
9764       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
9765                   : Evaluate(Result, Info, E->getSubExpr());
9766     }
9767   }
9768 };
9769 } // end anonymous namespace
9770 
9771 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
9772                            EvalInfo &Info) {
9773   assert(E->isRValue() && E->getType()->isAtomicType());
9774   return AtomicExprEvaluator(Info, This, Result).Visit(E);
9775 }
9776 
9777 //===----------------------------------------------------------------------===//
9778 // Void expression evaluation, primarily for a cast to void on the LHS of a
9779 // comma operator
9780 //===----------------------------------------------------------------------===//
9781 
9782 namespace {
9783 class VoidExprEvaluator
9784   : public ExprEvaluatorBase<VoidExprEvaluator> {
9785 public:
9786   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9787 
9788   bool Success(const APValue &V, const Expr *e) { return true; }
9789 
9790   bool ZeroInitialization(const Expr *E) { return true; }
9791 
9792   bool VisitCastExpr(const CastExpr *E) {
9793     switch (E->getCastKind()) {
9794     default:
9795       return ExprEvaluatorBaseTy::VisitCastExpr(E);
9796     case CK_ToVoid:
9797       VisitIgnoredValue(E->getSubExpr());
9798       return true;
9799     }
9800   }
9801 
9802   bool VisitCallExpr(const CallExpr *E) {
9803     switch (E->getBuiltinCallee()) {
9804     default:
9805       return ExprEvaluatorBaseTy::VisitCallExpr(E);
9806     case Builtin::BI__assume:
9807     case Builtin::BI__builtin_assume:
9808       // The argument is not evaluated!
9809       return true;
9810     }
9811   }
9812 };
9813 } // end anonymous namespace
9814 
9815 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9816   assert(E->isRValue() && E->getType()->isVoidType());
9817   return VoidExprEvaluator(Info).Visit(E);
9818 }
9819 
9820 //===----------------------------------------------------------------------===//
9821 // Top level Expr::EvaluateAsRValue method.
9822 //===----------------------------------------------------------------------===//
9823 
9824 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
9825   // In C, function designators are not lvalues, but we evaluate them as if they
9826   // are.
9827   QualType T = E->getType();
9828   if (E->isGLValue() || T->isFunctionType()) {
9829     LValue LV;
9830     if (!EvaluateLValue(E, LV, Info))
9831       return false;
9832     LV.moveInto(Result);
9833   } else if (T->isVectorType()) {
9834     if (!EvaluateVector(E, Result, Info))
9835       return false;
9836   } else if (T->isIntegralOrEnumerationType()) {
9837     if (!IntExprEvaluator(Info, Result).Visit(E))
9838       return false;
9839   } else if (T->hasPointerRepresentation()) {
9840     LValue LV;
9841     if (!EvaluatePointer(E, LV, Info))
9842       return false;
9843     LV.moveInto(Result);
9844   } else if (T->isRealFloatingType()) {
9845     llvm::APFloat F(0.0);
9846     if (!EvaluateFloat(E, F, Info))
9847       return false;
9848     Result = APValue(F);
9849   } else if (T->isAnyComplexType()) {
9850     ComplexValue C;
9851     if (!EvaluateComplex(E, C, Info))
9852       return false;
9853     C.moveInto(Result);
9854   } else if (T->isMemberPointerType()) {
9855     MemberPtr P;
9856     if (!EvaluateMemberPointer(E, P, Info))
9857       return false;
9858     P.moveInto(Result);
9859     return true;
9860   } else if (T->isArrayType()) {
9861     LValue LV;
9862     LV.set(E, Info.CurrentCall->Index);
9863     APValue &Value = Info.CurrentCall->createTemporary(E, false);
9864     if (!EvaluateArray(E, LV, Value, Info))
9865       return false;
9866     Result = Value;
9867   } else if (T->isRecordType()) {
9868     LValue LV;
9869     LV.set(E, Info.CurrentCall->Index);
9870     APValue &Value = Info.CurrentCall->createTemporary(E, false);
9871     if (!EvaluateRecord(E, LV, Value, Info))
9872       return false;
9873     Result = Value;
9874   } else if (T->isVoidType()) {
9875     if (!Info.getLangOpts().CPlusPlus11)
9876       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
9877         << E->getType();
9878     if (!EvaluateVoid(E, Info))
9879       return false;
9880   } else if (T->isAtomicType()) {
9881     QualType Unqual = T.getAtomicUnqualifiedType();
9882     if (Unqual->isArrayType() || Unqual->isRecordType()) {
9883       LValue LV;
9884       LV.set(E, Info.CurrentCall->Index);
9885       APValue &Value = Info.CurrentCall->createTemporary(E, false);
9886       if (!EvaluateAtomic(E, &LV, Value, Info))
9887         return false;
9888     } else {
9889       if (!EvaluateAtomic(E, nullptr, Result, Info))
9890         return false;
9891     }
9892   } else if (Info.getLangOpts().CPlusPlus11) {
9893     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
9894     return false;
9895   } else {
9896     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9897     return false;
9898   }
9899 
9900   return true;
9901 }
9902 
9903 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9904 /// cases, the in-place evaluation is essential, since later initializers for
9905 /// an object can indirectly refer to subobjects which were initialized earlier.
9906 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
9907                             const Expr *E, bool AllowNonLiteralTypes) {
9908   assert(!E->isValueDependent());
9909 
9910   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
9911     return false;
9912 
9913   if (E->isRValue()) {
9914     // Evaluate arrays and record types in-place, so that later initializers can
9915     // refer to earlier-initialized members of the object.
9916     QualType T = E->getType();
9917     if (T->isArrayType())
9918       return EvaluateArray(E, This, Result, Info);
9919     else if (T->isRecordType())
9920       return EvaluateRecord(E, This, Result, Info);
9921     else if (T->isAtomicType()) {
9922       QualType Unqual = T.getAtomicUnqualifiedType();
9923       if (Unqual->isArrayType() || Unqual->isRecordType())
9924         return EvaluateAtomic(E, &This, Result, Info);
9925     }
9926   }
9927 
9928   // For any other type, in-place evaluation is unimportant.
9929   return Evaluate(Result, Info, E);
9930 }
9931 
9932 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9933 /// lvalue-to-rvalue cast if it is an lvalue.
9934 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
9935   if (E->getType().isNull())
9936     return false;
9937 
9938   if (!CheckLiteralType(Info, E))
9939     return false;
9940 
9941   if (!::Evaluate(Result, Info, E))
9942     return false;
9943 
9944   if (E->isGLValue()) {
9945     LValue LV;
9946     LV.setFrom(Info.Ctx, Result);
9947     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
9948       return false;
9949   }
9950 
9951   // Check this core constant expression is a constant expression.
9952   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
9953 }
9954 
9955 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
9956                                  const ASTContext &Ctx, bool &IsConst) {
9957   // Fast-path evaluations of integer literals, since we sometimes see files
9958   // containing vast quantities of these.
9959   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9960     Result.Val = APValue(APSInt(L->getValue(),
9961                                 L->getType()->isUnsignedIntegerType()));
9962     IsConst = true;
9963     return true;
9964   }
9965 
9966   // This case should be rare, but we need to check it before we check on
9967   // the type below.
9968   if (Exp->getType().isNull()) {
9969     IsConst = false;
9970     return true;
9971   }
9972 
9973   // FIXME: Evaluating values of large array and record types can cause
9974   // performance problems. Only do so in C++11 for now.
9975   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9976                           Exp->getType()->isRecordType()) &&
9977       !Ctx.getLangOpts().CPlusPlus11) {
9978     IsConst = false;
9979     return true;
9980   }
9981   return false;
9982 }
9983 
9984 
9985 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
9986 /// any crazy technique (that has nothing to do with language standards) that
9987 /// we want to.  If this function returns true, it returns the folded constant
9988 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9989 /// will be applied to the result.
9990 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
9991   bool IsConst;
9992   if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
9993     return IsConst;
9994 
9995   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
9996   return ::EvaluateAsRValue(Info, this, Result.Val);
9997 }
9998 
9999 bool Expr::EvaluateAsBooleanCondition(bool &Result,
10000                                       const ASTContext &Ctx) const {
10001   EvalResult Scratch;
10002   return EvaluateAsRValue(Scratch, Ctx) &&
10003          HandleConversionToBool(Scratch.Val, Result);
10004 }
10005 
10006 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10007                                       Expr::SideEffectsKind SEK) {
10008   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10009          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10010 }
10011 
10012 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
10013                          SideEffectsKind AllowSideEffects) const {
10014   if (!getType()->isIntegralOrEnumerationType())
10015     return false;
10016 
10017   EvalResult ExprResult;
10018   if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
10019       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10020     return false;
10021 
10022   Result = ExprResult.Val.getInt();
10023   return true;
10024 }
10025 
10026 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10027                            SideEffectsKind AllowSideEffects) const {
10028   if (!getType()->isRealFloatingType())
10029     return false;
10030 
10031   EvalResult ExprResult;
10032   if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
10033       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10034     return false;
10035 
10036   Result = ExprResult.Val.getFloat();
10037   return true;
10038 }
10039 
10040 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
10041   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
10042 
10043   LValue LV;
10044   if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10045       !CheckLValueConstantExpression(Info, getExprLoc(),
10046                                      Ctx.getLValueReferenceType(getType()), LV))
10047     return false;
10048 
10049   LV.moveInto(Result.Val);
10050   return true;
10051 }
10052 
10053 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10054                                  const VarDecl *VD,
10055                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
10056   // FIXME: Evaluating initializers for large array and record types can cause
10057   // performance problems. Only do so in C++11 for now.
10058   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
10059       !Ctx.getLangOpts().CPlusPlus11)
10060     return false;
10061 
10062   Expr::EvalStatus EStatus;
10063   EStatus.Diag = &Notes;
10064 
10065   EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10066                                       ? EvalInfo::EM_ConstantExpression
10067                                       : EvalInfo::EM_ConstantFold);
10068   InitInfo.setEvaluatingDecl(VD, Value);
10069 
10070   LValue LVal;
10071   LVal.set(VD);
10072 
10073   // C++11 [basic.start.init]p2:
10074   //  Variables with static storage duration or thread storage duration shall be
10075   //  zero-initialized before any other initialization takes place.
10076   // This behavior is not present in C.
10077   if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
10078       !VD->getType()->isReferenceType()) {
10079     ImplicitValueInitExpr VIE(VD->getType());
10080     if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
10081                          /*AllowNonLiteralTypes=*/true))
10082       return false;
10083   }
10084 
10085   if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10086                        /*AllowNonLiteralTypes=*/true) ||
10087       EStatus.HasSideEffects)
10088     return false;
10089 
10090   return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10091                                  Value);
10092 }
10093 
10094 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10095 /// constant folded, but discard the result.
10096 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
10097   EvalResult Result;
10098   return EvaluateAsRValue(Result, Ctx) &&
10099          !hasUnacceptableSideEffect(Result, SEK);
10100 }
10101 
10102 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
10103                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
10104   EvalResult EvalResult;
10105   EvalResult.Diag = Diag;
10106   bool Result = EvaluateAsRValue(EvalResult, Ctx);
10107   (void)Result;
10108   assert(Result && "Could not evaluate expression");
10109   assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
10110 
10111   return EvalResult.Val.getInt();
10112 }
10113 
10114 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
10115   bool IsConst;
10116   EvalResult EvalResult;
10117   if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
10118     EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
10119     (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10120   }
10121 }
10122 
10123 bool Expr::EvalResult::isGlobalLValue() const {
10124   assert(Val.isLValue());
10125   return IsGlobalLValue(Val.getLValueBase());
10126 }
10127 
10128 
10129 /// isIntegerConstantExpr - this recursive routine will test if an expression is
10130 /// an integer constant expression.
10131 
10132 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10133 /// comma, etc
10134 
10135 // CheckICE - This function does the fundamental ICE checking: the returned
10136 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10137 // and a (possibly null) SourceLocation indicating the location of the problem.
10138 //
10139 // Note that to reduce code duplication, this helper does no evaluation
10140 // itself; the caller checks whether the expression is evaluatable, and
10141 // in the rare cases where CheckICE actually cares about the evaluated
10142 // value, it calls into Evaluate.
10143 
10144 namespace {
10145 
10146 enum ICEKind {
10147   /// This expression is an ICE.
10148   IK_ICE,
10149   /// This expression is not an ICE, but if it isn't evaluated, it's
10150   /// a legal subexpression for an ICE. This return value is used to handle
10151   /// the comma operator in C99 mode, and non-constant subexpressions.
10152   IK_ICEIfUnevaluated,
10153   /// This expression is not an ICE, and is not a legal subexpression for one.
10154   IK_NotICE
10155 };
10156 
10157 struct ICEDiag {
10158   ICEKind Kind;
10159   SourceLocation Loc;
10160 
10161   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
10162 };
10163 
10164 }
10165 
10166 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10167 
10168 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
10169 
10170 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
10171   Expr::EvalResult EVResult;
10172   if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
10173       !EVResult.Val.isInt())
10174     return ICEDiag(IK_NotICE, E->getLocStart());
10175 
10176   return NoDiag();
10177 }
10178 
10179 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
10180   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
10181   if (!E->getType()->isIntegralOrEnumerationType())
10182     return ICEDiag(IK_NotICE, E->getLocStart());
10183 
10184   switch (E->getStmtClass()) {
10185 #define ABSTRACT_STMT(Node)
10186 #define STMT(Node, Base) case Expr::Node##Class:
10187 #define EXPR(Node, Base)
10188 #include "clang/AST/StmtNodes.inc"
10189   case Expr::PredefinedExprClass:
10190   case Expr::FloatingLiteralClass:
10191   case Expr::ImaginaryLiteralClass:
10192   case Expr::StringLiteralClass:
10193   case Expr::ArraySubscriptExprClass:
10194   case Expr::OMPArraySectionExprClass:
10195   case Expr::MemberExprClass:
10196   case Expr::CompoundAssignOperatorClass:
10197   case Expr::CompoundLiteralExprClass:
10198   case Expr::ExtVectorElementExprClass:
10199   case Expr::DesignatedInitExprClass:
10200   case Expr::ArrayInitLoopExprClass:
10201   case Expr::ArrayInitIndexExprClass:
10202   case Expr::NoInitExprClass:
10203   case Expr::DesignatedInitUpdateExprClass:
10204   case Expr::ImplicitValueInitExprClass:
10205   case Expr::ParenListExprClass:
10206   case Expr::VAArgExprClass:
10207   case Expr::AddrLabelExprClass:
10208   case Expr::StmtExprClass:
10209   case Expr::CXXMemberCallExprClass:
10210   case Expr::CUDAKernelCallExprClass:
10211   case Expr::CXXDynamicCastExprClass:
10212   case Expr::CXXTypeidExprClass:
10213   case Expr::CXXUuidofExprClass:
10214   case Expr::MSPropertyRefExprClass:
10215   case Expr::MSPropertySubscriptExprClass:
10216   case Expr::CXXNullPtrLiteralExprClass:
10217   case Expr::UserDefinedLiteralClass:
10218   case Expr::CXXThisExprClass:
10219   case Expr::CXXThrowExprClass:
10220   case Expr::CXXNewExprClass:
10221   case Expr::CXXDeleteExprClass:
10222   case Expr::CXXPseudoDestructorExprClass:
10223   case Expr::UnresolvedLookupExprClass:
10224   case Expr::TypoExprClass:
10225   case Expr::DependentScopeDeclRefExprClass:
10226   case Expr::CXXConstructExprClass:
10227   case Expr::CXXInheritedCtorInitExprClass:
10228   case Expr::CXXStdInitializerListExprClass:
10229   case Expr::CXXBindTemporaryExprClass:
10230   case Expr::ExprWithCleanupsClass:
10231   case Expr::CXXTemporaryObjectExprClass:
10232   case Expr::CXXUnresolvedConstructExprClass:
10233   case Expr::CXXDependentScopeMemberExprClass:
10234   case Expr::UnresolvedMemberExprClass:
10235   case Expr::ObjCStringLiteralClass:
10236   case Expr::ObjCBoxedExprClass:
10237   case Expr::ObjCArrayLiteralClass:
10238   case Expr::ObjCDictionaryLiteralClass:
10239   case Expr::ObjCEncodeExprClass:
10240   case Expr::ObjCMessageExprClass:
10241   case Expr::ObjCSelectorExprClass:
10242   case Expr::ObjCProtocolExprClass:
10243   case Expr::ObjCIvarRefExprClass:
10244   case Expr::ObjCPropertyRefExprClass:
10245   case Expr::ObjCSubscriptRefExprClass:
10246   case Expr::ObjCIsaExprClass:
10247   case Expr::ObjCAvailabilityCheckExprClass:
10248   case Expr::ShuffleVectorExprClass:
10249   case Expr::ConvertVectorExprClass:
10250   case Expr::BlockExprClass:
10251   case Expr::NoStmtClass:
10252   case Expr::OpaqueValueExprClass:
10253   case Expr::PackExpansionExprClass:
10254   case Expr::SubstNonTypeTemplateParmPackExprClass:
10255   case Expr::FunctionParmPackExprClass:
10256   case Expr::AsTypeExprClass:
10257   case Expr::ObjCIndirectCopyRestoreExprClass:
10258   case Expr::MaterializeTemporaryExprClass:
10259   case Expr::PseudoObjectExprClass:
10260   case Expr::AtomicExprClass:
10261   case Expr::LambdaExprClass:
10262   case Expr::CXXFoldExprClass:
10263   case Expr::CoawaitExprClass:
10264   case Expr::DependentCoawaitExprClass:
10265   case Expr::CoyieldExprClass:
10266     return ICEDiag(IK_NotICE, E->getLocStart());
10267 
10268   case Expr::InitListExprClass: {
10269     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10270     // form "T x = { a };" is equivalent to "T x = a;".
10271     // Unless we're initializing a reference, T is a scalar as it is known to be
10272     // of integral or enumeration type.
10273     if (E->isRValue())
10274       if (cast<InitListExpr>(E)->getNumInits() == 1)
10275         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10276     return ICEDiag(IK_NotICE, E->getLocStart());
10277   }
10278 
10279   case Expr::SizeOfPackExprClass:
10280   case Expr::GNUNullExprClass:
10281     // GCC considers the GNU __null value to be an integral constant expression.
10282     return NoDiag();
10283 
10284   case Expr::SubstNonTypeTemplateParmExprClass:
10285     return
10286       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10287 
10288   case Expr::ParenExprClass:
10289     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
10290   case Expr::GenericSelectionExprClass:
10291     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
10292   case Expr::IntegerLiteralClass:
10293   case Expr::CharacterLiteralClass:
10294   case Expr::ObjCBoolLiteralExprClass:
10295   case Expr::CXXBoolLiteralExprClass:
10296   case Expr::CXXScalarValueInitExprClass:
10297   case Expr::TypeTraitExprClass:
10298   case Expr::ArrayTypeTraitExprClass:
10299   case Expr::ExpressionTraitExprClass:
10300   case Expr::CXXNoexceptExprClass:
10301     return NoDiag();
10302   case Expr::CallExprClass:
10303   case Expr::CXXOperatorCallExprClass: {
10304     // C99 6.6/3 allows function calls within unevaluated subexpressions of
10305     // constant expressions, but they can never be ICEs because an ICE cannot
10306     // contain an operand of (pointer to) function type.
10307     const CallExpr *CE = cast<CallExpr>(E);
10308     if (CE->getBuiltinCallee())
10309       return CheckEvalInICE(E, Ctx);
10310     return ICEDiag(IK_NotICE, E->getLocStart());
10311   }
10312   case Expr::DeclRefExprClass: {
10313     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10314       return NoDiag();
10315     const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
10316     if (Ctx.getLangOpts().CPlusPlus &&
10317         D && IsConstNonVolatile(D->getType())) {
10318       // Parameter variables are never constants.  Without this check,
10319       // getAnyInitializer() can find a default argument, which leads
10320       // to chaos.
10321       if (isa<ParmVarDecl>(D))
10322         return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10323 
10324       // C++ 7.1.5.1p2
10325       //   A variable of non-volatile const-qualified integral or enumeration
10326       //   type initialized by an ICE can be used in ICEs.
10327       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
10328         if (!Dcl->getType()->isIntegralOrEnumerationType())
10329           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10330 
10331         const VarDecl *VD;
10332         // Look for a declaration of this variable that has an initializer, and
10333         // check whether it is an ICE.
10334         if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10335           return NoDiag();
10336         else
10337           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10338       }
10339     }
10340     return ICEDiag(IK_NotICE, E->getLocStart());
10341   }
10342   case Expr::UnaryOperatorClass: {
10343     const UnaryOperator *Exp = cast<UnaryOperator>(E);
10344     switch (Exp->getOpcode()) {
10345     case UO_PostInc:
10346     case UO_PostDec:
10347     case UO_PreInc:
10348     case UO_PreDec:
10349     case UO_AddrOf:
10350     case UO_Deref:
10351     case UO_Coawait:
10352       // C99 6.6/3 allows increment and decrement within unevaluated
10353       // subexpressions of constant expressions, but they can never be ICEs
10354       // because an ICE cannot contain an lvalue operand.
10355       return ICEDiag(IK_NotICE, E->getLocStart());
10356     case UO_Extension:
10357     case UO_LNot:
10358     case UO_Plus:
10359     case UO_Minus:
10360     case UO_Not:
10361     case UO_Real:
10362     case UO_Imag:
10363       return CheckICE(Exp->getSubExpr(), Ctx);
10364     }
10365 
10366     // OffsetOf falls through here.
10367     LLVM_FALLTHROUGH;
10368   }
10369   case Expr::OffsetOfExprClass: {
10370     // Note that per C99, offsetof must be an ICE. And AFAIK, using
10371     // EvaluateAsRValue matches the proposed gcc behavior for cases like
10372     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
10373     // compliance: we should warn earlier for offsetof expressions with
10374     // array subscripts that aren't ICEs, and if the array subscripts
10375     // are ICEs, the value of the offsetof must be an integer constant.
10376     return CheckEvalInICE(E, Ctx);
10377   }
10378   case Expr::UnaryExprOrTypeTraitExprClass: {
10379     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10380     if ((Exp->getKind() ==  UETT_SizeOf) &&
10381         Exp->getTypeOfArgument()->isVariableArrayType())
10382       return ICEDiag(IK_NotICE, E->getLocStart());
10383     return NoDiag();
10384   }
10385   case Expr::BinaryOperatorClass: {
10386     const BinaryOperator *Exp = cast<BinaryOperator>(E);
10387     switch (Exp->getOpcode()) {
10388     case BO_PtrMemD:
10389     case BO_PtrMemI:
10390     case BO_Assign:
10391     case BO_MulAssign:
10392     case BO_DivAssign:
10393     case BO_RemAssign:
10394     case BO_AddAssign:
10395     case BO_SubAssign:
10396     case BO_ShlAssign:
10397     case BO_ShrAssign:
10398     case BO_AndAssign:
10399     case BO_XorAssign:
10400     case BO_OrAssign:
10401       // C99 6.6/3 allows assignments within unevaluated subexpressions of
10402       // constant expressions, but they can never be ICEs because an ICE cannot
10403       // contain an lvalue operand.
10404       return ICEDiag(IK_NotICE, E->getLocStart());
10405 
10406     case BO_Mul:
10407     case BO_Div:
10408     case BO_Rem:
10409     case BO_Add:
10410     case BO_Sub:
10411     case BO_Shl:
10412     case BO_Shr:
10413     case BO_LT:
10414     case BO_GT:
10415     case BO_LE:
10416     case BO_GE:
10417     case BO_EQ:
10418     case BO_NE:
10419     case BO_And:
10420     case BO_Xor:
10421     case BO_Or:
10422     case BO_Comma: {
10423       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10424       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
10425       if (Exp->getOpcode() == BO_Div ||
10426           Exp->getOpcode() == BO_Rem) {
10427         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
10428         // we don't evaluate one.
10429         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
10430           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
10431           if (REval == 0)
10432             return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10433           if (REval.isSigned() && REval.isAllOnesValue()) {
10434             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
10435             if (LEval.isMinSignedValue())
10436               return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10437           }
10438         }
10439       }
10440       if (Exp->getOpcode() == BO_Comma) {
10441         if (Ctx.getLangOpts().C99) {
10442           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10443           // if it isn't evaluated.
10444           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10445             return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10446         } else {
10447           // In both C89 and C++, commas in ICEs are illegal.
10448           return ICEDiag(IK_NotICE, E->getLocStart());
10449         }
10450       }
10451       return Worst(LHSResult, RHSResult);
10452     }
10453     case BO_LAnd:
10454     case BO_LOr: {
10455       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10456       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
10457       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
10458         // Rare case where the RHS has a comma "side-effect"; we need
10459         // to actually check the condition to see whether the side
10460         // with the comma is evaluated.
10461         if ((Exp->getOpcode() == BO_LAnd) !=
10462             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
10463           return RHSResult;
10464         return NoDiag();
10465       }
10466 
10467       return Worst(LHSResult, RHSResult);
10468     }
10469     }
10470     LLVM_FALLTHROUGH;
10471   }
10472   case Expr::ImplicitCastExprClass:
10473   case Expr::CStyleCastExprClass:
10474   case Expr::CXXFunctionalCastExprClass:
10475   case Expr::CXXStaticCastExprClass:
10476   case Expr::CXXReinterpretCastExprClass:
10477   case Expr::CXXConstCastExprClass:
10478   case Expr::ObjCBridgedCastExprClass: {
10479     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
10480     if (isa<ExplicitCastExpr>(E)) {
10481       if (const FloatingLiteral *FL
10482             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10483         unsigned DestWidth = Ctx.getIntWidth(E->getType());
10484         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10485         APSInt IgnoredVal(DestWidth, !DestSigned);
10486         bool Ignored;
10487         // If the value does not fit in the destination type, the behavior is
10488         // undefined, so we are not required to treat it as a constant
10489         // expression.
10490         if (FL->getValue().convertToInteger(IgnoredVal,
10491                                             llvm::APFloat::rmTowardZero,
10492                                             &Ignored) & APFloat::opInvalidOp)
10493           return ICEDiag(IK_NotICE, E->getLocStart());
10494         return NoDiag();
10495       }
10496     }
10497     switch (cast<CastExpr>(E)->getCastKind()) {
10498     case CK_LValueToRValue:
10499     case CK_AtomicToNonAtomic:
10500     case CK_NonAtomicToAtomic:
10501     case CK_NoOp:
10502     case CK_IntegralToBoolean:
10503     case CK_IntegralCast:
10504       return CheckICE(SubExpr, Ctx);
10505     default:
10506       return ICEDiag(IK_NotICE, E->getLocStart());
10507     }
10508   }
10509   case Expr::BinaryConditionalOperatorClass: {
10510     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10511     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
10512     if (CommonResult.Kind == IK_NotICE) return CommonResult;
10513     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
10514     if (FalseResult.Kind == IK_NotICE) return FalseResult;
10515     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10516     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
10517         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
10518     return FalseResult;
10519   }
10520   case Expr::ConditionalOperatorClass: {
10521     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10522     // If the condition (ignoring parens) is a __builtin_constant_p call,
10523     // then only the true side is actually considered in an integer constant
10524     // expression, and it is fully evaluated.  This is an important GNU
10525     // extension.  See GCC PR38377 for discussion.
10526     if (const CallExpr *CallCE
10527         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
10528       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
10529         return CheckEvalInICE(E, Ctx);
10530     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
10531     if (CondResult.Kind == IK_NotICE)
10532       return CondResult;
10533 
10534     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10535     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
10536 
10537     if (TrueResult.Kind == IK_NotICE)
10538       return TrueResult;
10539     if (FalseResult.Kind == IK_NotICE)
10540       return FalseResult;
10541     if (CondResult.Kind == IK_ICEIfUnevaluated)
10542       return CondResult;
10543     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
10544       return NoDiag();
10545     // Rare case where the diagnostics depend on which side is evaluated
10546     // Note that if we get here, CondResult is 0, and at least one of
10547     // TrueResult and FalseResult is non-zero.
10548     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
10549       return FalseResult;
10550     return TrueResult;
10551   }
10552   case Expr::CXXDefaultArgExprClass:
10553     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
10554   case Expr::CXXDefaultInitExprClass:
10555     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
10556   case Expr::ChooseExprClass: {
10557     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
10558   }
10559   }
10560 
10561   llvm_unreachable("Invalid StmtClass!");
10562 }
10563 
10564 /// Evaluate an expression as a C++11 integral constant expression.
10565 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
10566                                                     const Expr *E,
10567                                                     llvm::APSInt *Value,
10568                                                     SourceLocation *Loc) {
10569   if (!E->getType()->isIntegralOrEnumerationType()) {
10570     if (Loc) *Loc = E->getExprLoc();
10571     return false;
10572   }
10573 
10574   APValue Result;
10575   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
10576     return false;
10577 
10578   if (!Result.isInt()) {
10579     if (Loc) *Loc = E->getExprLoc();
10580     return false;
10581   }
10582 
10583   if (Value) *Value = Result.getInt();
10584   return true;
10585 }
10586 
10587 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10588                                  SourceLocation *Loc) const {
10589   if (Ctx.getLangOpts().CPlusPlus11)
10590     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
10591 
10592   ICEDiag D = CheckICE(this, Ctx);
10593   if (D.Kind != IK_ICE) {
10594     if (Loc) *Loc = D.Loc;
10595     return false;
10596   }
10597   return true;
10598 }
10599 
10600 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
10601                                  SourceLocation *Loc, bool isEvaluated) const {
10602   if (Ctx.getLangOpts().CPlusPlus11)
10603     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10604 
10605   if (!isIntegerConstantExpr(Ctx, Loc))
10606     return false;
10607   // The only possible side-effects here are due to UB discovered in the
10608   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10609   // required to treat the expression as an ICE, so we produce the folded
10610   // value.
10611   if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
10612     llvm_unreachable("ICE cannot be evaluated!");
10613   return true;
10614 }
10615 
10616 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
10617   return CheckICE(this, Ctx).Kind == IK_ICE;
10618 }
10619 
10620 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
10621                                SourceLocation *Loc) const {
10622   // We support this checking in C++98 mode in order to diagnose compatibility
10623   // issues.
10624   assert(Ctx.getLangOpts().CPlusPlus);
10625 
10626   // Build evaluation settings.
10627   Expr::EvalStatus Status;
10628   SmallVector<PartialDiagnosticAt, 8> Diags;
10629   Status.Diag = &Diags;
10630   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
10631 
10632   APValue Scratch;
10633   bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10634 
10635   if (!Diags.empty()) {
10636     IsConstExpr = false;
10637     if (Loc) *Loc = Diags[0].first;
10638   } else if (!IsConstExpr) {
10639     // FIXME: This shouldn't happen.
10640     if (Loc) *Loc = getExprLoc();
10641   }
10642 
10643   return IsConstExpr;
10644 }
10645 
10646 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10647                                     const FunctionDecl *Callee,
10648                                     ArrayRef<const Expr*> Args,
10649                                     const Expr *This) const {
10650   Expr::EvalStatus Status;
10651   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10652 
10653   LValue ThisVal;
10654   const LValue *ThisPtr = nullptr;
10655   if (This) {
10656 #ifndef NDEBUG
10657     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10658     assert(MD && "Don't provide `this` for non-methods.");
10659     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10660 #endif
10661     if (EvaluateObjectArgument(Info, This, ThisVal))
10662       ThisPtr = &ThisVal;
10663     if (Info.EvalStatus.HasSideEffects)
10664       return false;
10665   }
10666 
10667   ArgVector ArgValues(Args.size());
10668   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10669        I != E; ++I) {
10670     if ((*I)->isValueDependent() ||
10671         !Evaluate(ArgValues[I - Args.begin()], Info, *I))
10672       // If evaluation fails, throw away the argument entirely.
10673       ArgValues[I - Args.begin()] = APValue();
10674     if (Info.EvalStatus.HasSideEffects)
10675       return false;
10676   }
10677 
10678   // Build fake call to Callee.
10679   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
10680                        ArgValues.data());
10681   return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10682 }
10683 
10684 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
10685                                    SmallVectorImpl<
10686                                      PartialDiagnosticAt> &Diags) {
10687   // FIXME: It would be useful to check constexpr function templates, but at the
10688   // moment the constant expression evaluator cannot cope with the non-rigorous
10689   // ASTs which we build for dependent expressions.
10690   if (FD->isDependentContext())
10691     return true;
10692 
10693   Expr::EvalStatus Status;
10694   Status.Diag = &Diags;
10695 
10696   EvalInfo Info(FD->getASTContext(), Status,
10697                 EvalInfo::EM_PotentialConstantExpression);
10698 
10699   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
10700   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
10701 
10702   // Fabricate an arbitrary expression on the stack and pretend that it
10703   // is a temporary being used as the 'this' pointer.
10704   LValue This;
10705   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
10706   This.set(&VIE, Info.CurrentCall->Index);
10707 
10708   ArrayRef<const Expr*> Args;
10709 
10710   APValue Scratch;
10711   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10712     // Evaluate the call as a constant initializer, to allow the construction
10713     // of objects of non-literal types.
10714     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
10715     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10716   } else {
10717     SourceLocation Loc = FD->getLocation();
10718     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
10719                        Args, FD->getBody(), Info, Scratch, nullptr);
10720   }
10721 
10722   return Diags.empty();
10723 }
10724 
10725 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10726                                               const FunctionDecl *FD,
10727                                               SmallVectorImpl<
10728                                                 PartialDiagnosticAt> &Diags) {
10729   Expr::EvalStatus Status;
10730   Status.Diag = &Diags;
10731 
10732   EvalInfo Info(FD->getASTContext(), Status,
10733                 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10734 
10735   // Fabricate a call stack frame to give the arguments a plausible cover story.
10736   ArrayRef<const Expr*> Args;
10737   ArgVector ArgValues(0);
10738   bool Success = EvaluateArgs(Args, ArgValues, Info);
10739   (void)Success;
10740   assert(Success &&
10741          "Failed to set up arguments for potential constant evaluation");
10742   CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
10743 
10744   APValue ResultScratch;
10745   Evaluate(ResultScratch, Info, E);
10746   return Diags.empty();
10747 }
10748 
10749 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10750                                  unsigned Type) const {
10751   if (!getType()->isPointerType())
10752     return false;
10753 
10754   Expr::EvalStatus Status;
10755   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
10756   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
10757 }
10758