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