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