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