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