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