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