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