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