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