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