clang  9.0.0svn
ExprConstant.cpp
Go to the documentation of this file.
1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Expr constant evaluator.
10 //
11 // Constant expression evaluation produces four main results:
12 //
13 // * A success/failure flag indicating whether constant folding was successful.
14 // This is the 'bool' return value used by most of the code in this file. A
15 // 'false' return value indicates that constant folding has failed, and any
16 // appropriate diagnostic has already been produced.
17 //
18 // * An evaluated result, valid only if constant folding has not failed.
19 //
20 // * A flag indicating if evaluation encountered (unevaluated) side-effects.
21 // These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22 // where it is possible to determine the evaluated result regardless.
23 //
24 // * A set of notes indicating why the evaluation was not a constant expression
25 // (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26 // too, why the expression could not be folded.
27 //
28 // If we are checking for a potential constant expression, failure to constant
29 // fold a potential constant sub-expression will be indicated by a 'false'
30 // return value (the expression could not be folded) and no diagnostic (the
31 // expression is not necessarily non-constant).
32 //
33 //===----------------------------------------------------------------------===//
34 
35 #include "clang/AST/APValue.h"
36 #include "clang/AST/ASTContext.h"
38 #include "clang/AST/ASTLambda.h"
39 #include "clang/AST/CharUnits.h"
40 #include "clang/AST/Expr.h"
41 #include "clang/AST/OSLog.h"
42 #include "clang/AST/RecordLayout.h"
43 #include "clang/AST/StmtVisitor.h"
44 #include "clang/AST/TypeLoc.h"
45 #include "clang/Basic/Builtins.h"
46 #include "clang/Basic/FixedPoint.h"
47 #include "clang/Basic/TargetInfo.h"
48 #include "llvm/Support/SaveAndRestore.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include <cstring>
51 #include <functional>
52 
53 #define DEBUG_TYPE "exprconstant"
54 
55 using namespace clang;
56 using llvm::APSInt;
57 using llvm::APFloat;
58 
59 static bool IsGlobalLValue(APValue::LValueBase B);
60 
61 namespace {
62  struct LValue;
63  struct CallStackFrame;
64  struct EvalInfo;
65 
66  static QualType getType(APValue::LValueBase B) {
67  if (!B) return QualType();
68  if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
69  // FIXME: It's unclear where we're supposed to take the type from, and
70  // this actually matters for arrays of unknown bound. Eg:
71  //
72  // extern int arr[]; void f() { extern int arr[3]; };
73  // constexpr int *p = &arr[1]; // valid?
74  //
75  // For now, we take the array bound from the most recent declaration.
76  for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
77  Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
78  QualType T = Redecl->getType();
79  if (!T->isIncompleteArrayType())
80  return T;
81  }
82  return D->getType();
83  }
84 
85  const Expr *Base = B.get<const Expr*>();
86 
87  // For a materialized temporary, the type of the temporary we materialized
88  // may not be the type of the expression.
89  if (const MaterializeTemporaryExpr *MTE =
90  dyn_cast<MaterializeTemporaryExpr>(Base)) {
93  const Expr *Temp = MTE->GetTemporaryExpr();
94  const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
95  Adjustments);
96  // Keep any cv-qualifiers from the reference if we generated a temporary
97  // for it directly. Otherwise use the type after adjustment.
98  if (!Adjustments.empty())
99  return Inner->getType();
100  }
101 
102  return Base->getType();
103  }
104 
105  /// Get an LValue path entry, which is known to not be an array index, as a
106  /// field or base class.
107  static
110  Value.setFromOpaqueValue(E.BaseOrMember);
111  return Value;
112  }
113 
114  /// Get an LValue path entry, which is known to not be an array index, as a
115  /// field declaration.
116  static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
117  return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
118  }
119  /// Get an LValue path entry, which is known to not be an array index, as a
120  /// base class declaration.
121  static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
122  return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
123  }
124  /// Determine whether this LValue path entry for a base class names a virtual
125  /// base class.
126  static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
127  return getAsBaseOrMember(E).getInt();
128  }
129 
130  /// Given a CallExpr, try to get the alloc_size attribute. May return null.
131  static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
132  const FunctionDecl *Callee = CE->getDirectCallee();
133  return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
134  }
135 
136  /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
137  /// This will look through a single cast.
138  ///
139  /// Returns null if we couldn't unwrap a function with alloc_size.
140  static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
141  if (!E->getType()->isPointerType())
142  return nullptr;
143 
144  E = E->IgnoreParens();
145  // If we're doing a variable assignment from e.g. malloc(N), there will
146  // probably be a cast of some kind. In exotic cases, we might also see a
147  // top-level ExprWithCleanups. Ignore them either way.
148  if (const auto *FE = dyn_cast<FullExpr>(E))
149  E = FE->getSubExpr()->IgnoreParens();
150 
151  if (const auto *Cast = dyn_cast<CastExpr>(E))
152  E = Cast->getSubExpr()->IgnoreParens();
153 
154  if (const auto *CE = dyn_cast<CallExpr>(E))
155  return getAllocSizeAttr(CE) ? CE : nullptr;
156  return nullptr;
157  }
158 
159  /// Determines whether or not the given Base contains a call to a function
160  /// with the alloc_size attribute.
161  static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
162  const auto *E = Base.dyn_cast<const Expr *>();
163  return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
164  }
165 
166  /// The bound to claim that an array of unknown bound has.
167  /// The value in MostDerivedArraySize is undefined in this case. So, set it
168  /// to an arbitrary value that's likely to loudly break things if it's used.
169  static const uint64_t AssumedSizeForUnsizedArray =
171 
172  /// Determines if an LValue with the given LValueBase will have an unsized
173  /// array in its designator.
174  /// Find the path length and type of the most-derived subobject in the given
175  /// path, and find the size of the containing array, if any.
176  static unsigned
177  findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
179  uint64_t &ArraySize, QualType &Type, bool &IsArray,
180  bool &FirstEntryIsUnsizedArray) {
181  // This only accepts LValueBases from APValues, and APValues don't support
182  // arrays that lack size info.
183  assert(!isBaseAnAllocSizeCall(Base) &&
184  "Unsized arrays shouldn't appear here");
185  unsigned MostDerivedLength = 0;
186  Type = getType(Base);
187 
188  for (unsigned I = 0, N = Path.size(); I != N; ++I) {
189  if (Type->isArrayType()) {
190  const ArrayType *AT = Ctx.getAsArrayType(Type);
191  Type = AT->getElementType();
192  MostDerivedLength = I + 1;
193  IsArray = true;
194 
195  if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
196  ArraySize = CAT->getSize().getZExtValue();
197  } else {
198  assert(I == 0 && "unexpected unsized array designator");
199  FirstEntryIsUnsizedArray = true;
200  ArraySize = AssumedSizeForUnsizedArray;
201  }
202  } else if (Type->isAnyComplexType()) {
203  const ComplexType *CT = Type->castAs<ComplexType>();
204  Type = CT->getElementType();
205  ArraySize = 2;
206  MostDerivedLength = I + 1;
207  IsArray = true;
208  } else if (const FieldDecl *FD = getAsField(Path[I])) {
209  Type = FD->getType();
210  ArraySize = 0;
211  MostDerivedLength = I + 1;
212  IsArray = false;
213  } else {
214  // Path[I] describes a base class.
215  ArraySize = 0;
216  IsArray = false;
217  }
218  }
219  return MostDerivedLength;
220  }
221 
222  // The order of this enum is important for diagnostics.
224  CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
225  CSK_This, CSK_Real, CSK_Imag
226  };
227 
228  /// A path from a glvalue to a subobject of that glvalue.
229  struct SubobjectDesignator {
230  /// True if the subobject was named in a manner not supported by C++11. Such
231  /// lvalues can still be folded, but they are not core constant expressions
232  /// and we cannot perform lvalue-to-rvalue conversions on them.
233  unsigned Invalid : 1;
234 
235  /// Is this a pointer one past the end of an object?
236  unsigned IsOnePastTheEnd : 1;
237 
238  /// Indicator of whether the first entry is an unsized array.
239  unsigned FirstEntryIsAnUnsizedArray : 1;
240 
241  /// Indicator of whether the most-derived object is an array element.
242  unsigned MostDerivedIsArrayElement : 1;
243 
244  /// The length of the path to the most-derived object of which this is a
245  /// subobject.
246  unsigned MostDerivedPathLength : 28;
247 
248  /// The size of the array of which the most-derived object is an element.
249  /// This will always be 0 if the most-derived object is not an array
250  /// element. 0 is not an indicator of whether or not the most-derived object
251  /// is an array, however, because 0-length arrays are allowed.
252  ///
253  /// If the current array is an unsized array, the value of this is
254  /// undefined.
255  uint64_t MostDerivedArraySize;
256 
257  /// The type of the most derived object referred to by this address.
258  QualType MostDerivedType;
259 
260  typedef APValue::LValuePathEntry PathEntry;
261 
262  /// The entries on the path from the glvalue to the designated subobject.
264 
265  SubobjectDesignator() : Invalid(true) {}
266 
267  explicit SubobjectDesignator(QualType T)
268  : Invalid(false), IsOnePastTheEnd(false),
269  FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
270  MostDerivedPathLength(0), MostDerivedArraySize(0),
271  MostDerivedType(T) {}
272 
273  SubobjectDesignator(ASTContext &Ctx, const APValue &V)
274  : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
275  FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
276  MostDerivedPathLength(0), MostDerivedArraySize(0) {
277  assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
278  if (!Invalid) {
279  IsOnePastTheEnd = V.isLValueOnePastTheEnd();
280  ArrayRef<PathEntry> VEntries = V.getLValuePath();
281  Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
282  if (V.getLValueBase()) {
283  bool IsArray = false;
284  bool FirstIsUnsizedArray = false;
285  MostDerivedPathLength = findMostDerivedSubobject(
286  Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
287  MostDerivedType, IsArray, FirstIsUnsizedArray);
288  MostDerivedIsArrayElement = IsArray;
289  FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
290  }
291  }
292  }
293 
294  void setInvalid() {
295  Invalid = true;
296  Entries.clear();
297  }
298 
299  /// Determine whether the most derived subobject is an array without a
300  /// known bound.
301  bool isMostDerivedAnUnsizedArray() const {
302  assert(!Invalid && "Calling this makes no sense on invalid designators");
303  return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
304  }
305 
306  /// Determine what the most derived array's size is. Results in an assertion
307  /// failure if the most derived array lacks a size.
308  uint64_t getMostDerivedArraySize() const {
309  assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
310  return MostDerivedArraySize;
311  }
312 
313  /// Determine whether this is a one-past-the-end pointer.
314  bool isOnePastTheEnd() const {
315  assert(!Invalid);
316  if (IsOnePastTheEnd)
317  return true;
318  if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
319  Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
320  return true;
321  return false;
322  }
323 
324  /// Get the range of valid index adjustments in the form
325  /// {maximum value that can be subtracted from this pointer,
326  /// maximum value that can be added to this pointer}
327  std::pair<uint64_t, uint64_t> validIndexAdjustments() {
328  if (Invalid || isMostDerivedAnUnsizedArray())
329  return {0, 0};
330 
331  // [expr.add]p4: For the purposes of these operators, a pointer to a
332  // nonarray object behaves the same as a pointer to the first element of
333  // an array of length one with the type of the object as its element type.
334  bool IsArray = MostDerivedPathLength == Entries.size() &&
335  MostDerivedIsArrayElement;
336  uint64_t ArrayIndex =
337  IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
338  uint64_t ArraySize =
339  IsArray ? getMostDerivedArraySize() : (uint64_t)1;
340  return {ArrayIndex, ArraySize - ArrayIndex};
341  }
342 
343  /// Check that this refers to a valid subobject.
344  bool isValidSubobject() const {
345  if (Invalid)
346  return false;
347  return !isOnePastTheEnd();
348  }
349  /// Check that this refers to a valid subobject, and if not, produce a
350  /// relevant diagnostic and set the designator as invalid.
351  bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
352 
353  /// Get the type of the designated object.
354  QualType getType(ASTContext &Ctx) const {
355  assert(!Invalid && "invalid designator has no subobject type");
356  return MostDerivedPathLength == Entries.size()
357  ? MostDerivedType
358  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
359  }
360 
361  /// Update this designator to refer to the first element within this array.
362  void addArrayUnchecked(const ConstantArrayType *CAT) {
363  PathEntry Entry;
364  Entry.ArrayIndex = 0;
365  Entries.push_back(Entry);
366 
367  // This is a most-derived object.
368  MostDerivedType = CAT->getElementType();
369  MostDerivedIsArrayElement = true;
370  MostDerivedArraySize = CAT->getSize().getZExtValue();
371  MostDerivedPathLength = Entries.size();
372  }
373  /// Update this designator to refer to the first element within the array of
374  /// elements of type T. This is an array of unknown size.
375  void addUnsizedArrayUnchecked(QualType ElemTy) {
376  PathEntry Entry;
377  Entry.ArrayIndex = 0;
378  Entries.push_back(Entry);
379 
380  MostDerivedType = ElemTy;
381  MostDerivedIsArrayElement = true;
382  // The value in MostDerivedArraySize is undefined in this case. So, set it
383  // to an arbitrary value that's likely to loudly break things if it's
384  // used.
385  MostDerivedArraySize = AssumedSizeForUnsizedArray;
386  MostDerivedPathLength = Entries.size();
387  }
388  /// Update this designator to refer to the given base or member of this
389  /// object.
390  void addDeclUnchecked(const Decl *D, bool Virtual = false) {
391  PathEntry Entry;
392  APValue::BaseOrMemberType Value(D, Virtual);
393  Entry.BaseOrMember = Value.getOpaqueValue();
394  Entries.push_back(Entry);
395 
396  // If this isn't a base class, it's a new most-derived object.
397  if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
398  MostDerivedType = FD->getType();
399  MostDerivedIsArrayElement = false;
400  MostDerivedArraySize = 0;
401  MostDerivedPathLength = Entries.size();
402  }
403  }
404  /// Update this designator to refer to the given complex component.
405  void addComplexUnchecked(QualType EltTy, bool Imag) {
406  PathEntry Entry;
407  Entry.ArrayIndex = Imag;
408  Entries.push_back(Entry);
409 
410  // This is technically a most-derived object, though in practice this
411  // is unlikely to matter.
412  MostDerivedType = EltTy;
413  MostDerivedIsArrayElement = true;
414  MostDerivedArraySize = 2;
415  MostDerivedPathLength = Entries.size();
416  }
417  void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
418  void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
419  const APSInt &N);
420  /// Add N to the address of this subobject.
421  void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
422  if (Invalid || !N) return;
423  uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
424  if (isMostDerivedAnUnsizedArray()) {
425  diagnoseUnsizedArrayPointerArithmetic(Info, E);
426  // Can't verify -- trust that the user is doing the right thing (or if
427  // not, trust that the caller will catch the bad behavior).
428  // FIXME: Should we reject if this overflows, at least?
429  Entries.back().ArrayIndex += TruncatedN;
430  return;
431  }
432 
433  // [expr.add]p4: For the purposes of these operators, a pointer to a
434  // nonarray object behaves the same as a pointer to the first element of
435  // an array of length one with the type of the object as its element type.
436  bool IsArray = MostDerivedPathLength == Entries.size() &&
437  MostDerivedIsArrayElement;
438  uint64_t ArrayIndex =
439  IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
440  uint64_t ArraySize =
441  IsArray ? getMostDerivedArraySize() : (uint64_t)1;
442 
443  if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
444  // Calculate the actual index in a wide enough type, so we can include
445  // it in the note.
446  N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
447  (llvm::APInt&)N += ArrayIndex;
448  assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
449  diagnosePointerArithmetic(Info, E, N);
450  setInvalid();
451  return;
452  }
453 
454  ArrayIndex += TruncatedN;
455  assert(ArrayIndex <= ArraySize &&
456  "bounds check succeeded for out-of-bounds index");
457 
458  if (IsArray)
459  Entries.back().ArrayIndex = ArrayIndex;
460  else
461  IsOnePastTheEnd = (ArrayIndex != 0);
462  }
463  };
464 
465  /// A stack frame in the constexpr call stack.
466  struct CallStackFrame {
467  EvalInfo &Info;
468 
469  /// Parent - The caller of this stack frame.
470  CallStackFrame *Caller;
471 
472  /// Callee - The function which was called.
473  const FunctionDecl *Callee;
474 
475  /// This - The binding for the this pointer in this call, if any.
476  const LValue *This;
477 
478  /// Arguments - Parameter bindings for this function call, indexed by
479  /// parameters' function scope indices.
480  APValue *Arguments;
481 
482  // Note that we intentionally use std::map here so that references to
483  // values are stable.
484  typedef std::pair<const void *, unsigned> MapKeyTy;
485  typedef std::map<MapKeyTy, APValue> MapTy;
486  /// Temporaries - Temporary lvalues materialized within this stack frame.
487  MapTy Temporaries;
488 
489  /// CallLoc - The location of the call expression for this call.
490  SourceLocation CallLoc;
491 
492  /// Index - The call index of this call.
493  unsigned Index;
494 
495  /// The stack of integers for tracking version numbers for temporaries.
496  SmallVector<unsigned, 2> TempVersionStack = {1};
497  unsigned CurTempVersion = TempVersionStack.back();
498 
499  unsigned getTempVersion() const { return TempVersionStack.back(); }
500 
501  void pushTempVersion() {
502  TempVersionStack.push_back(++CurTempVersion);
503  }
504 
505  void popTempVersion() {
506  TempVersionStack.pop_back();
507  }
508 
509  // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
510  // on the overall stack usage of deeply-recursing constexpr evaluations.
511  // (We should cache this map rather than recomputing it repeatedly.)
512  // But let's try this and see how it goes; we can look into caching the map
513  // as a later change.
514 
515  /// LambdaCaptureFields - Mapping from captured variables/this to
516  /// corresponding data members in the closure class.
517  llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
518  FieldDecl *LambdaThisCaptureField;
519 
520  CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
521  const FunctionDecl *Callee, const LValue *This,
522  APValue *Arguments);
523  ~CallStackFrame();
524 
525  // Return the temporary for Key whose version number is Version.
526  APValue *getTemporary(const void *Key, unsigned Version) {
527  MapKeyTy KV(Key, Version);
528  auto LB = Temporaries.lower_bound(KV);
529  if (LB != Temporaries.end() && LB->first == KV)
530  return &LB->second;
531  // Pair (Key,Version) wasn't found in the map. Check that no elements
532  // in the map have 'Key' as their key.
533  assert((LB == Temporaries.end() || LB->first.first != Key) &&
534  (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
535  "Element with key 'Key' found in map");
536  return nullptr;
537  }
538 
539  // Return the current temporary for Key in the map.
540  APValue *getCurrentTemporary(const void *Key) {
541  auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
542  if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
543  return &std::prev(UB)->second;
544  return nullptr;
545  }
546 
547  // Return the version number of the current temporary for Key.
548  unsigned getCurrentTemporaryVersion(const void *Key) const {
549  auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
550  if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
551  return std::prev(UB)->first.second;
552  return 0;
553  }
554 
555  APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
556  };
557 
558  /// Temporarily override 'this'.
559  class ThisOverrideRAII {
560  public:
561  ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
562  : Frame(Frame), OldThis(Frame.This) {
563  if (Enable)
564  Frame.This = NewThis;
565  }
566  ~ThisOverrideRAII() {
567  Frame.This = OldThis;
568  }
569  private:
570  CallStackFrame &Frame;
571  const LValue *OldThis;
572  };
573 
574  /// A partial diagnostic which we might know in advance that we are not going
575  /// to emit.
576  class OptionalDiagnostic {
578 
579  public:
580  explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
581  : Diag(Diag) {}
582 
583  template<typename T>
584  OptionalDiagnostic &operator<<(const T &v) {
585  if (Diag)
586  *Diag << v;
587  return *this;
588  }
589 
590  OptionalDiagnostic &operator<<(const APSInt &I) {
591  if (Diag) {
592  SmallVector<char, 32> Buffer;
593  I.toString(Buffer);
594  *Diag << StringRef(Buffer.data(), Buffer.size());
595  }
596  return *this;
597  }
598 
599  OptionalDiagnostic &operator<<(const APFloat &F) {
600  if (Diag) {
601  // FIXME: Force the precision of the source value down so we don't
602  // print digits which are usually useless (we don't really care here if
603  // we truncate a digit by accident in edge cases). Ideally,
604  // APFloat::toString would automatically print the shortest
605  // representation which rounds to the correct value, but it's a bit
606  // tricky to implement.
607  unsigned precision =
608  llvm::APFloat::semanticsPrecision(F.getSemantics());
609  precision = (precision * 59 + 195) / 196;
610  SmallVector<char, 32> Buffer;
611  F.toString(Buffer, precision);
612  *Diag << StringRef(Buffer.data(), Buffer.size());
613  }
614  return *this;
615  }
616 
617  OptionalDiagnostic &operator<<(const APFixedPoint &FX) {
618  if (Diag) {
619  SmallVector<char, 32> Buffer;
620  FX.toString(Buffer);
621  *Diag << StringRef(Buffer.data(), Buffer.size());
622  }
623  return *this;
624  }
625  };
626 
627  /// A cleanup, and a flag indicating whether it is lifetime-extended.
628  class Cleanup {
629  llvm::PointerIntPair<APValue*, 1, bool> Value;
630 
631  public:
632  Cleanup(APValue *Val, bool IsLifetimeExtended)
633  : Value(Val, IsLifetimeExtended) {}
634 
635  bool isLifetimeExtended() const { return Value.getInt(); }
636  void endLifetime() {
637  *Value.getPointer() = APValue();
638  }
639  };
640 
641  /// EvalInfo - This is a private struct used by the evaluator to capture
642  /// information about a subexpression as it is folded. It retains information
643  /// about the AST context, but also maintains information about the folded
644  /// expression.
645  ///
646  /// If an expression could be evaluated, it is still possible it is not a C
647  /// "integer constant expression" or constant expression. If not, this struct
648  /// captures information about how and why not.
649  ///
650  /// One bit of information passed *into* the request for constant folding
651  /// indicates whether the subexpression is "evaluated" or not according to C
652  /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
653  /// evaluate the expression regardless of what the RHS is, but C only allows
654  /// certain things in certain situations.
655  struct EvalInfo {
656  ASTContext &Ctx;
657 
658  /// EvalStatus - Contains information about the evaluation.
659  Expr::EvalStatus &EvalStatus;
660 
661  /// CurrentCall - The top of the constexpr call stack.
662  CallStackFrame *CurrentCall;
663 
664  /// CallStackDepth - The number of calls in the call stack right now.
665  unsigned CallStackDepth;
666 
667  /// NextCallIndex - The next call index to assign.
668  unsigned NextCallIndex;
669 
670  /// StepsLeft - The remaining number of evaluation steps we're permitted
671  /// to perform. This is essentially a limit for the number of statements
672  /// we will evaluate.
673  unsigned StepsLeft;
674 
675  /// BottomFrame - The frame in which evaluation started. This must be
676  /// initialized after CurrentCall and CallStackDepth.
677  CallStackFrame BottomFrame;
678 
679  /// A stack of values whose lifetimes end at the end of some surrounding
680  /// evaluation frame.
681  llvm::SmallVector<Cleanup, 16> CleanupStack;
682 
683  /// EvaluatingDecl - This is the declaration whose initializer is being
684  /// evaluated, if any.
685  APValue::LValueBase EvaluatingDecl;
686 
687  /// EvaluatingDeclValue - This is the value being constructed for the
688  /// declaration whose initializer is being evaluated, if any.
689  APValue *EvaluatingDeclValue;
690 
691  /// EvaluatingObject - Pair of the AST node that an lvalue represents and
692  /// the call index that that lvalue was allocated in.
693  typedef std::pair<APValue::LValueBase, std::pair<unsigned, unsigned>>
694  EvaluatingObject;
695 
696  /// EvaluatingConstructors - Set of objects that are currently being
697  /// constructed.
698  llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
699 
700  struct EvaluatingConstructorRAII {
701  EvalInfo &EI;
702  EvaluatingObject Object;
703  bool DidInsert;
704  EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
705  : EI(EI), Object(Object) {
706  DidInsert = EI.EvaluatingConstructors.insert(Object).second;
707  }
708  ~EvaluatingConstructorRAII() {
709  if (DidInsert) EI.EvaluatingConstructors.erase(Object);
710  }
711  };
712 
713  bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex,
714  unsigned Version) {
715  return EvaluatingConstructors.count(
716  EvaluatingObject(Decl, {CallIndex, Version}));
717  }
718 
719  /// The current array initialization index, if we're performing array
720  /// initialization.
721  uint64_t ArrayInitIndex = -1;
722 
723  /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
724  /// notes attached to it will also be stored, otherwise they will not be.
725  bool HasActiveDiagnostic;
726 
727  /// Have we emitted a diagnostic explaining why we couldn't constant
728  /// fold (not just why it's not strictly a constant expression)?
729  bool HasFoldFailureDiagnostic;
730 
731  /// Whether or not we're currently speculatively evaluating.
732  bool IsSpeculativelyEvaluating;
733 
734  /// Whether or not we're in a context where the front end requires a
735  /// constant value.
736  bool InConstantContext;
737 
738  enum EvaluationMode {
739  /// Evaluate as a constant expression. Stop if we find that the expression
740  /// is not a constant expression.
741  EM_ConstantExpression,
742 
743  /// Evaluate as a potential constant expression. Keep going if we hit a
744  /// construct that we can't evaluate yet (because we don't yet know the
745  /// value of something) but stop if we hit something that could never be
746  /// a constant expression.
747  EM_PotentialConstantExpression,
748 
749  /// Fold the expression to a constant. Stop if we hit a side-effect that
750  /// we can't model.
751  EM_ConstantFold,
752 
753  /// Evaluate the expression looking for integer overflow and similar
754  /// issues. Don't worry about side-effects, and try to visit all
755  /// subexpressions.
756  EM_EvaluateForOverflow,
757 
758  /// Evaluate in any way we know how. Don't worry about side-effects that
759  /// can't be modeled.
760  EM_IgnoreSideEffects,
761 
762  /// Evaluate as a constant expression. Stop if we find that the expression
763  /// is not a constant expression. Some expressions can be retried in the
764  /// optimizer if we don't constant fold them here, but in an unevaluated
765  /// context we try to fold them immediately since the optimizer never
766  /// gets a chance to look at it.
767  EM_ConstantExpressionUnevaluated,
768 
769  /// Evaluate as a potential constant expression. Keep going if we hit a
770  /// construct that we can't evaluate yet (because we don't yet know the
771  /// value of something) but stop if we hit something that could never be
772  /// a constant expression. Some expressions can be retried in the
773  /// optimizer if we don't constant fold them here, but in an unevaluated
774  /// context we try to fold them immediately since the optimizer never
775  /// gets a chance to look at it.
776  EM_PotentialConstantExpressionUnevaluated,
777  } EvalMode;
778 
779  /// Are we checking whether the expression is a potential constant
780  /// expression?
781  bool checkingPotentialConstantExpression() const {
782  return EvalMode == EM_PotentialConstantExpression ||
783  EvalMode == EM_PotentialConstantExpressionUnevaluated;
784  }
785 
786  /// Are we checking an expression for overflow?
787  // FIXME: We should check for any kind of undefined or suspicious behavior
788  // in such constructs, not just overflow.
789  bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
790 
791  EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
792  : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
793  CallStackDepth(0), NextCallIndex(1),
794  StepsLeft(getLangOpts().ConstexprStepLimit),
795  BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
796  EvaluatingDecl((const ValueDecl *)nullptr),
797  EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
798  HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
799  InConstantContext(false), EvalMode(Mode) {}
800 
801  void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
802  EvaluatingDecl = Base;
803  EvaluatingDeclValue = &Value;
804  EvaluatingConstructors.insert({Base, {0, 0}});
805  }
806 
807  const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
808 
809  bool CheckCallLimit(SourceLocation Loc) {
810  // Don't perform any constexpr calls (other than the call we're checking)
811  // when checking a potential constant expression.
812  if (checkingPotentialConstantExpression() && CallStackDepth > 1)
813  return false;
814  if (NextCallIndex == 0) {
815  // NextCallIndex has wrapped around.
816  FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
817  return false;
818  }
819  if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
820  return true;
821  FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
822  << getLangOpts().ConstexprCallDepth;
823  return false;
824  }
825 
826  CallStackFrame *getCallFrame(unsigned CallIndex) {
827  assert(CallIndex && "no call index in getCallFrame");
828  // We will eventually hit BottomFrame, which has Index 1, so Frame can't
829  // be null in this loop.
830  CallStackFrame *Frame = CurrentCall;
831  while (Frame->Index > CallIndex)
832  Frame = Frame->Caller;
833  return (Frame->Index == CallIndex) ? Frame : nullptr;
834  }
835 
836  bool nextStep(const Stmt *S) {
837  if (!StepsLeft) {
838  FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
839  return false;
840  }
841  --StepsLeft;
842  return true;
843  }
844 
845  private:
846  /// Add a diagnostic to the diagnostics list.
847  PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
848  PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
849  EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
850  return EvalStatus.Diag->back().second;
851  }
852 
853  /// Add notes containing a call stack to the current point of evaluation.
854  void addCallStack(unsigned Limit);
855 
856  private:
857  OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
858  unsigned ExtraNotes, bool IsCCEDiag) {
859 
860  if (EvalStatus.Diag) {
861  // If we have a prior diagnostic, it will be noting that the expression
862  // isn't a constant expression. This diagnostic is more important,
863  // unless we require this evaluation to produce a constant expression.
864  //
865  // FIXME: We might want to show both diagnostics to the user in
866  // EM_ConstantFold mode.
867  if (!EvalStatus.Diag->empty()) {
868  switch (EvalMode) {
869  case EM_ConstantFold:
870  case EM_IgnoreSideEffects:
871  case EM_EvaluateForOverflow:
872  if (!HasFoldFailureDiagnostic)
873  break;
874  // We've already failed to fold something. Keep that diagnostic.
875  LLVM_FALLTHROUGH;
876  case EM_ConstantExpression:
877  case EM_PotentialConstantExpression:
878  case EM_ConstantExpressionUnevaluated:
879  case EM_PotentialConstantExpressionUnevaluated:
880  HasActiveDiagnostic = false;
881  return OptionalDiagnostic();
882  }
883  }
884 
885  unsigned CallStackNotes = CallStackDepth - 1;
886  unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
887  if (Limit)
888  CallStackNotes = std::min(CallStackNotes, Limit + 1);
889  if (checkingPotentialConstantExpression())
890  CallStackNotes = 0;
891 
892  HasActiveDiagnostic = true;
893  HasFoldFailureDiagnostic = !IsCCEDiag;
894  EvalStatus.Diag->clear();
895  EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
896  addDiag(Loc, DiagId);
897  if (!checkingPotentialConstantExpression())
898  addCallStack(Limit);
899  return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
900  }
901  HasActiveDiagnostic = false;
902  return OptionalDiagnostic();
903  }
904  public:
905  // Diagnose that the evaluation could not be folded (FF => FoldFailure)
906  OptionalDiagnostic
907  FFDiag(SourceLocation Loc,
908  diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
909  unsigned ExtraNotes = 0) {
910  return Diag(Loc, DiagId, ExtraNotes, false);
911  }
912 
913  OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
914  = diag::note_invalid_subexpr_in_const_expr,
915  unsigned ExtraNotes = 0) {
916  if (EvalStatus.Diag)
917  return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
918  HasActiveDiagnostic = false;
919  return OptionalDiagnostic();
920  }
921 
922  /// Diagnose that the evaluation does not produce a C++11 core constant
923  /// expression.
924  ///
925  /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
926  /// EM_PotentialConstantExpression mode and we produce one of these.
927  OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
928  = diag::note_invalid_subexpr_in_const_expr,
929  unsigned ExtraNotes = 0) {
930  // Don't override a previous diagnostic. Don't bother collecting
931  // diagnostics if we're evaluating for overflow.
932  if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
933  HasActiveDiagnostic = false;
934  return OptionalDiagnostic();
935  }
936  return Diag(Loc, DiagId, ExtraNotes, true);
937  }
938  OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
939  = diag::note_invalid_subexpr_in_const_expr,
940  unsigned ExtraNotes = 0) {
941  return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
942  }
943  /// Add a note to a prior diagnostic.
944  OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
945  if (!HasActiveDiagnostic)
946  return OptionalDiagnostic();
947  return OptionalDiagnostic(&addDiag(Loc, DiagId));
948  }
949 
950  /// Add a stack of notes to a prior diagnostic.
951  void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
952  if (HasActiveDiagnostic) {
953  EvalStatus.Diag->insert(EvalStatus.Diag->end(),
954  Diags.begin(), Diags.end());
955  }
956  }
957 
958  /// Should we continue evaluation after encountering a side-effect that we
959  /// couldn't model?
960  bool keepEvaluatingAfterSideEffect() {
961  switch (EvalMode) {
962  case EM_PotentialConstantExpression:
963  case EM_PotentialConstantExpressionUnevaluated:
964  case EM_EvaluateForOverflow:
965  case EM_IgnoreSideEffects:
966  return true;
967 
968  case EM_ConstantExpression:
969  case EM_ConstantExpressionUnevaluated:
970  case EM_ConstantFold:
971  return false;
972  }
973  llvm_unreachable("Missed EvalMode case");
974  }
975 
976  /// Note that we have had a side-effect, and determine whether we should
977  /// keep evaluating.
978  bool noteSideEffect() {
979  EvalStatus.HasSideEffects = true;
980  return keepEvaluatingAfterSideEffect();
981  }
982 
983  /// Should we continue evaluation after encountering undefined behavior?
984  bool keepEvaluatingAfterUndefinedBehavior() {
985  switch (EvalMode) {
986  case EM_EvaluateForOverflow:
987  case EM_IgnoreSideEffects:
988  case EM_ConstantFold:
989  return true;
990 
991  case EM_PotentialConstantExpression:
992  case EM_PotentialConstantExpressionUnevaluated:
993  case EM_ConstantExpression:
994  case EM_ConstantExpressionUnevaluated:
995  return false;
996  }
997  llvm_unreachable("Missed EvalMode case");
998  }
999 
1000  /// Note that we hit something that was technically undefined behavior, but
1001  /// that we can evaluate past it (such as signed overflow or floating-point
1002  /// division by zero.)
1003  bool noteUndefinedBehavior() {
1004  EvalStatus.HasUndefinedBehavior = true;
1005  return keepEvaluatingAfterUndefinedBehavior();
1006  }
1007 
1008  /// Should we continue evaluation as much as possible after encountering a
1009  /// construct which can't be reduced to a value?
1010  bool keepEvaluatingAfterFailure() {
1011  if (!StepsLeft)
1012  return false;
1013 
1014  switch (EvalMode) {
1015  case EM_PotentialConstantExpression:
1016  case EM_PotentialConstantExpressionUnevaluated:
1017  case EM_EvaluateForOverflow:
1018  return true;
1019 
1020  case EM_ConstantExpression:
1021  case EM_ConstantExpressionUnevaluated:
1022  case EM_ConstantFold:
1023  case EM_IgnoreSideEffects:
1024  return false;
1025  }
1026  llvm_unreachable("Missed EvalMode case");
1027  }
1028 
1029  /// Notes that we failed to evaluate an expression that other expressions
1030  /// directly depend on, and determine if we should keep evaluating. This
1031  /// should only be called if we actually intend to keep evaluating.
1032  ///
1033  /// Call noteSideEffect() instead if we may be able to ignore the value that
1034  /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1035  ///
1036  /// (Foo(), 1) // use noteSideEffect
1037  /// (Foo() || true) // use noteSideEffect
1038  /// Foo() + 1 // use noteFailure
1039  LLVM_NODISCARD bool noteFailure() {
1040  // Failure when evaluating some expression often means there is some
1041  // subexpression whose evaluation was skipped. Therefore, (because we
1042  // don't track whether we skipped an expression when unwinding after an
1043  // evaluation failure) every evaluation failure that bubbles up from a
1044  // subexpression implies that a side-effect has potentially happened. We
1045  // skip setting the HasSideEffects flag to true until we decide to
1046  // continue evaluating after that point, which happens here.
1047  bool KeepGoing = keepEvaluatingAfterFailure();
1048  EvalStatus.HasSideEffects |= KeepGoing;
1049  return KeepGoing;
1050  }
1051 
1052  class ArrayInitLoopIndex {
1053  EvalInfo &Info;
1054  uint64_t OuterIndex;
1055 
1056  public:
1057  ArrayInitLoopIndex(EvalInfo &Info)
1058  : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1059  Info.ArrayInitIndex = 0;
1060  }
1061  ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1062 
1063  operator uint64_t&() { return Info.ArrayInitIndex; }
1064  };
1065  };
1066 
1067  /// Object used to treat all foldable expressions as constant expressions.
1068  struct FoldConstant {
1069  EvalInfo &Info;
1070  bool Enabled;
1071  bool HadNoPriorDiags;
1072  EvalInfo::EvaluationMode OldMode;
1073 
1074  explicit FoldConstant(EvalInfo &Info, bool Enabled)
1075  : Info(Info),
1076  Enabled(Enabled),
1077  HadNoPriorDiags(Info.EvalStatus.Diag &&
1078  Info.EvalStatus.Diag->empty() &&
1079  !Info.EvalStatus.HasSideEffects),
1080  OldMode(Info.EvalMode) {
1081  if (Enabled &&
1082  (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1083  Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
1084  Info.EvalMode = EvalInfo::EM_ConstantFold;
1085  }
1086  void keepDiagnostics() { Enabled = false; }
1087  ~FoldConstant() {
1088  if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1089  !Info.EvalStatus.HasSideEffects)
1090  Info.EvalStatus.Diag->clear();
1091  Info.EvalMode = OldMode;
1092  }
1093  };
1094 
1095  /// RAII object used to set the current evaluation mode to ignore
1096  /// side-effects.
1097  struct IgnoreSideEffectsRAII {
1098  EvalInfo &Info;
1099  EvalInfo::EvaluationMode OldMode;
1100  explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1101  : Info(Info), OldMode(Info.EvalMode) {
1102  if (!Info.checkingPotentialConstantExpression())
1103  Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1104  }
1105 
1106  ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1107  };
1108 
1109  /// RAII object used to optionally suppress diagnostics and side-effects from
1110  /// a speculative evaluation.
1111  class SpeculativeEvaluationRAII {
1112  EvalInfo *Info = nullptr;
1113  Expr::EvalStatus OldStatus;
1114  bool OldIsSpeculativelyEvaluating;
1115 
1116  void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1117  Info = Other.Info;
1118  OldStatus = Other.OldStatus;
1119  OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
1120  Other.Info = nullptr;
1121  }
1122 
1123  void maybeRestoreState() {
1124  if (!Info)
1125  return;
1126 
1127  Info->EvalStatus = OldStatus;
1128  Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
1129  }
1130 
1131  public:
1132  SpeculativeEvaluationRAII() = default;
1133 
1134  SpeculativeEvaluationRAII(
1135  EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1136  : Info(&Info), OldStatus(Info.EvalStatus),
1137  OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
1138  Info.EvalStatus.Diag = NewDiag;
1139  Info.IsSpeculativelyEvaluating = true;
1140  }
1141 
1142  SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1143  SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1144  moveFromAndCancel(std::move(Other));
1145  }
1146 
1147  SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1148  maybeRestoreState();
1149  moveFromAndCancel(std::move(Other));
1150  return *this;
1151  }
1152 
1153  ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1154  };
1155 
1156  /// RAII object wrapping a full-expression or block scope, and handling
1157  /// the ending of the lifetime of temporaries created within it.
1158  template<bool IsFullExpression>
1159  class ScopeRAII {
1160  EvalInfo &Info;
1161  unsigned OldStackSize;
1162  public:
1163  ScopeRAII(EvalInfo &Info)
1164  : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1165  // Push a new temporary version. This is needed to distinguish between
1166  // temporaries created in different iterations of a loop.
1167  Info.CurrentCall->pushTempVersion();
1168  }
1169  ~ScopeRAII() {
1170  // Body moved to a static method to encourage the compiler to inline away
1171  // instances of this class.
1172  cleanup(Info, OldStackSize);
1173  Info.CurrentCall->popTempVersion();
1174  }
1175  private:
1176  static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1177  unsigned NewEnd = OldStackSize;
1178  for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1179  I != N; ++I) {
1180  if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1181  // Full-expression cleanup of a lifetime-extended temporary: nothing
1182  // to do, just move this cleanup to the right place in the stack.
1183  std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1184  ++NewEnd;
1185  } else {
1186  // End the lifetime of the object.
1187  Info.CleanupStack[I].endLifetime();
1188  }
1189  }
1190  Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1191  Info.CleanupStack.end());
1192  }
1193  };
1194  typedef ScopeRAII<false> BlockScopeRAII;
1195  typedef ScopeRAII<true> FullExpressionRAII;
1196 }
1197 
1198 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1199  CheckSubobjectKind CSK) {
1200  if (Invalid)
1201  return false;
1202  if (isOnePastTheEnd()) {
1203  Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1204  << CSK;
1205  setInvalid();
1206  return false;
1207  }
1208  // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1209  // must actually be at least one array element; even a VLA cannot have a
1210  // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1211  return true;
1212 }
1213 
1214 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1215  const Expr *E) {
1216  Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1217  // Do not set the designator as invalid: we can represent this situation,
1218  // and correct handling of __builtin_object_size requires us to do so.
1219 }
1220 
1221 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1222  const Expr *E,
1223  const APSInt &N) {
1224  // If we're complaining, we must be able to statically determine the size of
1225  // the most derived array.
1226  if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1227  Info.CCEDiag(E, diag::note_constexpr_array_index)
1228  << N << /*array*/ 0
1229  << static_cast<unsigned>(getMostDerivedArraySize());
1230  else
1231  Info.CCEDiag(E, diag::note_constexpr_array_index)
1232  << N << /*non-array*/ 1;
1233  setInvalid();
1234 }
1235 
1236 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1237  const FunctionDecl *Callee, const LValue *This,
1238  APValue *Arguments)
1239  : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1240  Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1241  Info.CurrentCall = this;
1242  ++Info.CallStackDepth;
1243 }
1244 
1245 CallStackFrame::~CallStackFrame() {
1246  assert(Info.CurrentCall == this && "calls retired out of order");
1247  --Info.CallStackDepth;
1248  Info.CurrentCall = Caller;
1249 }
1250 
1251 APValue &CallStackFrame::createTemporary(const void *Key,
1252  bool IsLifetimeExtended) {
1253  unsigned Version = Info.CurrentCall->getTempVersion();
1254  APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1255  assert(Result.isUninit() && "temporary created multiple times");
1256  Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1257  return Result;
1258 }
1259 
1260 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
1261 
1262 void EvalInfo::addCallStack(unsigned Limit) {
1263  // Determine which calls to skip, if any.
1264  unsigned ActiveCalls = CallStackDepth - 1;
1265  unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1266  if (Limit && Limit < ActiveCalls) {
1267  SkipStart = Limit / 2 + Limit % 2;
1268  SkipEnd = ActiveCalls - Limit / 2;
1269  }
1270 
1271  // Walk the call stack and add the diagnostics.
1272  unsigned CallIdx = 0;
1273  for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1274  Frame = Frame->Caller, ++CallIdx) {
1275  // Skip this call?
1276  if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1277  if (CallIdx == SkipStart) {
1278  // Note that we're skipping calls.
1279  addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1280  << unsigned(ActiveCalls - Limit);
1281  }
1282  continue;
1283  }
1284 
1285  // Use a different note for an inheriting constructor, because from the
1286  // user's perspective it's not really a function at all.
1287  if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1288  if (CD->isInheritingConstructor()) {
1289  addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1290  << CD->getParent();
1291  continue;
1292  }
1293  }
1294 
1295  SmallVector<char, 128> Buffer;
1296  llvm::raw_svector_ostream Out(Buffer);
1297  describeCall(Frame, Out);
1298  addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1299  }
1300 }
1301 
1302 /// Kinds of access we can perform on an object, for diagnostics.
1308 };
1309 
1310 namespace {
1311  struct ComplexValue {
1312  private:
1313  bool IsInt;
1314 
1315  public:
1316  APSInt IntReal, IntImag;
1317  APFloat FloatReal, FloatImag;
1318 
1319  ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1320 
1321  void makeComplexFloat() { IsInt = false; }
1322  bool isComplexFloat() const { return !IsInt; }
1323  APFloat &getComplexFloatReal() { return FloatReal; }
1324  APFloat &getComplexFloatImag() { return FloatImag; }
1325 
1326  void makeComplexInt() { IsInt = true; }
1327  bool isComplexInt() const { return IsInt; }
1328  APSInt &getComplexIntReal() { return IntReal; }
1329  APSInt &getComplexIntImag() { return IntImag; }
1330 
1331  void moveInto(APValue &v) const {
1332  if (isComplexFloat())
1333  v = APValue(FloatReal, FloatImag);
1334  else
1335  v = APValue(IntReal, IntImag);
1336  }
1337  void setFrom(const APValue &v) {
1338  assert(v.isComplexFloat() || v.isComplexInt());
1339  if (v.isComplexFloat()) {
1340  makeComplexFloat();
1341  FloatReal = v.getComplexFloatReal();
1342  FloatImag = v.getComplexFloatImag();
1343  } else {
1344  makeComplexInt();
1345  IntReal = v.getComplexIntReal();
1346  IntImag = v.getComplexIntImag();
1347  }
1348  }
1349  };
1350 
1351  struct LValue {
1352  APValue::LValueBase Base;
1353  CharUnits Offset;
1354  SubobjectDesignator Designator;
1355  bool IsNullPtr : 1;
1356  bool InvalidBase : 1;
1357 
1358  const APValue::LValueBase getLValueBase() const { return Base; }
1359  CharUnits &getLValueOffset() { return Offset; }
1360  const CharUnits &getLValueOffset() const { return Offset; }
1361  SubobjectDesignator &getLValueDesignator() { return Designator; }
1362  const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1363  bool isNullPointer() const { return IsNullPtr;}
1364 
1365  unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1366  unsigned getLValueVersion() const { return Base.getVersion(); }
1367 
1368  void moveInto(APValue &V) const {
1369  if (Designator.Invalid)
1370  V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1371  else {
1372  assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1373  V = APValue(Base, Offset, Designator.Entries,
1374  Designator.IsOnePastTheEnd, IsNullPtr);
1375  }
1376  }
1377  void setFrom(ASTContext &Ctx, const APValue &V) {
1378  assert(V.isLValue() && "Setting LValue from a non-LValue?");
1379  Base = V.getLValueBase();
1380  Offset = V.getLValueOffset();
1381  InvalidBase = false;
1382  Designator = SubobjectDesignator(Ctx, V);
1383  IsNullPtr = V.isNullPointer();
1384  }
1385 
1386  void set(APValue::LValueBase B, bool BInvalid = false) {
1387 #ifndef NDEBUG
1388  // We only allow a few types of invalid bases. Enforce that here.
1389  if (BInvalid) {
1390  const auto *E = B.get<const Expr *>();
1391  assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1392  "Unexpected type of invalid base");
1393  }
1394 #endif
1395 
1396  Base = B;
1397  Offset = CharUnits::fromQuantity(0);
1398  InvalidBase = BInvalid;
1399  Designator = SubobjectDesignator(getType(B));
1400  IsNullPtr = false;
1401  }
1402 
1403  void setNull(QualType PointerTy, uint64_t TargetVal) {
1404  Base = (Expr *)nullptr;
1405  Offset = CharUnits::fromQuantity(TargetVal);
1406  InvalidBase = false;
1407  Designator = SubobjectDesignator(PointerTy->getPointeeType());
1408  IsNullPtr = true;
1409  }
1410 
1411  void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1412  set(B, true);
1413  }
1414 
1415  private:
1416  // Check that this LValue is not based on a null pointer. If it is, produce
1417  // a diagnostic and mark the designator as invalid.
1418  template <typename GenDiagType>
1419  bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1420  if (Designator.Invalid)
1421  return false;
1422  if (IsNullPtr) {
1423  GenDiag();
1424  Designator.setInvalid();
1425  return false;
1426  }
1427  return true;
1428  }
1429 
1430  public:
1431  bool checkNullPointer(EvalInfo &Info, const Expr *E,
1432  CheckSubobjectKind CSK) {
1433  return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1434  Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1435  });
1436  }
1437 
1438  bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1439  AccessKinds AK) {
1440  return checkNullPointerDiagnosingWith([&Info, E, AK] {
1441  Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1442  });
1443  }
1444 
1445  // Check this LValue refers to an object. If not, set the designator to be
1446  // invalid and emit a diagnostic.
1447  bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1448  return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1449  Designator.checkSubobject(Info, E, CSK);
1450  }
1451 
1452  void addDecl(EvalInfo &Info, const Expr *E,
1453  const Decl *D, bool Virtual = false) {
1454  if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1455  Designator.addDeclUnchecked(D, Virtual);
1456  }
1457  void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1458  if (!Designator.Entries.empty()) {
1459  Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1460  Designator.setInvalid();
1461  return;
1462  }
1463  if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1464  assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1465  Designator.FirstEntryIsAnUnsizedArray = true;
1466  Designator.addUnsizedArrayUnchecked(ElemTy);
1467  }
1468  }
1469  void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1470  if (checkSubobject(Info, E, CSK_ArrayToPointer))
1471  Designator.addArrayUnchecked(CAT);
1472  }
1473  void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1474  if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1475  Designator.addComplexUnchecked(EltTy, Imag);
1476  }
1477  void clearIsNullPointer() {
1478  IsNullPtr = false;
1479  }
1480  void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1481  const APSInt &Index, CharUnits ElementSize) {
1482  // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1483  // but we're not required to diagnose it and it's valid in C++.)
1484  if (!Index)
1485  return;
1486 
1487  // Compute the new offset in the appropriate width, wrapping at 64 bits.
1488  // FIXME: When compiling for a 32-bit target, we should use 32-bit
1489  // offsets.
1490  uint64_t Offset64 = Offset.getQuantity();
1491  uint64_t ElemSize64 = ElementSize.getQuantity();
1492  uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1493  Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1494 
1495  if (checkNullPointer(Info, E, CSK_ArrayIndex))
1496  Designator.adjustIndex(Info, E, Index);
1497  clearIsNullPointer();
1498  }
1499  void adjustOffset(CharUnits N) {
1500  Offset += N;
1501  if (N.getQuantity())
1502  clearIsNullPointer();
1503  }
1504  };
1505 
1506  struct MemberPtr {
1507  MemberPtr() {}
1508  explicit MemberPtr(const ValueDecl *Decl) :
1509  DeclAndIsDerivedMember(Decl, false), Path() {}
1510 
1511  /// The member or (direct or indirect) field referred to by this member
1512  /// pointer, or 0 if this is a null member pointer.
1513  const ValueDecl *getDecl() const {
1514  return DeclAndIsDerivedMember.getPointer();
1515  }
1516  /// Is this actually a member of some type derived from the relevant class?
1517  bool isDerivedMember() const {
1518  return DeclAndIsDerivedMember.getInt();
1519  }
1520  /// Get the class which the declaration actually lives in.
1521  const CXXRecordDecl *getContainingRecord() const {
1522  return cast<CXXRecordDecl>(
1523  DeclAndIsDerivedMember.getPointer()->getDeclContext());
1524  }
1525 
1526  void moveInto(APValue &V) const {
1527  V = APValue(getDecl(), isDerivedMember(), Path);
1528  }
1529  void setFrom(const APValue &V) {
1530  assert(V.isMemberPointer());
1531  DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1532  DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1533  Path.clear();
1535  Path.insert(Path.end(), P.begin(), P.end());
1536  }
1537 
1538  /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1539  /// whether the member is a member of some class derived from the class type
1540  /// of the member pointer.
1541  llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1542  /// Path - The path of base/derived classes from the member declaration's
1543  /// class (exclusive) to the class type of the member pointer (inclusive).
1545 
1546  /// Perform a cast towards the class of the Decl (either up or down the
1547  /// hierarchy).
1548  bool castBack(const CXXRecordDecl *Class) {
1549  assert(!Path.empty());
1550  const CXXRecordDecl *Expected;
1551  if (Path.size() >= 2)
1552  Expected = Path[Path.size() - 2];
1553  else
1554  Expected = getContainingRecord();
1555  if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1556  // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1557  // if B does not contain the original member and is not a base or
1558  // derived class of the class containing the original member, the result
1559  // of the cast is undefined.
1560  // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1561  // (D::*). We consider that to be a language defect.
1562  return false;
1563  }
1564  Path.pop_back();
1565  return true;
1566  }
1567  /// Perform a base-to-derived member pointer cast.
1568  bool castToDerived(const CXXRecordDecl *Derived) {
1569  if (!getDecl())
1570  return true;
1571  if (!isDerivedMember()) {
1572  Path.push_back(Derived);
1573  return true;
1574  }
1575  if (!castBack(Derived))
1576  return false;
1577  if (Path.empty())
1578  DeclAndIsDerivedMember.setInt(false);
1579  return true;
1580  }
1581  /// Perform a derived-to-base member pointer cast.
1582  bool castToBase(const CXXRecordDecl *Base) {
1583  if (!getDecl())
1584  return true;
1585  if (Path.empty())
1586  DeclAndIsDerivedMember.setInt(true);
1587  if (isDerivedMember()) {
1588  Path.push_back(Base);
1589  return true;
1590  }
1591  return castBack(Base);
1592  }
1593  };
1594 
1595  /// Compare two member pointers, which are assumed to be of the same type.
1596  static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1597  if (!LHS.getDecl() || !RHS.getDecl())
1598  return !LHS.getDecl() && !RHS.getDecl();
1599  if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1600  return false;
1601  return LHS.Path == RHS.Path;
1602  }
1603 }
1604 
1605 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1606 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1607  const LValue &This, const Expr *E,
1608  bool AllowNonLiteralTypes = false);
1609 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1610  bool InvalidBaseOK = false);
1611 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1612  bool InvalidBaseOK = false);
1613 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1614  EvalInfo &Info);
1615 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1616 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1617 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1618  EvalInfo &Info);
1619 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1620 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1621 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1622  EvalInfo &Info);
1623 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1624 
1625 /// Evaluate an integer or fixed point expression into an APResult.
1626 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1627  EvalInfo &Info);
1628 
1629 /// Evaluate only a fixed point expression into an APResult.
1630 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1631  EvalInfo &Info);
1632 
1633 //===----------------------------------------------------------------------===//
1634 // Misc utilities
1635 //===----------------------------------------------------------------------===//
1636 
1637 /// A helper function to create a temporary and set an LValue.
1638 template <class KeyTy>
1639 static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1640  LValue &LV, CallStackFrame &Frame) {
1641  LV.set({Key, Frame.Info.CurrentCall->Index,
1642  Frame.Info.CurrentCall->getTempVersion()});
1643  return Frame.createTemporary(Key, IsLifetimeExtended);
1644 }
1645 
1646 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1647 /// preserving its value (by extending by up to one bit as needed).
1648 static void negateAsSigned(APSInt &Int) {
1649  if (Int.isUnsigned() || Int.isMinSignedValue()) {
1650  Int = Int.extend(Int.getBitWidth() + 1);
1651  Int.setIsSigned(true);
1652  }
1653  Int = -Int;
1654 }
1655 
1656 /// Produce a string describing the given constexpr call.
1657 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1658  unsigned ArgIndex = 0;
1659  bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1660  !isa<CXXConstructorDecl>(Frame->Callee) &&
1661  cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1662 
1663  if (!IsMemberCall)
1664  Out << *Frame->Callee << '(';
1665 
1666  if (Frame->This && IsMemberCall) {
1667  APValue Val;
1668  Frame->This->moveInto(Val);
1669  Val.printPretty(Out, Frame->Info.Ctx,
1670  Frame->This->Designator.MostDerivedType);
1671  // FIXME: Add parens around Val if needed.
1672  Out << "->" << *Frame->Callee << '(';
1673  IsMemberCall = false;
1674  }
1675 
1676  for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1677  E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1678  if (ArgIndex > (unsigned)IsMemberCall)
1679  Out << ", ";
1680 
1681  const ParmVarDecl *Param = *I;
1682  const APValue &Arg = Frame->Arguments[ArgIndex];
1683  Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1684 
1685  if (ArgIndex == 0 && IsMemberCall)
1686  Out << "->" << *Frame->Callee << '(';
1687  }
1688 
1689  Out << ')';
1690 }
1691 
1692 /// Evaluate an expression to see if it had side-effects, and discard its
1693 /// result.
1694 /// \return \c true if the caller should keep evaluating.
1695 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1696  APValue Scratch;
1697  if (!Evaluate(Scratch, Info, E))
1698  // We don't need the value, but we might have skipped a side effect here.
1699  return Info.noteSideEffect();
1700  return true;
1701 }
1702 
1703 /// Should this call expression be treated as a string literal?
1704 static bool IsStringLiteralCall(const CallExpr *E) {
1705  unsigned Builtin = E->getBuiltinCallee();
1706  return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1707  Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1708 }
1709 
1711  // C++11 [expr.const]p3 An address constant expression is a prvalue core
1712  // constant expression of pointer type that evaluates to...
1713 
1714  // ... a null pointer value, or a prvalue core constant expression of type
1715  // std::nullptr_t.
1716  if (!B) return true;
1717 
1718  if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1719  // ... the address of an object with static storage duration,
1720  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1721  return VD->hasGlobalStorage();
1722  // ... the address of a function,
1723  return isa<FunctionDecl>(D);
1724  }
1725 
1726  const Expr *E = B.get<const Expr*>();
1727  switch (E->getStmtClass()) {
1728  default:
1729  return false;
1730  case Expr::CompoundLiteralExprClass: {
1731  const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1732  return CLE->isFileScope() && CLE->isLValue();
1733  }
1734  case Expr::MaterializeTemporaryExprClass:
1735  // A materialized temporary might have been lifetime-extended to static
1736  // storage duration.
1737  return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1738  // A string literal has static storage duration.
1739  case Expr::StringLiteralClass:
1740  case Expr::PredefinedExprClass:
1741  case Expr::ObjCStringLiteralClass:
1742  case Expr::ObjCEncodeExprClass:
1743  case Expr::CXXTypeidExprClass:
1744  case Expr::CXXUuidofExprClass:
1745  return true;
1746  case Expr::CallExprClass:
1747  return IsStringLiteralCall(cast<CallExpr>(E));
1748  // For GCC compatibility, &&label has static storage duration.
1749  case Expr::AddrLabelExprClass:
1750  return true;
1751  // A Block literal expression may be used as the initialization value for
1752  // Block variables at global or local static scope.
1753  case Expr::BlockExprClass:
1754  return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1755  case Expr::ImplicitValueInitExprClass:
1756  // FIXME:
1757  // We can never form an lvalue with an implicit value initialization as its
1758  // base through expression evaluation, so these only appear in one case: the
1759  // implicit variable declaration we invent when checking whether a constexpr
1760  // constructor can produce a constant expression. We must assume that such
1761  // an expression might be a global lvalue.
1762  return true;
1763  }
1764 }
1765 
1766 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1767  return LVal.Base.dyn_cast<const ValueDecl*>();
1768 }
1769 
1770 static bool IsLiteralLValue(const LValue &Value) {
1771  if (Value.getLValueCallIndex())
1772  return false;
1773  const Expr *E = Value.Base.dyn_cast<const Expr*>();
1774  return E && !isa<MaterializeTemporaryExpr>(E);
1775 }
1776 
1777 static bool IsWeakLValue(const LValue &Value) {
1778  const ValueDecl *Decl = GetLValueBaseDecl(Value);
1779  return Decl && Decl->isWeak();
1780 }
1781 
1782 static bool isZeroSized(const LValue &Value) {
1783  const ValueDecl *Decl = GetLValueBaseDecl(Value);
1784  if (Decl && isa<VarDecl>(Decl)) {
1785  QualType Ty = Decl->getType();
1786  if (Ty->isArrayType())
1787  return Ty->isIncompleteType() ||
1788  Decl->getASTContext().getTypeSize(Ty) == 0;
1789  }
1790  return false;
1791 }
1792 
1793 static bool HasSameBase(const LValue &A, const LValue &B) {
1794  if (!A.getLValueBase())
1795  return !B.getLValueBase();
1796  if (!B.getLValueBase())
1797  return false;
1798 
1799  if (A.getLValueBase().getOpaqueValue() !=
1800  B.getLValueBase().getOpaqueValue()) {
1801  const Decl *ADecl = GetLValueBaseDecl(A);
1802  if (!ADecl)
1803  return false;
1804  const Decl *BDecl = GetLValueBaseDecl(B);
1805  if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1806  return false;
1807  }
1808 
1809  return IsGlobalLValue(A.getLValueBase()) ||
1810  (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1811  A.getLValueVersion() == B.getLValueVersion());
1812 }
1813 
1814 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1815  assert(Base && "no location for a null lvalue");
1816  const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1817  if (VD)
1818  Info.Note(VD->getLocation(), diag::note_declared_at);
1819  else
1820  Info.Note(Base.get<const Expr*>()->getExprLoc(),
1821  diag::note_constexpr_temporary_here);
1822 }
1823 
1824 /// Check that this reference or pointer core constant expression is a valid
1825 /// value for an address or reference constant expression. Return true if we
1826 /// can fold this expression, whether or not it's a constant expression.
1827 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1828  QualType Type, const LValue &LVal,
1829  Expr::ConstExprUsage Usage) {
1830  bool IsReferenceType = Type->isReferenceType();
1831 
1832  APValue::LValueBase Base = LVal.getLValueBase();
1833  const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1834 
1835  // Check that the object is a global. Note that the fake 'this' object we
1836  // manufacture when checking potential constant expressions is conservatively
1837  // assumed to be global here.
1838  if (!IsGlobalLValue(Base)) {
1839  if (Info.getLangOpts().CPlusPlus11) {
1840  const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1841  Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
1842  << IsReferenceType << !Designator.Entries.empty()
1843  << !!VD << VD;
1844  NoteLValueLocation(Info, Base);
1845  } else {
1846  Info.FFDiag(Loc);
1847  }
1848  // Don't allow references to temporaries to escape.
1849  return false;
1850  }
1851  assert((Info.checkingPotentialConstantExpression() ||
1852  LVal.getLValueCallIndex() == 0) &&
1853  "have call index for global lvalue");
1854 
1855  if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1856  if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1857  // Check if this is a thread-local variable.
1858  if (Var->getTLSKind())
1859  return false;
1860 
1861  // A dllimport variable never acts like a constant.
1862  if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
1863  return false;
1864  }
1865  if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1866  // __declspec(dllimport) must be handled very carefully:
1867  // We must never initialize an expression with the thunk in C++.
1868  // Doing otherwise would allow the same id-expression to yield
1869  // different addresses for the same function in different translation
1870  // units. However, this means that we must dynamically initialize the
1871  // expression with the contents of the import address table at runtime.
1872  //
1873  // The C language has no notion of ODR; furthermore, it has no notion of
1874  // dynamic initialization. This means that we are permitted to
1875  // perform initialization with the address of the thunk.
1876  if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1877  FD->hasAttr<DLLImportAttr>())
1878  return false;
1879  }
1880  }
1881 
1882  // Allow address constant expressions to be past-the-end pointers. This is
1883  // an extension: the standard requires them to point to an object.
1884  if (!IsReferenceType)
1885  return true;
1886 
1887  // A reference constant expression must refer to an object.
1888  if (!Base) {
1889  // FIXME: diagnostic
1890  Info.CCEDiag(Loc);
1891  return true;
1892  }
1893 
1894  // Does this refer one past the end of some object?
1895  if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1896  const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1897  Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
1898  << !Designator.Entries.empty() << !!VD << VD;
1899  NoteLValueLocation(Info, Base);
1900  }
1901 
1902  return true;
1903 }
1904 
1905 /// Member pointers are constant expressions unless they point to a
1906 /// non-virtual dllimport member function.
1907 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1908  SourceLocation Loc,
1909  QualType Type,
1910  const APValue &Value,
1911  Expr::ConstExprUsage Usage) {
1912  const ValueDecl *Member = Value.getMemberPointerDecl();
1913  const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1914  if (!FD)
1915  return true;
1916  return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
1917  !FD->hasAttr<DLLImportAttr>();
1918 }
1919 
1920 /// Check that this core constant expression is of literal type, and if not,
1921 /// produce an appropriate diagnostic.
1922 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1923  const LValue *This = nullptr) {
1924  if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1925  return true;
1926 
1927  // C++1y: A constant initializer for an object o [...] may also invoke
1928  // constexpr constructors for o and its subobjects even if those objects
1929  // are of non-literal class types.
1930  //
1931  // C++11 missed this detail for aggregates, so classes like this:
1932  // struct foo_t { union { int i; volatile int j; } u; };
1933  // are not (obviously) initializable like so:
1934  // __attribute__((__require_constant_initialization__))
1935  // static const foo_t x = {{0}};
1936  // because "i" is a subobject with non-literal initialization (due to the
1937  // volatile member of the union). See:
1938  // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1939  // Therefore, we use the C++1y behavior.
1940  if (This && Info.EvaluatingDecl == This->getLValueBase())
1941  return true;
1942 
1943  // Prvalue constant expressions must be of literal types.
1944  if (Info.getLangOpts().CPlusPlus11)
1945  Info.FFDiag(E, diag::note_constexpr_nonliteral)
1946  << E->getType();
1947  else
1948  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1949  return false;
1950 }
1951 
1952 /// Check that this core constant expression value is a valid value for a
1953 /// constant expression. If not, report an appropriate diagnostic. Does not
1954 /// check that the expression is of literal type.
1955 static bool
1956 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
1957  const APValue &Value,
1959  if (Value.isUninit()) {
1960  Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
1961  << true << Type;
1962  return false;
1963  }
1964 
1965  // We allow _Atomic(T) to be initialized from anything that T can be
1966  // initialized from.
1967  if (const AtomicType *AT = Type->getAs<AtomicType>())
1968  Type = AT->getValueType();
1969 
1970  // Core issue 1454: For a literal constant expression of array or class type,
1971  // each subobject of its value shall have been initialized by a constant
1972  // expression.
1973  if (Value.isArray()) {
1974  QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1975  for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1976  if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1977  Value.getArrayInitializedElt(I), Usage))
1978  return false;
1979  }
1980  if (!Value.hasArrayFiller())
1981  return true;
1982  return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
1983  Usage);
1984  }
1985  if (Value.isUnion() && Value.getUnionField()) {
1986  return CheckConstantExpression(Info, DiagLoc,
1987  Value.getUnionField()->getType(),
1988  Value.getUnionValue(), Usage);
1989  }
1990  if (Value.isStruct()) {
1991  RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1992  if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1993  unsigned BaseIndex = 0;
1994  for (const CXXBaseSpecifier &BS : CD->bases()) {
1995  if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
1996  Value.getStructBase(BaseIndex), Usage))
1997  return false;
1998  ++BaseIndex;
1999  }
2000  }
2001  for (const auto *I : RD->fields()) {
2002  if (I->isUnnamedBitfield())
2003  continue;
2004 
2005  if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
2006  Value.getStructField(I->getFieldIndex()),
2007  Usage))
2008  return false;
2009  }
2010  }
2011 
2012  if (Value.isLValue()) {
2013  LValue LVal;
2014  LVal.setFrom(Info.Ctx, Value);
2015  return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
2016  }
2017 
2018  if (Value.isMemberPointer())
2019  return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
2020 
2021  // Everything else is fine.
2022  return true;
2023 }
2024 
2025 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2026  // A null base expression indicates a null pointer. These are always
2027  // evaluatable, and they are false unless the offset is zero.
2028  if (!Value.getLValueBase()) {
2029  Result = !Value.getLValueOffset().isZero();
2030  return true;
2031  }
2032 
2033  // We have a non-null base. These are generally known to be true, but if it's
2034  // a weak declaration it can be null at runtime.
2035  Result = true;
2036  const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2037  return !Decl || !Decl->isWeak();
2038 }
2039 
2040 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2041  switch (Val.getKind()) {
2043  return false;
2044  case APValue::Int:
2045  Result = Val.getInt().getBoolValue();
2046  return true;
2047  case APValue::FixedPoint:
2048  Result = Val.getFixedPoint().getBoolValue();
2049  return true;
2050  case APValue::Float:
2051  Result = !Val.getFloat().isZero();
2052  return true;
2053  case APValue::ComplexInt:
2054  Result = Val.getComplexIntReal().getBoolValue() ||
2055  Val.getComplexIntImag().getBoolValue();
2056  return true;
2057  case APValue::ComplexFloat:
2058  Result = !Val.getComplexFloatReal().isZero() ||
2059  !Val.getComplexFloatImag().isZero();
2060  return true;
2061  case APValue::LValue:
2062  return EvalPointerValueAsBool(Val, Result);
2064  Result = Val.getMemberPointerDecl();
2065  return true;
2066  case APValue::Vector:
2067  case APValue::Array:
2068  case APValue::Struct:
2069  case APValue::Union:
2071  return false;
2072  }
2073 
2074  llvm_unreachable("unknown APValue kind");
2075 }
2076 
2077 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2078  EvalInfo &Info) {
2079  assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2080  APValue Val;
2081  if (!Evaluate(Val, Info, E))
2082  return false;
2083  return HandleConversionToBool(Val, Result);
2084 }
2085 
2086 template<typename T>
2087 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2088  const T &SrcValue, QualType DestType) {
2089  Info.CCEDiag(E, diag::note_constexpr_overflow)
2090  << SrcValue << DestType;
2091  return Info.noteUndefinedBehavior();
2092 }
2093 
2094 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2095  QualType SrcType, const APFloat &Value,
2096  QualType DestType, APSInt &Result) {
2097  unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2098  // Determine whether we are converting to unsigned or signed.
2099  bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2100 
2101  Result = APSInt(DestWidth, !DestSigned);
2102  bool ignored;
2103  if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2104  & APFloat::opInvalidOp)
2105  return HandleOverflow(Info, E, Value, DestType);
2106  return true;
2107 }
2108 
2109 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2110  QualType SrcType, QualType DestType,
2111  APFloat &Result) {
2112  APFloat Value = Result;
2113  bool ignored;
2114  if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2115  APFloat::rmNearestTiesToEven, &ignored)
2116  & APFloat::opOverflow)
2117  return HandleOverflow(Info, E, Value, DestType);
2118  return true;
2119 }
2120 
2121 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2122  QualType DestType, QualType SrcType,
2123  const APSInt &Value) {
2124  unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2125  // Figure out if this is a truncate, extend or noop cast.
2126  // If the input is signed, do a sign extend, noop, or truncate.
2127  APSInt Result = Value.extOrTrunc(DestWidth);
2128  Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2129  if (DestType->isBooleanType())
2130  Result = Value.getBoolValue();
2131  return Result;
2132 }
2133 
2134 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2135  QualType SrcType, const APSInt &Value,
2136  QualType DestType, APFloat &Result) {
2137  Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2138  if (Result.convertFromAPInt(Value, Value.isSigned(),
2139  APFloat::rmNearestTiesToEven)
2140  & APFloat::opOverflow)
2141  return HandleOverflow(Info, E, Value, DestType);
2142  return true;
2143 }
2144 
2145 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2146  APValue &Value, const FieldDecl *FD) {
2147  assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2148 
2149  if (!Value.isInt()) {
2150  // Trying to store a pointer-cast-to-integer into a bitfield.
2151  // FIXME: In this case, we should provide the diagnostic for casting
2152  // a pointer to an integer.
2153  assert(Value.isLValue() && "integral value neither int nor lvalue?");
2154  Info.FFDiag(E);
2155  return false;
2156  }
2157 
2158  APSInt &Int = Value.getInt();
2159  unsigned OldBitWidth = Int.getBitWidth();
2160  unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2161  if (NewBitWidth < OldBitWidth)
2162  Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2163  return true;
2164 }
2165 
2166 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2167  llvm::APInt &Res) {
2168  APValue SVal;
2169  if (!Evaluate(SVal, Info, E))
2170  return false;
2171  if (SVal.isInt()) {
2172  Res = SVal.getInt();
2173  return true;
2174  }
2175  if (SVal.isFloat()) {
2176  Res = SVal.getFloat().bitcastToAPInt();
2177  return true;
2178  }
2179  if (SVal.isVector()) {
2180  QualType VecTy = E->getType();
2181  unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2182  QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2183  unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2184  bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2185  Res = llvm::APInt::getNullValue(VecSize);
2186  for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2187  APValue &Elt = SVal.getVectorElt(i);
2188  llvm::APInt EltAsInt;
2189  if (Elt.isInt()) {
2190  EltAsInt = Elt.getInt();
2191  } else if (Elt.isFloat()) {
2192  EltAsInt = Elt.getFloat().bitcastToAPInt();
2193  } else {
2194  // Don't try to handle vectors of anything other than int or float
2195  // (not sure if it's possible to hit this case).
2196  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2197  return false;
2198  }
2199  unsigned BaseEltSize = EltAsInt.getBitWidth();
2200  if (BigEndian)
2201  Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2202  else
2203  Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2204  }
2205  return true;
2206  }
2207  // Give up if the input isn't an int, float, or vector. For example, we
2208  // reject "(v4i16)(intptr_t)&a".
2209  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2210  return false;
2211 }
2212 
2213 /// Perform the given integer operation, which is known to need at most BitWidth
2214 /// bits, and check for overflow in the original type (if that type was not an
2215 /// unsigned type).
2216 template<typename Operation>
2217 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2218  const APSInt &LHS, const APSInt &RHS,
2219  unsigned BitWidth, Operation Op,
2220  APSInt &Result) {
2221  if (LHS.isUnsigned()) {
2222  Result = Op(LHS, RHS);
2223  return true;
2224  }
2225 
2226  APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2227  Result = Value.trunc(LHS.getBitWidth());
2228  if (Result.extend(BitWidth) != Value) {
2229  if (Info.checkingForOverflow())
2230  Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2231  diag::warn_integer_constant_overflow)
2232  << Result.toString(10) << E->getType();
2233  else
2234  return HandleOverflow(Info, E, Value, E->getType());
2235  }
2236  return true;
2237 }
2238 
2239 /// Perform the given binary integer operation.
2240 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2241  BinaryOperatorKind Opcode, APSInt RHS,
2242  APSInt &Result) {
2243  switch (Opcode) {
2244  default:
2245  Info.FFDiag(E);
2246  return false;
2247  case BO_Mul:
2248  return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2249  std::multiplies<APSInt>(), Result);
2250  case BO_Add:
2251  return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2252  std::plus<APSInt>(), Result);
2253  case BO_Sub:
2254  return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2255  std::minus<APSInt>(), Result);
2256  case BO_And: Result = LHS & RHS; return true;
2257  case BO_Xor: Result = LHS ^ RHS; return true;
2258  case BO_Or: Result = LHS | RHS; return true;
2259  case BO_Div:
2260  case BO_Rem:
2261  if (RHS == 0) {
2262  Info.FFDiag(E, diag::note_expr_divide_by_zero);
2263  return false;
2264  }
2265  Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2266  // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2267  // this operation and gives the two's complement result.
2268  if (RHS.isNegative() && RHS.isAllOnesValue() &&
2269  LHS.isSigned() && LHS.isMinSignedValue())
2270  return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2271  E->getType());
2272  return true;
2273  case BO_Shl: {
2274  if (Info.getLangOpts().OpenCL)
2275  // OpenCL 6.3j: shift values are effectively % word size of LHS.
2276  RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2277  static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2278  RHS.isUnsigned());
2279  else if (RHS.isSigned() && RHS.isNegative()) {
2280  // During constant-folding, a negative shift is an opposite shift. Such
2281  // a shift is not a constant expression.
2282  Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2283  RHS = -RHS;
2284  goto shift_right;
2285  }
2286  shift_left:
2287  // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2288  // the shifted type.
2289  unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2290  if (SA != RHS) {
2291  Info.CCEDiag(E, diag::note_constexpr_large_shift)
2292  << RHS << E->getType() << LHS.getBitWidth();
2293  } else if (LHS.isSigned()) {
2294  // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2295  // operand, and must not overflow the corresponding unsigned type.
2296  if (LHS.isNegative())
2297  Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2298  else if (LHS.countLeadingZeros() < SA)
2299  Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2300  }
2301  Result = LHS << SA;
2302  return true;
2303  }
2304  case BO_Shr: {
2305  if (Info.getLangOpts().OpenCL)
2306  // OpenCL 6.3j: shift values are effectively % word size of LHS.
2307  RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2308  static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2309  RHS.isUnsigned());
2310  else if (RHS.isSigned() && RHS.isNegative()) {
2311  // During constant-folding, a negative shift is an opposite shift. Such a
2312  // shift is not a constant expression.
2313  Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2314  RHS = -RHS;
2315  goto shift_left;
2316  }
2317  shift_right:
2318  // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2319  // shifted type.
2320  unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2321  if (SA != RHS)
2322  Info.CCEDiag(E, diag::note_constexpr_large_shift)
2323  << RHS << E->getType() << LHS.getBitWidth();
2324  Result = LHS >> SA;
2325  return true;
2326  }
2327 
2328  case BO_LT: Result = LHS < RHS; return true;
2329  case BO_GT: Result = LHS > RHS; return true;
2330  case BO_LE: Result = LHS <= RHS; return true;
2331  case BO_GE: Result = LHS >= RHS; return true;
2332  case BO_EQ: Result = LHS == RHS; return true;
2333  case BO_NE: Result = LHS != RHS; return true;
2334  case BO_Cmp:
2335  llvm_unreachable("BO_Cmp should be handled elsewhere");
2336  }
2337 }
2338 
2339 /// Perform the given binary floating-point operation, in-place, on LHS.
2340 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2341  APFloat &LHS, BinaryOperatorKind Opcode,
2342  const APFloat &RHS) {
2343  switch (Opcode) {
2344  default:
2345  Info.FFDiag(E);
2346  return false;
2347  case BO_Mul:
2348  LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2349  break;
2350  case BO_Add:
2351  LHS.add(RHS, APFloat::rmNearestTiesToEven);
2352  break;
2353  case BO_Sub:
2354  LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2355  break;
2356  case BO_Div:
2357  LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2358  break;
2359  }
2360 
2361  if (LHS.isInfinity() || LHS.isNaN()) {
2362  Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2363  return Info.noteUndefinedBehavior();
2364  }
2365  return true;
2366 }
2367 
2368 /// Cast an lvalue referring to a base subobject to a derived class, by
2369 /// truncating the lvalue's path to the given length.
2370 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2371  const RecordDecl *TruncatedType,
2372  unsigned TruncatedElements) {
2373  SubobjectDesignator &D = Result.Designator;
2374 
2375  // Check we actually point to a derived class object.
2376  if (TruncatedElements == D.Entries.size())
2377  return true;
2378  assert(TruncatedElements >= D.MostDerivedPathLength &&
2379  "not casting to a derived class");
2380  if (!Result.checkSubobject(Info, E, CSK_Derived))
2381  return false;
2382 
2383  // Truncate the path to the subobject, and remove any derived-to-base offsets.
2384  const RecordDecl *RD = TruncatedType;
2385  for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2386  if (RD->isInvalidDecl()) return false;
2387  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2388  const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2389  if (isVirtualBaseClass(D.Entries[I]))
2390  Result.Offset -= Layout.getVBaseClassOffset(Base);
2391  else
2392  Result.Offset -= Layout.getBaseClassOffset(Base);
2393  RD = Base;
2394  }
2395  D.Entries.resize(TruncatedElements);
2396  return true;
2397 }
2398 
2399 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2400  const CXXRecordDecl *Derived,
2401  const CXXRecordDecl *Base,
2402  const ASTRecordLayout *RL = nullptr) {
2403  if (!RL) {
2404  if (Derived->isInvalidDecl()) return false;
2405  RL = &Info.Ctx.getASTRecordLayout(Derived);
2406  }
2407 
2408  Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2409  Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2410  return true;
2411 }
2412 
2413 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2414  const CXXRecordDecl *DerivedDecl,
2415  const CXXBaseSpecifier *Base) {
2416  const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2417 
2418  if (!Base->isVirtual())
2419  return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2420 
2421  SubobjectDesignator &D = Obj.Designator;
2422  if (D.Invalid)
2423  return false;
2424 
2425  // Extract most-derived object and corresponding type.
2426  DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2427  if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2428  return false;
2429 
2430  // Find the virtual base class.
2431  if (DerivedDecl->isInvalidDecl()) return false;
2432  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2433  Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2434  Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2435  return true;
2436 }
2437 
2438 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2439  QualType Type, LValue &Result) {
2440  for (CastExpr::path_const_iterator PathI = E->path_begin(),
2441  PathE = E->path_end();
2442  PathI != PathE; ++PathI) {
2443  if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2444  *PathI))
2445  return false;
2446  Type = (*PathI)->getType();
2447  }
2448  return true;
2449 }
2450 
2451 /// Update LVal to refer to the given field, which must be a member of the type
2452 /// currently described by LVal.
2453 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2454  const FieldDecl *FD,
2455  const ASTRecordLayout *RL = nullptr) {
2456  if (!RL) {
2457  if (FD->getParent()->isInvalidDecl()) return false;
2458  RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2459  }
2460 
2461  unsigned I = FD->getFieldIndex();
2462  LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2463  LVal.addDecl(Info, E, FD);
2464  return true;
2465 }
2466 
2467 /// Update LVal to refer to the given indirect field.
2468 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2469  LValue &LVal,
2470  const IndirectFieldDecl *IFD) {
2471  for (const auto *C : IFD->chain())
2472  if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2473  return false;
2474  return true;
2475 }
2476 
2477 /// Get the size of the given type in char units.
2478 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2479  QualType Type, CharUnits &Size) {
2480  // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2481  // extension.
2482  if (Type->isVoidType() || Type->isFunctionType()) {
2483  Size = CharUnits::One();
2484  return true;
2485  }
2486 
2487  if (Type->isDependentType()) {
2488  Info.FFDiag(Loc);
2489  return false;
2490  }
2491 
2492  if (!Type->isConstantSizeType()) {
2493  // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2494  // FIXME: Better diagnostic.
2495  Info.FFDiag(Loc);
2496  return false;
2497  }
2498 
2499  Size = Info.Ctx.getTypeSizeInChars(Type);
2500  return true;
2501 }
2502 
2503 /// Update a pointer value to model pointer arithmetic.
2504 /// \param Info - Information about the ongoing evaluation.
2505 /// \param E - The expression being evaluated, for diagnostic purposes.
2506 /// \param LVal - The pointer value to be updated.
2507 /// \param EltTy - The pointee type represented by LVal.
2508 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2509 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2510  LValue &LVal, QualType EltTy,
2511  APSInt Adjustment) {
2512  CharUnits SizeOfPointee;
2513  if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2514  return false;
2515 
2516  LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2517  return true;
2518 }
2519 
2520 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2521  LValue &LVal, QualType EltTy,
2522  int64_t Adjustment) {
2523  return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2524  APSInt::get(Adjustment));
2525 }
2526 
2527 /// Update an lvalue to refer to a component of a complex number.
2528 /// \param Info - Information about the ongoing evaluation.
2529 /// \param LVal - The lvalue to be updated.
2530 /// \param EltTy - The complex number's component type.
2531 /// \param Imag - False for the real component, true for the imaginary.
2532 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2533  LValue &LVal, QualType EltTy,
2534  bool Imag) {
2535  if (Imag) {
2536  CharUnits SizeOfComponent;
2537  if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2538  return false;
2539  LVal.Offset += SizeOfComponent;
2540  }
2541  LVal.addComplex(Info, E, EltTy, Imag);
2542  return true;
2543 }
2544 
2545 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2546  QualType Type, const LValue &LVal,
2547  APValue &RVal);
2548 
2549 /// Try to evaluate the initializer for a variable declaration.
2550 ///
2551 /// \param Info Information about the ongoing evaluation.
2552 /// \param E An expression to be used when printing diagnostics.
2553 /// \param VD The variable whose initializer should be obtained.
2554 /// \param Frame The frame in which the variable was created. Must be null
2555 /// if this variable is not local to the evaluation.
2556 /// \param Result Filled in with a pointer to the value of the variable.
2557 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2558  const VarDecl *VD, CallStackFrame *Frame,
2559  APValue *&Result, const LValue *LVal) {
2560 
2561  // If this is a parameter to an active constexpr function call, perform
2562  // argument substitution.
2563  if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2564  // Assume arguments of a potential constant expression are unknown
2565  // constant expressions.
2566  if (Info.checkingPotentialConstantExpression())
2567  return false;
2568  if (!Frame || !Frame->Arguments) {
2569  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2570  return false;
2571  }
2572  Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2573  return true;
2574  }
2575 
2576  // If this is a local variable, dig out its value.
2577  if (Frame) {
2578  Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2579  : Frame->getCurrentTemporary(VD);
2580  if (!Result) {
2581  // Assume variables referenced within a lambda's call operator that were
2582  // not declared within the call operator are captures and during checking
2583  // of a potential constant expression, assume they are unknown constant
2584  // expressions.
2585  assert(isLambdaCallOperator(Frame->Callee) &&
2586  (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2587  "missing value for local variable");
2588  if (Info.checkingPotentialConstantExpression())
2589  return false;
2590  // FIXME: implement capture evaluation during constant expr evaluation.
2591  Info.FFDiag(E->getBeginLoc(),
2592  diag::note_unimplemented_constexpr_lambda_feature_ast)
2593  << "captures not currently allowed";
2594  return false;
2595  }
2596  return true;
2597  }
2598 
2599  // Dig out the initializer, and use the declaration which it's attached to.
2600  const Expr *Init = VD->getAnyInitializer(VD);
2601  if (!Init || Init->isValueDependent()) {
2602  // If we're checking a potential constant expression, the variable could be
2603  // initialized later.
2604  if (!Info.checkingPotentialConstantExpression())
2605  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2606  return false;
2607  }
2608 
2609  // If we're currently evaluating the initializer of this declaration, use that
2610  // in-flight value.
2611  if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2612  Result = Info.EvaluatingDeclValue;
2613  return true;
2614  }
2615 
2616  // Never evaluate the initializer of a weak variable. We can't be sure that
2617  // this is the definition which will be used.
2618  if (VD->isWeak()) {
2619  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2620  return false;
2621  }
2622 
2623  // Check that we can fold the initializer. In C++, we will have already done
2624  // this in the cases where it matters for conformance.
2626  if (!VD->evaluateValue(Notes)) {
2627  Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2628  Notes.size() + 1) << VD;
2629  Info.Note(VD->getLocation(), diag::note_declared_at);
2630  Info.addNotes(Notes);
2631  return false;
2632  } else if (!VD->checkInitIsICE()) {
2633  Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2634  Notes.size() + 1) << VD;
2635  Info.Note(VD->getLocation(), diag::note_declared_at);
2636  Info.addNotes(Notes);
2637  }
2638 
2639  Result = VD->getEvaluatedValue();
2640  return true;
2641 }
2642 
2644  Qualifiers Quals = T.getQualifiers();
2645  return Quals.hasConst() && !Quals.hasVolatile();
2646 }
2647 
2648 /// Get the base index of the given base class within an APValue representing
2649 /// the given derived class.
2650 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2651  const CXXRecordDecl *Base) {
2652  Base = Base->getCanonicalDecl();
2653  unsigned Index = 0;
2655  E = Derived->bases_end(); I != E; ++I, ++Index) {
2656  if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2657  return Index;
2658  }
2659 
2660  llvm_unreachable("base class missing from derived class's bases list");
2661 }
2662 
2663 /// Extract the value of a character from a string literal.
2664 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2665  uint64_t Index) {
2666  // FIXME: Support MakeStringConstant
2667  if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2668  std::string Str;
2669  Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2670  assert(Index <= Str.size() && "Index too large");
2671  return APSInt::getUnsigned(Str.c_str()[Index]);
2672  }
2673 
2674  if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2675  Lit = PE->getFunctionName();
2676  const StringLiteral *S = cast<StringLiteral>(Lit);
2677  const ConstantArrayType *CAT =
2678  Info.Ctx.getAsConstantArrayType(S->getType());
2679  assert(CAT && "string literal isn't an array");
2680  QualType CharType = CAT->getElementType();
2681  assert(CharType->isIntegerType() && "unexpected character type");
2682 
2683  APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2684  CharType->isUnsignedIntegerType());
2685  if (Index < S->getLength())
2686  Value = S->getCodeUnit(Index);
2687  return Value;
2688 }
2689 
2690 // Expand a string literal into an array of characters.
2691 //
2692 // FIXME: This is inefficient; we should probably introduce something similar
2693 // to the LLVM ConstantDataArray to make this cheaper.
2694 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
2695  APValue &Result) {
2696  const ConstantArrayType *CAT =
2697  Info.Ctx.getAsConstantArrayType(S->getType());
2698  assert(CAT && "string literal isn't an array");
2699  QualType CharType = CAT->getElementType();
2700  assert(CharType->isIntegerType() && "unexpected character type");
2701 
2702  unsigned Elts = CAT->getSize().getZExtValue();
2703  Result = APValue(APValue::UninitArray(),
2704  std::min(S->getLength(), Elts), Elts);
2705  APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2706  CharType->isUnsignedIntegerType());
2707  if (Result.hasArrayFiller())
2708  Result.getArrayFiller() = APValue(Value);
2709  for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2710  Value = S->getCodeUnit(I);
2711  Result.getArrayInitializedElt(I) = APValue(Value);
2712  }
2713 }
2714 
2715 // Expand an array so that it has more than Index filled elements.
2716 static void expandArray(APValue &Array, unsigned Index) {
2717  unsigned Size = Array.getArraySize();
2718  assert(Index < Size);
2719 
2720  // Always at least double the number of elements for which we store a value.
2721  unsigned OldElts = Array.getArrayInitializedElts();
2722  unsigned NewElts = std::max(Index+1, OldElts * 2);
2723  NewElts = std::min(Size, std::max(NewElts, 8u));
2724 
2725  // Copy the data across.
2726  APValue NewValue(APValue::UninitArray(), NewElts, Size);
2727  for (unsigned I = 0; I != OldElts; ++I)
2728  NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2729  for (unsigned I = OldElts; I != NewElts; ++I)
2730  NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2731  if (NewValue.hasArrayFiller())
2732  NewValue.getArrayFiller() = Array.getArrayFiller();
2733  Array.swap(NewValue);
2734 }
2735 
2736 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2737 /// conversion. If it's of class type, we may assume that the copy operation
2738 /// is trivial. Note that this is never true for a union type with fields
2739 /// (because the copy always "reads" the active member) and always true for
2740 /// a non-class type.
2743  if (!RD || (RD->isUnion() && !RD->field_empty()))
2744  return true;
2745  if (RD->isEmpty())
2746  return false;
2747 
2748  for (auto *Field : RD->fields())
2749  if (isReadByLvalueToRvalueConversion(Field->getType()))
2750  return true;
2751 
2752  for (auto &BaseSpec : RD->bases())
2753  if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2754  return true;
2755 
2756  return false;
2757 }
2758 
2759 /// Diagnose an attempt to read from any unreadable field within the specified
2760 /// type, which might be a class type.
2761 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2762  QualType T) {
2764  if (!RD)
2765  return false;
2766 
2767  if (!RD->hasMutableFields())
2768  return false;
2769 
2770  for (auto *Field : RD->fields()) {
2771  // If we're actually going to read this field in some way, then it can't
2772  // be mutable. If we're in a union, then assigning to a mutable field
2773  // (even an empty one) can change the active member, so that's not OK.
2774  // FIXME: Add core issue number for the union case.
2775  if (Field->isMutable() &&
2776  (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2777  Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2778  Info.Note(Field->getLocation(), diag::note_declared_at);
2779  return true;
2780  }
2781 
2782  if (diagnoseUnreadableFields(Info, E, Field->getType()))
2783  return true;
2784  }
2785 
2786  for (auto &BaseSpec : RD->bases())
2787  if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2788  return true;
2789 
2790  // All mutable fields were empty, and thus not actually read.
2791  return false;
2792 }
2793 
2794 namespace {
2795 /// A handle to a complete object (an object that is not a subobject of
2796 /// another object).
2797 struct CompleteObject {
2798  /// The value of the complete object.
2799  APValue *Value;
2800  /// The type of the complete object.
2801  QualType Type;
2802  bool LifetimeStartedInEvaluation;
2803 
2804  CompleteObject() : Value(nullptr) {}
2805  CompleteObject(APValue *Value, QualType Type,
2806  bool LifetimeStartedInEvaluation)
2807  : Value(Value), Type(Type),
2808  LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
2809  assert(Value && "missing value for complete object");
2810  }
2811 
2812  explicit operator bool() const { return Value; }
2813 };
2814 } // end anonymous namespace
2815 
2816 /// Find the designated sub-object of an rvalue.
2817 template<typename SubobjectHandler>
2818 typename SubobjectHandler::result_type
2819 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2820  const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2821  if (Sub.Invalid)
2822  // A diagnostic will have already been produced.
2823  return handler.failed();
2824  if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
2825  if (Info.getLangOpts().CPlusPlus11)
2826  Info.FFDiag(E, Sub.isOnePastTheEnd()
2827  ? diag::note_constexpr_access_past_end
2828  : diag::note_constexpr_access_unsized_array)
2829  << handler.AccessKind;
2830  else
2831  Info.FFDiag(E);
2832  return handler.failed();
2833  }
2834 
2835  APValue *O = Obj.Value;
2836  QualType ObjType = Obj.Type;
2837  const FieldDecl *LastField = nullptr;
2838  const bool MayReadMutableMembers =
2839  Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
2840 
2841  // Walk the designator's path to find the subobject.
2842  for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2843  if (O->isUninit()) {
2844  if (!Info.checkingPotentialConstantExpression())
2845  Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2846  return handler.failed();
2847  }
2848 
2849  if (I == N) {
2850  // If we are reading an object of class type, there may still be more
2851  // things we need to check: if there are any mutable subobjects, we
2852  // cannot perform this read. (This only happens when performing a trivial
2853  // copy or assignment.)
2854  if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2855  !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
2856  return handler.failed();
2857 
2858  if (!handler.found(*O, ObjType))
2859  return false;
2860 
2861  // If we modified a bit-field, truncate it to the right width.
2862  if (handler.AccessKind != AK_Read &&
2863  LastField && LastField->isBitField() &&
2864  !truncateBitfieldValue(Info, E, *O, LastField))
2865  return false;
2866 
2867  return true;
2868  }
2869 
2870  LastField = nullptr;
2871  if (ObjType->isArrayType()) {
2872  // Next subobject is an array element.
2873  const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2874  assert(CAT && "vla in literal type?");
2875  uint64_t Index = Sub.Entries[I].ArrayIndex;
2876  if (CAT->getSize().ule(Index)) {
2877  // Note, it should not be possible to form a pointer with a valid
2878  // designator which points more than one past the end of the array.
2879  if (Info.getLangOpts().CPlusPlus11)
2880  Info.FFDiag(E, diag::note_constexpr_access_past_end)
2881  << handler.AccessKind;
2882  else
2883  Info.FFDiag(E);
2884  return handler.failed();
2885  }
2886 
2887  ObjType = CAT->getElementType();
2888 
2889  if (O->getArrayInitializedElts() > Index)
2890  O = &O->getArrayInitializedElt(Index);
2891  else if (handler.AccessKind != AK_Read) {
2892  expandArray(*O, Index);
2893  O = &O->getArrayInitializedElt(Index);
2894  } else
2895  O = &O->getArrayFiller();
2896  } else if (ObjType->isAnyComplexType()) {
2897  // Next subobject is a complex number.
2898  uint64_t Index = Sub.Entries[I].ArrayIndex;
2899  if (Index > 1) {
2900  if (Info.getLangOpts().CPlusPlus11)
2901  Info.FFDiag(E, diag::note_constexpr_access_past_end)
2902  << handler.AccessKind;
2903  else
2904  Info.FFDiag(E);
2905  return handler.failed();
2906  }
2907 
2908  bool WasConstQualified = ObjType.isConstQualified();
2909  ObjType = ObjType->castAs<ComplexType>()->getElementType();
2910  if (WasConstQualified)
2911  ObjType.addConst();
2912 
2913  assert(I == N - 1 && "extracting subobject of scalar?");
2914  if (O->isComplexInt()) {
2915  return handler.found(Index ? O->getComplexIntImag()
2916  : O->getComplexIntReal(), ObjType);
2917  } else {
2918  assert(O->isComplexFloat());
2919  return handler.found(Index ? O->getComplexFloatImag()
2920  : O->getComplexFloatReal(), ObjType);
2921  }
2922  } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2923  // In C++14 onwards, it is permitted to read a mutable member whose
2924  // lifetime began within the evaluation.
2925  // FIXME: Should we also allow this in C++11?
2926  if (Field->isMutable() && handler.AccessKind == AK_Read &&
2927  !MayReadMutableMembers) {
2928  Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
2929  << Field;
2930  Info.Note(Field->getLocation(), diag::note_declared_at);
2931  return handler.failed();
2932  }
2933 
2934  // Next subobject is a class, struct or union field.
2935  RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2936  if (RD->isUnion()) {
2937  const FieldDecl *UnionField = O->getUnionField();
2938  if (!UnionField ||
2939  UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2940  Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
2941  << handler.AccessKind << Field << !UnionField << UnionField;
2942  return handler.failed();
2943  }
2944  O = &O->getUnionValue();
2945  } else
2946  O = &O->getStructField(Field->getFieldIndex());
2947 
2948  bool WasConstQualified = ObjType.isConstQualified();
2949  ObjType = Field->getType();
2950  if (WasConstQualified && !Field->isMutable())
2951  ObjType.addConst();
2952 
2953  if (ObjType.isVolatileQualified()) {
2954  if (Info.getLangOpts().CPlusPlus) {
2955  // FIXME: Include a description of the path to the volatile subobject.
2956  Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2957  << handler.AccessKind << 2 << Field;
2958  Info.Note(Field->getLocation(), diag::note_declared_at);
2959  } else {
2960  Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2961  }
2962  return handler.failed();
2963  }
2964 
2965  LastField = Field;
2966  } else {
2967  // Next subobject is a base class.
2968  const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2969  const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2970  O = &O->getStructBase(getBaseIndex(Derived, Base));
2971 
2972  bool WasConstQualified = ObjType.isConstQualified();
2973  ObjType = Info.Ctx.getRecordType(Base);
2974  if (WasConstQualified)
2975  ObjType.addConst();
2976  }
2977  }
2978 }
2979 
2980 namespace {
2981 struct ExtractSubobjectHandler {
2982  EvalInfo &Info;
2983  APValue &Result;
2984 
2985  static const AccessKinds AccessKind = AK_Read;
2986 
2987  typedef bool result_type;
2988  bool failed() { return false; }
2989  bool found(APValue &Subobj, QualType SubobjType) {
2990  Result = Subobj;
2991  return true;
2992  }
2993  bool found(APSInt &Value, QualType SubobjType) {
2994  Result = APValue(Value);
2995  return true;
2996  }
2997  bool found(APFloat &Value, QualType SubobjType) {
2998  Result = APValue(Value);
2999  return true;
3000  }
3001 };
3002 } // end anonymous namespace
3003 
3005 
3006 /// Extract the designated sub-object of an rvalue.
3007 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3008  const CompleteObject &Obj,
3009  const SubobjectDesignator &Sub,
3010  APValue &Result) {
3011  ExtractSubobjectHandler Handler = { Info, Result };
3012  return findSubobject(Info, E, Obj, Sub, Handler);
3013 }
3014 
3015 namespace {
3016 struct ModifySubobjectHandler {
3017  EvalInfo &Info;
3018  APValue &NewVal;
3019  const Expr *E;
3020 
3021  typedef bool result_type;
3022  static const AccessKinds AccessKind = AK_Assign;
3023 
3024  bool checkConst(QualType QT) {
3025  // Assigning to a const object has undefined behavior.
3026  if (QT.isConstQualified()) {
3027  Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3028  return false;
3029  }
3030  return true;
3031  }
3032 
3033  bool failed() { return false; }
3034  bool found(APValue &Subobj, QualType SubobjType) {
3035  if (!checkConst(SubobjType))
3036  return false;
3037  // We've been given ownership of NewVal, so just swap it in.
3038  Subobj.swap(NewVal);
3039  return true;
3040  }
3041  bool found(APSInt &Value, QualType SubobjType) {
3042  if (!checkConst(SubobjType))
3043  return false;
3044  if (!NewVal.isInt()) {
3045  // Maybe trying to write a cast pointer value into a complex?
3046  Info.FFDiag(E);
3047  return false;
3048  }
3049  Value = NewVal.getInt();
3050  return true;
3051  }
3052  bool found(APFloat &Value, QualType SubobjType) {
3053  if (!checkConst(SubobjType))
3054  return false;
3055  Value = NewVal.getFloat();
3056  return true;
3057  }
3058 };
3059 } // end anonymous namespace
3060 
3062 
3063 /// Update the designated sub-object of an rvalue to the given value.
3064 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3065  const CompleteObject &Obj,
3066  const SubobjectDesignator &Sub,
3067  APValue &NewVal) {
3068  ModifySubobjectHandler Handler = { Info, NewVal, E };
3069  return findSubobject(Info, E, Obj, Sub, Handler);
3070 }
3071 
3072 /// Find the position where two subobject designators diverge, or equivalently
3073 /// the length of the common initial subsequence.
3074 static unsigned FindDesignatorMismatch(QualType ObjType,
3075  const SubobjectDesignator &A,
3076  const SubobjectDesignator &B,
3077  bool &WasArrayIndex) {
3078  unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3079  for (/**/; I != N; ++I) {
3080  if (!ObjType.isNull() &&
3081  (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3082  // Next subobject is an array element.
3083  if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
3084  WasArrayIndex = true;
3085  return I;
3086  }
3087  if (ObjType->isAnyComplexType())
3088  ObjType = ObjType->castAs<ComplexType>()->getElementType();
3089  else
3090  ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3091  } else {
3092  if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
3093  WasArrayIndex = false;
3094  return I;
3095  }
3096  if (const FieldDecl *FD = getAsField(A.Entries[I]))
3097  // Next subobject is a field.
3098  ObjType = FD->getType();
3099  else
3100  // Next subobject is a base class.
3101  ObjType = QualType();
3102  }
3103  }
3104  WasArrayIndex = false;
3105  return I;
3106 }
3107 
3108 /// Determine whether the given subobject designators refer to elements of the
3109 /// same array object.
3110 static bool AreElementsOfSameArray(QualType ObjType,
3111  const SubobjectDesignator &A,
3112  const SubobjectDesignator &B) {
3113  if (A.Entries.size() != B.Entries.size())
3114  return false;
3115 
3116  bool IsArray = A.MostDerivedIsArrayElement;
3117  if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3118  // A is a subobject of the array element.
3119  return false;
3120 
3121  // If A (and B) designates an array element, the last entry will be the array
3122  // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3123  // of length 1' case, and the entire path must match.
3124  bool WasArrayIndex;
3125  unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3126  return CommonLength >= A.Entries.size() - IsArray;
3127 }
3128 
3129 /// Find the complete object to which an LValue refers.
3130 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3131  AccessKinds AK, const LValue &LVal,
3132  QualType LValType) {
3133  if (!LVal.Base) {
3134  Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3135  return CompleteObject();
3136  }
3137 
3138  CallStackFrame *Frame = nullptr;
3139  if (LVal.getLValueCallIndex()) {
3140  Frame = Info.getCallFrame(LVal.getLValueCallIndex());
3141  if (!Frame) {
3142  Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3143  << AK << LVal.Base.is<const ValueDecl*>();
3144  NoteLValueLocation(Info, LVal.Base);
3145  return CompleteObject();
3146  }
3147  }
3148 
3149  // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3150  // is not a constant expression (even if the object is non-volatile). We also
3151  // apply this rule to C++98, in order to conform to the expected 'volatile'
3152  // semantics.
3153  if (LValType.isVolatileQualified()) {
3154  if (Info.getLangOpts().CPlusPlus)
3155  Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3156  << AK << LValType;
3157  else
3158  Info.FFDiag(E);
3159  return CompleteObject();
3160  }
3161 
3162  // Compute value storage location and type of base object.
3163  APValue *BaseVal = nullptr;
3164  QualType BaseType = getType(LVal.Base);
3165  bool LifetimeStartedInEvaluation = Frame;
3166 
3167  if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3168  // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3169  // In C++11, constexpr, non-volatile variables initialized with constant
3170  // expressions are constant expressions too. Inside constexpr functions,
3171  // parameters are constant expressions even if they're non-const.
3172  // In C++1y, objects local to a constant expression (those with a Frame) are
3173  // both readable and writable inside constant expressions.
3174  // In C, such things can also be folded, although they are not ICEs.
3175  const VarDecl *VD = dyn_cast<VarDecl>(D);
3176  if (VD) {
3177  if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3178  VD = VDef;
3179  }
3180  if (!VD || VD->isInvalidDecl()) {
3181  Info.FFDiag(E);
3182  return CompleteObject();
3183  }
3184 
3185  // Accesses of volatile-qualified objects are not allowed.
3186  if (BaseType.isVolatileQualified()) {
3187  if (Info.getLangOpts().CPlusPlus) {
3188  Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3189  << AK << 1 << VD;
3190  Info.Note(VD->getLocation(), diag::note_declared_at);
3191  } else {
3192  Info.FFDiag(E);
3193  }
3194  return CompleteObject();
3195  }
3196 
3197  // Unless we're looking at a local variable or argument in a constexpr call,
3198  // the variable we're reading must be const.
3199  if (!Frame) {
3200  if (Info.getLangOpts().CPlusPlus14 &&
3201  VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3202  // OK, we can read and modify an object if we're in the process of
3203  // evaluating its initializer, because its lifetime began in this
3204  // evaluation.
3205  } else if (AK != AK_Read) {
3206  // All the remaining cases only permit reading.
3207  Info.FFDiag(E, diag::note_constexpr_modify_global);
3208  return CompleteObject();
3209  } else if (VD->isConstexpr()) {
3210  // OK, we can read this variable.
3211  } else if (BaseType->isIntegralOrEnumerationType()) {
3212  // In OpenCL if a variable is in constant address space it is a const value.
3213  if (!(BaseType.isConstQualified() ||
3214  (Info.getLangOpts().OpenCL &&
3215  BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3216  if (Info.getLangOpts().CPlusPlus) {
3217  Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3218  Info.Note(VD->getLocation(), diag::note_declared_at);
3219  } else {
3220  Info.FFDiag(E);
3221  }
3222  return CompleteObject();
3223  }
3224  } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3225  // We support folding of const floating-point types, in order to make
3226  // static const data members of such types (supported as an extension)
3227  // more useful.
3228  if (Info.getLangOpts().CPlusPlus11) {
3229  Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3230  Info.Note(VD->getLocation(), diag::note_declared_at);
3231  } else {
3232  Info.CCEDiag(E);
3233  }
3234  } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3235  Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3236  // Keep evaluating to see what we can do.
3237  } else {
3238  // FIXME: Allow folding of values of any literal type in all languages.
3239  if (Info.checkingPotentialConstantExpression() &&
3240  VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3241  // The definition of this variable could be constexpr. We can't
3242  // access it right now, but may be able to in future.
3243  } else if (Info.getLangOpts().CPlusPlus11) {
3244  Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3245  Info.Note(VD->getLocation(), diag::note_declared_at);
3246  } else {
3247  Info.FFDiag(E);
3248  }
3249  return CompleteObject();
3250  }
3251  }
3252 
3253  if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
3254  return CompleteObject();
3255  } else {
3256  const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3257 
3258  if (!Frame) {
3259  if (const MaterializeTemporaryExpr *MTE =
3260  dyn_cast<MaterializeTemporaryExpr>(Base)) {
3261  assert(MTE->getStorageDuration() == SD_Static &&
3262  "should have a frame for a non-global materialized temporary");
3263 
3264  // Per C++1y [expr.const]p2:
3265  // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3266  // - a [...] glvalue of integral or enumeration type that refers to
3267  // a non-volatile const object [...]
3268  // [...]
3269  // - a [...] glvalue of literal type that refers to a non-volatile
3270  // object whose lifetime began within the evaluation of e.
3271  //
3272  // C++11 misses the 'began within the evaluation of e' check and
3273  // instead allows all temporaries, including things like:
3274  // int &&r = 1;
3275  // int x = ++r;
3276  // constexpr int k = r;
3277  // Therefore we use the C++14 rules in C++11 too.
3278  const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3279  const ValueDecl *ED = MTE->getExtendingDecl();
3280  if (!(BaseType.isConstQualified() &&
3281  BaseType->isIntegralOrEnumerationType()) &&
3282  !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
3283  Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3284  Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3285  return CompleteObject();
3286  }
3287 
3288  BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3289  assert(BaseVal && "got reference to unevaluated temporary");
3290  LifetimeStartedInEvaluation = true;
3291  } else {
3292  Info.FFDiag(E);
3293  return CompleteObject();
3294  }
3295  } else {
3296  BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
3297  assert(BaseVal && "missing value for temporary");
3298  }
3299 
3300  // Volatile temporary objects cannot be accessed in constant expressions.
3301  if (BaseType.isVolatileQualified()) {
3302  if (Info.getLangOpts().CPlusPlus) {
3303  Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3304  << AK << 0;
3305  Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3306  } else {
3307  Info.FFDiag(E);
3308  }
3309  return CompleteObject();
3310  }
3311  }
3312 
3313  // During the construction of an object, it is not yet 'const'.
3314  // FIXME: This doesn't do quite the right thing for const subobjects of the
3315  // object under construction.
3316  if (Info.isEvaluatingConstructor(LVal.getLValueBase(),
3317  LVal.getLValueCallIndex(),
3318  LVal.getLValueVersion())) {
3319  BaseType = Info.Ctx.getCanonicalType(BaseType);
3320  BaseType.removeLocalConst();
3321  LifetimeStartedInEvaluation = true;
3322  }
3323 
3324  // In C++14, we can't safely access any mutable state when we might be
3325  // evaluating after an unmodeled side effect.
3326  //
3327  // FIXME: Not all local state is mutable. Allow local constant subobjects
3328  // to be read here (but take care with 'mutable' fields).
3329  if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3330  Info.EvalStatus.HasSideEffects) ||
3331  (AK != AK_Read && Info.IsSpeculativelyEvaluating))
3332  return CompleteObject();
3333 
3334  return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
3335 }
3336 
3337 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
3338 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3339 /// glvalue referred to by an entity of reference type.
3340 ///
3341 /// \param Info - Information about the ongoing evaluation.
3342 /// \param Conv - The expression for which we are performing the conversion.
3343 /// Used for diagnostics.
3344 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3345 /// case of a non-class type).
3346 /// \param LVal - The glvalue on which we are attempting to perform this action.
3347 /// \param RVal - The produced value will be placed here.
3348 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
3349  QualType Type,
3350  const LValue &LVal, APValue &RVal) {
3351  if (LVal.Designator.Invalid)
3352  return false;
3353 
3354  // Check for special cases where there is no existing APValue to look at.
3355  const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3356  if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
3357  if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3358  // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3359  // initializer until now for such expressions. Such an expression can't be
3360  // an ICE in C, so this only matters for fold.
3361  if (Type.isVolatileQualified()) {
3362  Info.FFDiag(Conv);
3363  return false;
3364  }
3365  APValue Lit;
3366  if (!Evaluate(Lit, Info, CLE->getInitializer()))
3367  return false;
3368  CompleteObject LitObj(&Lit, Base->getType(), false);
3369  return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
3370  } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3371  // Special-case character extraction so we don't have to construct an
3372  // APValue for the whole string.
3373  assert(LVal.Designator.Entries.size() <= 1 &&
3374  "Can only read characters from string literals");
3375  if (LVal.Designator.Entries.empty()) {
3376  // Fail for now for LValue to RValue conversion of an array.
3377  // (This shouldn't show up in C/C++, but it could be triggered by a
3378  // weird EvaluateAsRValue call from a tool.)
3379  Info.FFDiag(Conv);
3380  return false;
3381  }
3382  if (LVal.Designator.isOnePastTheEnd()) {
3383  if (Info.getLangOpts().CPlusPlus11)
3384  Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK_Read;
3385  else
3386  Info.FFDiag(Conv);
3387  return false;
3388  }
3389  uint64_t CharIndex = LVal.Designator.Entries[0].ArrayIndex;
3390  RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3391  return true;
3392  }
3393  }
3394 
3395  CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3396  return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
3397 }
3398 
3399 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3400 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3401  QualType LValType, APValue &Val) {
3402  if (LVal.Designator.Invalid)
3403  return false;
3404 
3405  if (!Info.getLangOpts().CPlusPlus14) {
3406  Info.FFDiag(E);
3407  return false;
3408  }
3409 
3410  CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3411  return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3412 }
3413 
3414 namespace {
3415 struct CompoundAssignSubobjectHandler {
3416  EvalInfo &Info;
3417  const Expr *E;
3418  QualType PromotedLHSType;
3419  BinaryOperatorKind Opcode;
3420  const APValue &RHS;
3421 
3422  static const AccessKinds AccessKind = AK_Assign;
3423 
3424  typedef bool result_type;
3425 
3426  bool checkConst(QualType QT) {
3427  // Assigning to a const object has undefined behavior.
3428  if (QT.isConstQualified()) {
3429  Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3430  return false;
3431  }
3432  return true;
3433  }
3434 
3435  bool failed() { return false; }
3436  bool found(APValue &Subobj, QualType SubobjType) {
3437  switch (Subobj.getKind()) {
3438  case APValue::Int:
3439  return found(Subobj.getInt(), SubobjType);
3440  case APValue::Float:
3441  return found(Subobj.getFloat(), SubobjType);
3442  case APValue::ComplexInt:
3443  case APValue::ComplexFloat:
3444  // FIXME: Implement complex compound assignment.
3445  Info.FFDiag(E);
3446  return false;
3447  case APValue::LValue:
3448  return foundPointer(Subobj, SubobjType);
3449  default:
3450  // FIXME: can this happen?
3451  Info.FFDiag(E);
3452  return false;
3453  }
3454  }
3455  bool found(APSInt &Value, QualType SubobjType) {
3456  if (!checkConst(SubobjType))
3457  return false;
3458 
3459  if (!SubobjType->isIntegerType()) {
3460  // We don't support compound assignment on integer-cast-to-pointer
3461  // values.
3462  Info.FFDiag(E);
3463  return false;
3464  }
3465 
3466  if (RHS.isInt()) {
3467  APSInt LHS =
3468  HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3469  if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3470  return false;
3471  Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3472  return true;
3473  } else if (RHS.isFloat()) {
3474  APFloat FValue(0.0);
3475  return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3476  FValue) &&
3477  handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3478  HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3479  Value);
3480  }
3481 
3482  Info.FFDiag(E);
3483  return false;
3484  }
3485  bool found(APFloat &Value, QualType SubobjType) {
3486  return checkConst(SubobjType) &&
3487  HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3488  Value) &&
3489  handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3490  HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3491  }
3492  bool foundPointer(APValue &Subobj, QualType SubobjType) {
3493  if (!checkConst(SubobjType))
3494  return false;
3495 
3496  QualType PointeeType;
3497  if (const PointerType *PT = SubobjType->getAs<PointerType>())
3498  PointeeType = PT->getPointeeType();
3499 
3500  if (PointeeType.isNull() || !RHS.isInt() ||
3501  (Opcode != BO_Add && Opcode != BO_Sub)) {
3502  Info.FFDiag(E);
3503  return false;
3504  }
3505 
3506  APSInt Offset = RHS.getInt();
3507  if (Opcode == BO_Sub)
3508  negateAsSigned(Offset);
3509 
3510  LValue LVal;
3511  LVal.setFrom(Info.Ctx, Subobj);
3512  if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3513  return false;
3514  LVal.moveInto(Subobj);
3515  return true;
3516  }
3517 };
3518 } // end anonymous namespace
3519 
3521 
3522 /// Perform a compound assignment of LVal <op>= RVal.
3524  EvalInfo &Info, const Expr *E,
3525  const LValue &LVal, QualType LValType, QualType PromotedLValType,
3526  BinaryOperatorKind Opcode, const APValue &RVal) {
3527  if (LVal.Designator.Invalid)
3528  return false;
3529 
3530  if (!Info.getLangOpts().CPlusPlus14) {
3531  Info.FFDiag(E);
3532  return false;
3533  }
3534 
3535  CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3536  CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3537  RVal };
3538  return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3539 }
3540 
3541 namespace {
3542 struct IncDecSubobjectHandler {
3543  EvalInfo &Info;
3544  const UnaryOperator *E;
3546  APValue *Old;
3547 
3548  typedef bool result_type;
3549 
3550  bool checkConst(QualType QT) {
3551  // Assigning to a const object has undefined behavior.
3552  if (QT.isConstQualified()) {
3553  Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3554  return false;
3555  }
3556  return true;
3557  }
3558 
3559  bool failed() { return false; }
3560  bool found(APValue &Subobj, QualType SubobjType) {
3561  // Stash the old value. Also clear Old, so we don't clobber it later
3562  // if we're post-incrementing a complex.
3563  if (Old) {
3564  *Old = Subobj;
3565  Old = nullptr;
3566  }
3567 
3568  switch (Subobj.getKind()) {
3569  case APValue::Int:
3570  return found(Subobj.getInt(), SubobjType);
3571  case APValue::Float:
3572  return found(Subobj.getFloat(), SubobjType);
3573  case APValue::ComplexInt:
3574  return found(Subobj.getComplexIntReal(),
3575  SubobjType->castAs<ComplexType>()->getElementType()
3576  .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3577  case APValue::ComplexFloat:
3578  return found(Subobj.getComplexFloatReal(),
3579  SubobjType->castAs<ComplexType>()->getElementType()
3580  .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3581  case APValue::LValue:
3582  return foundPointer(Subobj, SubobjType);
3583  default:
3584  // FIXME: can this happen?
3585  Info.FFDiag(E);
3586  return false;
3587  }
3588  }
3589  bool found(APSInt &Value, QualType SubobjType) {
3590  if (!checkConst(SubobjType))
3591  return false;
3592 
3593  if (!SubobjType->isIntegerType()) {
3594  // We don't support increment / decrement on integer-cast-to-pointer
3595  // values.
3596  Info.FFDiag(E);
3597  return false;
3598  }
3599 
3600  if (Old) *Old = APValue(Value);
3601 
3602  // bool arithmetic promotes to int, and the conversion back to bool
3603  // doesn't reduce mod 2^n, so special-case it.
3604  if (SubobjType->isBooleanType()) {
3605  if (AccessKind == AK_Increment)
3606  Value = 1;
3607  else
3608  Value = !Value;
3609  return true;
3610  }
3611 
3612  bool WasNegative = Value.isNegative();
3613  if (AccessKind == AK_Increment) {
3614  ++Value;
3615 
3616  if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3617  APSInt ActualValue(Value, /*IsUnsigned*/true);
3618  return HandleOverflow(Info, E, ActualValue, SubobjType);
3619  }
3620  } else {
3621  --Value;
3622 
3623  if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3624  unsigned BitWidth = Value.getBitWidth();
3625  APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3626  ActualValue.setBit(BitWidth);
3627  return HandleOverflow(Info, E, ActualValue, SubobjType);
3628  }
3629  }
3630  return true;
3631  }
3632  bool found(APFloat &Value, QualType SubobjType) {
3633  if (!checkConst(SubobjType))
3634  return false;
3635 
3636  if (Old) *Old = APValue(Value);
3637 
3638  APFloat One(Value.getSemantics(), 1);
3639  if (AccessKind == AK_Increment)
3640  Value.add(One, APFloat::rmNearestTiesToEven);
3641  else
3642  Value.subtract(One, APFloat::rmNearestTiesToEven);
3643  return true;
3644  }
3645  bool foundPointer(APValue &Subobj, QualType SubobjType) {
3646  if (!checkConst(SubobjType))
3647  return false;
3648 
3649  QualType PointeeType;
3650  if (const PointerType *PT = SubobjType->getAs<PointerType>())
3651  PointeeType = PT->getPointeeType();
3652  else {
3653  Info.FFDiag(E);
3654  return false;
3655  }
3656 
3657  LValue LVal;
3658  LVal.setFrom(Info.Ctx, Subobj);
3659  if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3660  AccessKind == AK_Increment ? 1 : -1))
3661  return false;
3662  LVal.moveInto(Subobj);
3663  return true;
3664  }
3665 };
3666 } // end anonymous namespace
3667 
3668 /// Perform an increment or decrement on LVal.
3669 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3670  QualType LValType, bool IsIncrement, APValue *Old) {
3671  if (LVal.Designator.Invalid)
3672  return false;
3673 
3674  if (!Info.getLangOpts().CPlusPlus14) {
3675  Info.FFDiag(E);
3676  return false;
3677  }
3678 
3679  AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3680  CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3681  IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3682  return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3683 }
3684 
3685 /// Build an lvalue for the object argument of a member function call.
3686 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3687  LValue &This) {
3688  if (Object->getType()->isPointerType())
3689  return EvaluatePointer(Object, This, Info);
3690 
3691  if (Object->isGLValue())
3692  return EvaluateLValue(Object, This, Info);
3693 
3694  if (Object->getType()->isLiteralType(Info.Ctx))
3695  return EvaluateTemporary(Object, This, Info);
3696 
3697  Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3698  return false;
3699 }
3700 
3701 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3702 /// lvalue referring to the result.
3703 ///
3704 /// \param Info - Information about the ongoing evaluation.
3705 /// \param LV - An lvalue referring to the base of the member pointer.
3706 /// \param RHS - The member pointer expression.
3707 /// \param IncludeMember - Specifies whether the member itself is included in
3708 /// the resulting LValue subobject designator. This is not possible when
3709 /// creating a bound member function.
3710 /// \return The field or method declaration to which the member pointer refers,
3711 /// or 0 if evaluation fails.
3712 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3713  QualType LVType,
3714  LValue &LV,
3715  const Expr *RHS,
3716  bool IncludeMember = true) {
3717  MemberPtr MemPtr;
3718  if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3719  return nullptr;
3720 
3721  // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3722  // member value, the behavior is undefined.
3723  if (!MemPtr.getDecl()) {
3724  // FIXME: Specific diagnostic.
3725  Info.FFDiag(RHS);
3726  return nullptr;
3727  }
3728 
3729  if (MemPtr.isDerivedMember()) {
3730  // This is a member of some derived class. Truncate LV appropriately.
3731  // The end of the derived-to-base path for the base object must match the
3732  // derived-to-base path for the member pointer.
3733  if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3734  LV.Designator.Entries.size()) {
3735  Info.FFDiag(RHS);
3736  return nullptr;
3737  }
3738  unsigned PathLengthToMember =
3739  LV.Designator.Entries.size() - MemPtr.Path.size();
3740  for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3741  const CXXRecordDecl *LVDecl = getAsBaseClass(
3742  LV.Designator.Entries[PathLengthToMember + I]);
3743  const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3744  if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3745  Info.FFDiag(RHS);
3746  return nullptr;
3747  }
3748  }
3749 
3750  // Truncate the lvalue to the appropriate derived class.
3751  if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3752  PathLengthToMember))
3753  return nullptr;
3754  } else if (!MemPtr.Path.empty()) {
3755  // Extend the LValue path with the member pointer's path.
3756  LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3757  MemPtr.Path.size() + IncludeMember);
3758 
3759  // Walk down to the appropriate base class.
3760  if (const PointerType *PT = LVType->getAs<PointerType>())
3761  LVType = PT->getPointeeType();
3762  const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3763  assert(RD && "member pointer access on non-class-type expression");
3764  // The first class in the path is that of the lvalue.
3765  for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3766  const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3767  if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3768  return nullptr;
3769  RD = Base;
3770  }
3771  // Finally cast to the class containing the member.
3772  if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3773  MemPtr.getContainingRecord()))
3774  return nullptr;
3775  }
3776 
3777  // Add the member. Note that we cannot build bound member functions here.
3778  if (IncludeMember) {
3779  if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3780  if (!HandleLValueMember(Info, RHS, LV, FD))
3781  return nullptr;
3782  } else if (const IndirectFieldDecl *IFD =
3783  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3784  if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3785  return nullptr;
3786  } else {
3787  llvm_unreachable("can't construct reference to bound member function");
3788  }
3789  }
3790 
3791  return MemPtr.getDecl();
3792 }
3793 
3794 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3795  const BinaryOperator *BO,
3796  LValue &LV,
3797  bool IncludeMember = true) {
3798  assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3799 
3800  if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3801  if (Info.noteFailure()) {
3802  MemberPtr MemPtr;
3803  EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3804  }
3805  return nullptr;
3806  }
3807 
3808  return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3809  BO->getRHS(), IncludeMember);
3810 }
3811 
3812 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3813 /// the provided lvalue, which currently refers to the base object.
3814 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3815  LValue &Result) {
3816  SubobjectDesignator &D = Result.Designator;
3817  if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3818  return false;
3819 
3820  QualType TargetQT = E->getType();
3821  if (const PointerType *PT = TargetQT->getAs<PointerType>())
3822  TargetQT = PT->getPointeeType();
3823 
3824  // Check this cast lands within the final derived-to-base subobject path.
3825  if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3826  Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3827  << D.MostDerivedType << TargetQT;
3828  return false;
3829  }
3830 
3831  // Check the type of the final cast. We don't need to check the path,
3832  // since a cast can only be formed if the path is unique.
3833  unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3834  const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3835  const CXXRecordDecl *FinalType;
3836  if (NewEntriesSize == D.MostDerivedPathLength)
3837  FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3838  else
3839  FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3840  if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3841  Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3842  << D.MostDerivedType << TargetQT;
3843  return false;
3844  }
3845 
3846  // Truncate the lvalue to the appropriate derived class.
3847  return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3848 }
3849 
3850 namespace {
3852  /// Evaluation failed.
3853  ESR_Failed,
3854  /// Hit a 'return' statement.
3855  ESR_Returned,
3856  /// Evaluation succeeded.
3857  ESR_Succeeded,
3858  /// Hit a 'continue' statement.
3859  ESR_Continue,
3860  /// Hit a 'break' statement.
3861  ESR_Break,
3862  /// Still scanning for 'case' or 'default' statement.
3863  ESR_CaseNotFound
3864 };
3865 }
3866 
3867 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3868  // We don't need to evaluate the initializer for a static local.
3869  if (!VD->hasLocalStorage())
3870  return true;
3871 
3872  LValue Result;
3873  APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
3874 
3875  const Expr *InitE = VD->getInit();
3876  if (!InitE) {
3877  Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
3878  << false << VD->getType();
3879  Val = APValue();
3880  return false;
3881  }
3882 
3883  if (InitE->isValueDependent())
3884  return false;
3885 
3886  if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3887  // Wipe out any partially-computed value, to allow tracking that this
3888  // evaluation failed.
3889  Val = APValue();
3890  return false;
3891  }
3892 
3893  return true;
3894 }
3895 
3896 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3897  bool OK = true;
3898 
3899  if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3900  OK &= EvaluateVarDecl(Info, VD);
3901 
3902  if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3903  for (auto *BD : DD->bindings())
3904  if (auto *VD = BD->getHoldingVar())
3905  OK &= EvaluateDecl(Info, VD);
3906 
3907  return OK;
3908 }
3909 
3910 
3911 /// Evaluate a condition (either a variable declaration or an expression).
3912 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3913  const Expr *Cond, bool &Result) {
3914  FullExpressionRAII Scope(Info);
3915  if (CondDecl && !EvaluateDecl(Info, CondDecl))
3916  return false;
3917  return EvaluateAsBooleanCondition(Cond, Result, Info);
3918 }
3919 
3920 namespace {
3921 /// A location where the result (returned value) of evaluating a
3922 /// statement should be stored.
3923 struct StmtResult {
3924  /// The APValue that should be filled in with the returned value.
3925  APValue &Value;
3926  /// The location containing the result, if any (used to support RVO).
3927  const LValue *Slot;
3928 };
3929 
3930 struct TempVersionRAII {
3931  CallStackFrame &Frame;
3932 
3933  TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
3934  Frame.pushTempVersion();
3935  }
3936 
3937  ~TempVersionRAII() {
3938  Frame.popTempVersion();
3939  }
3940 };
3941 
3942 }
3943 
3944 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3945  const Stmt *S,
3946  const SwitchCase *SC = nullptr);
3947 
3948 /// Evaluate the body of a loop, and translate the result as appropriate.
3949 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
3950  const Stmt *Body,
3951  const SwitchCase *Case = nullptr) {
3952  BlockScopeRAII Scope(Info);
3953  switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3954  case ESR_Break:
3955  return ESR_Succeeded;
3956  case ESR_Succeeded:
3957  case ESR_Continue:
3958  return ESR_Continue;
3959  case ESR_Failed:
3960  case ESR_Returned:
3961  case ESR_CaseNotFound:
3962  return ESR;
3963  }
3964  llvm_unreachable("Invalid EvalStmtResult!");
3965 }
3966 
3967 /// Evaluate a switch statement.
3968 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
3969  const SwitchStmt *SS) {
3970  BlockScopeRAII Scope(Info);
3971 
3972  // Evaluate the switch condition.
3973  APSInt Value;
3974  {
3975  FullExpressionRAII Scope(Info);
3976  if (const Stmt *Init = SS->getInit()) {
3977  EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3978  if (ESR != ESR_Succeeded)
3979  return ESR;
3980  }
3981  if (SS->getConditionVariable() &&
3982  !EvaluateDecl(Info, SS->getConditionVariable()))
3983  return ESR_Failed;
3984  if (!EvaluateInteger(SS->getCond(), Value, Info))
3985  return ESR_Failed;
3986  }
3987 
3988  // Find the switch case corresponding to the value of the condition.
3989  // FIXME: Cache this lookup.
3990  const SwitchCase *Found = nullptr;
3991  for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3992  SC = SC->getNextSwitchCase()) {
3993  if (isa<DefaultStmt>(SC)) {
3994  Found = SC;
3995  continue;
3996  }
3997 
3998  const CaseStmt *CS = cast<CaseStmt>(SC);
3999  APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4000  APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4001  : LHS;
4002  if (LHS <= Value && Value <= RHS) {
4003  Found = SC;
4004  break;
4005  }
4006  }
4007 
4008  if (!Found)
4009  return ESR_Succeeded;
4010 
4011  // Search the switch body for the switch case and evaluate it from there.
4012  switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
4013  case ESR_Break:
4014  return ESR_Succeeded;
4015  case ESR_Succeeded:
4016  case ESR_Continue:
4017  case ESR_Failed:
4018  case ESR_Returned:
4019  return ESR;
4020  case ESR_CaseNotFound:
4021  // This can only happen if the switch case is nested within a statement
4022  // expression. We have no intention of supporting that.
4023  Info.FFDiag(Found->getBeginLoc(),
4024  diag::note_constexpr_stmt_expr_unsupported);
4025  return ESR_Failed;
4026  }
4027  llvm_unreachable("Invalid EvalStmtResult!");
4028 }
4029 
4030 // Evaluate a statement.
4031 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4032  const Stmt *S, const SwitchCase *Case) {
4033  if (!Info.nextStep(S))
4034  return ESR_Failed;
4035 
4036  // If we're hunting down a 'case' or 'default' label, recurse through
4037  // substatements until we hit the label.
4038  if (Case) {
4039  // FIXME: We don't start the lifetime of objects whose initialization we
4040  // jump over. However, such objects must be of class type with a trivial
4041  // default constructor that initialize all subobjects, so must be empty,
4042  // so this almost never matters.
4043  switch (S->getStmtClass()) {
4044  case Stmt::CompoundStmtClass:
4045  // FIXME: Precompute which substatement of a compound statement we
4046  // would jump to, and go straight there rather than performing a
4047  // linear scan each time.
4048  case Stmt::LabelStmtClass:
4049  case Stmt::AttributedStmtClass:
4050  case Stmt::DoStmtClass:
4051  break;
4052 
4053  case Stmt::CaseStmtClass:
4054  case Stmt::DefaultStmtClass:
4055  if (Case == S)
4056  Case = nullptr;
4057  break;
4058 
4059  case Stmt::IfStmtClass: {
4060  // FIXME: Precompute which side of an 'if' we would jump to, and go
4061  // straight there rather than scanning both sides.
4062  const IfStmt *IS = cast<IfStmt>(S);
4063 
4064  // Wrap the evaluation in a block scope, in case it's a DeclStmt
4065  // preceded by our switch label.
4066  BlockScopeRAII Scope(Info);
4067 
4068  EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4069  if (ESR != ESR_CaseNotFound || !IS->getElse())
4070  return ESR;
4071  return EvaluateStmt(Result, Info, IS->getElse(), Case);
4072  }
4073 
4074  case Stmt::WhileStmtClass: {
4075  EvalStmtResult ESR =
4076  EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4077  if (ESR != ESR_Continue)
4078  return ESR;
4079  break;
4080  }
4081 
4082  case Stmt::ForStmtClass: {
4083  const ForStmt *FS = cast<ForStmt>(S);
4084  EvalStmtResult ESR =
4085  EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4086  if (ESR != ESR_Continue)
4087  return ESR;
4088  if (FS->getInc()) {
4089  FullExpressionRAII IncScope(Info);
4090  if (!EvaluateIgnoredValue(Info, FS->getInc()))
4091  return ESR_Failed;
4092  }
4093  break;
4094  }
4095 
4096  case Stmt::DeclStmtClass:
4097  // FIXME: If the variable has initialization that can't be jumped over,
4098  // bail out of any immediately-surrounding compound-statement too.
4099  default:
4100  return ESR_CaseNotFound;
4101  }
4102  }
4103 
4104  switch (S->getStmtClass()) {
4105  default:
4106  if (const Expr *E = dyn_cast<Expr>(S)) {
4107  // Don't bother evaluating beyond an expression-statement which couldn't
4108  // be evaluated.
4109  FullExpressionRAII Scope(Info);
4110  if (!EvaluateIgnoredValue(Info, E))
4111  return ESR_Failed;
4112  return ESR_Succeeded;
4113  }
4114 
4115  Info.FFDiag(S->getBeginLoc());
4116  return ESR_Failed;
4117 
4118  case Stmt::NullStmtClass:
4119  return ESR_Succeeded;
4120 
4121  case Stmt::DeclStmtClass: {
4122  const DeclStmt *DS = cast<DeclStmt>(S);
4123  for (const auto *DclIt : DS->decls()) {
4124  // Each declaration initialization is its own full-expression.
4125  // FIXME: This isn't quite right; if we're performing aggregate
4126  // initialization, each braced subexpression is its own full-expression.
4127  FullExpressionRAII Scope(Info);
4128  if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
4129  return ESR_Failed;
4130  }
4131  return ESR_Succeeded;
4132  }
4133 
4134  case Stmt::ReturnStmtClass: {
4135  const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
4136  FullExpressionRAII Scope(Info);
4137  if (RetExpr &&
4138  !(Result.Slot
4139  ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4140  : Evaluate(Result.Value, Info, RetExpr)))
4141  return ESR_Failed;
4142  return ESR_Returned;
4143  }
4144 
4145  case Stmt::CompoundStmtClass: {
4146  BlockScopeRAII Scope(Info);
4147 
4148  const CompoundStmt *CS = cast<CompoundStmt>(S);
4149  for (const auto *BI : CS->body()) {
4150  EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
4151  if (ESR == ESR_Succeeded)
4152  Case = nullptr;
4153  else if (ESR != ESR_CaseNotFound)
4154  return ESR;
4155  }
4156  return Case ? ESR_CaseNotFound : ESR_Succeeded;
4157  }
4158 
4159  case Stmt::IfStmtClass: {
4160  const IfStmt *IS = cast<IfStmt>(S);
4161 
4162  // Evaluate the condition, as either a var decl or as an expression.
4163  BlockScopeRAII Scope(Info);
4164  if (const Stmt *Init = IS->getInit()) {
4165  EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4166  if (ESR != ESR_Succeeded)
4167  return ESR;
4168  }
4169  bool Cond;
4170  if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4171  return ESR_Failed;
4172 
4173  if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4174  EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4175  if (ESR != ESR_Succeeded)
4176  return ESR;
4177  }
4178  return ESR_Succeeded;
4179  }
4180 
4181  case Stmt::WhileStmtClass: {
4182  const WhileStmt *WS = cast<WhileStmt>(S);
4183  while (true) {
4184  BlockScopeRAII Scope(Info);
4185  bool Continue;
4186  if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4187  Continue))
4188  return ESR_Failed;
4189  if (!Continue)
4190  break;
4191 
4192  EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4193  if (ESR != ESR_Continue)
4194  return ESR;
4195  }
4196  return ESR_Succeeded;
4197  }
4198 
4199  case Stmt::DoStmtClass: {
4200  const DoStmt *DS = cast<DoStmt>(S);
4201  bool Continue;
4202  do {
4203  EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4204  if (ESR != ESR_Continue)
4205  return ESR;
4206  Case = nullptr;
4207 
4208  FullExpressionRAII CondScope(Info);
4209  if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4210  return ESR_Failed;
4211  } while (Continue);
4212  return ESR_Succeeded;
4213  }
4214 
4215  case Stmt::ForStmtClass: {
4216  const ForStmt *FS = cast<ForStmt>(S);
4217  BlockScopeRAII Scope(Info);
4218  if (FS->getInit()) {
4219  EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4220  if (ESR != ESR_Succeeded)
4221  return ESR;
4222  }
4223  while (true) {
4224  BlockScopeRAII Scope(Info);
4225  bool Continue = true;
4226  if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4227  FS->getCond(), Continue))
4228  return ESR_Failed;
4229  if (!Continue)
4230  break;
4231 
4232  EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4233  if (ESR != ESR_Continue)
4234  return ESR;
4235 
4236  if (FS->getInc()) {
4237  FullExpressionRAII IncScope(Info);
4238  if (!EvaluateIgnoredValue(Info, FS->getInc()))
4239  return ESR_Failed;
4240  }
4241  }
4242  return ESR_Succeeded;
4243  }
4244 
4245  case Stmt::CXXForRangeStmtClass: {
4246  const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4247  BlockScopeRAII Scope(Info);
4248 
4249  // Evaluate the init-statement if present.
4250  if (FS->getInit()) {
4251  EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4252  if (ESR != ESR_Succeeded)
4253  return ESR;
4254  }
4255 
4256  // Initialize the __range variable.
4257  EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4258  if (ESR != ESR_Succeeded)
4259  return ESR;
4260 
4261  // Create the __begin and __end iterators.
4262  ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4263  if (ESR != ESR_Succeeded)
4264  return ESR;
4265  ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4266  if (ESR != ESR_Succeeded)
4267  return ESR;
4268 
4269  while (true) {
4270  // Condition: __begin != __end.
4271  {
4272  bool Continue = true;
4273  FullExpressionRAII CondExpr(Info);
4274  if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4275  return ESR_Failed;
4276  if (!Continue)
4277  break;
4278  }
4279 
4280  // User's variable declaration, initialized by *__begin.
4281  BlockScopeRAII InnerScope(Info);
4282  ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4283  if (ESR != ESR_Succeeded)
4284  return ESR;
4285 
4286  // Loop body.
4287  ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4288  if (ESR != ESR_Continue)
4289  return ESR;
4290 
4291  // Increment: ++__begin
4292  if (!EvaluateIgnoredValue(Info, FS->getInc()))
4293  return ESR_Failed;
4294  }
4295 
4296  return ESR_Succeeded;
4297  }
4298 
4299  case Stmt::SwitchStmtClass:
4300  return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4301 
4302  case Stmt::ContinueStmtClass:
4303  return ESR_Continue;
4304 
4305  case Stmt::BreakStmtClass:
4306  return ESR_Break;
4307 
4308  case Stmt::LabelStmtClass:
4309  return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4310 
4311  case Stmt::AttributedStmtClass:
4312  // As a general principle, C++11 attributes can be ignored without
4313  // any semantic impact.
4314  return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4315  Case);
4316 
4317  case Stmt::CaseStmtClass:
4318  case Stmt::DefaultStmtClass:
4319  return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4320  case Stmt::CXXTryStmtClass:
4321  // Evaluate try blocks by evaluating all sub statements.
4322  return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
4323  }
4324 }
4325 
4326 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4327 /// default constructor. If so, we'll fold it whether or not it's marked as
4328 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4329 /// so we need special handling.
4330 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4331  const CXXConstructorDecl *CD,
4332  bool IsValueInitialization) {
4333  if (!CD->isTrivial() || !CD->isDefaultConstructor())
4334  return false;
4335 
4336  // Value-initialization does not call a trivial default constructor, so such a
4337  // call is a core constant expression whether or not the constructor is
4338  // constexpr.
4339  if (!CD->isConstexpr() && !IsValueInitialization) {
4340  if (Info.getLangOpts().CPlusPlus11) {
4341  // FIXME: If DiagDecl is an implicitly-declared special member function,
4342  // we should be much more explicit about why it's not constexpr.
4343  Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4344  << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4345  Info.Note(CD->getLocation(), diag::note_declared_at);
4346  } else {
4347  Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4348  }
4349  }
4350  return true;
4351 }
4352 
4353 /// CheckConstexprFunction - Check that a function can be called in a constant
4354 /// expression.
4355 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4356  const FunctionDecl *Declaration,
4357  const FunctionDecl *Definition,
4358  const Stmt *Body) {
4359  // Potential constant expressions can contain calls to declared, but not yet
4360  // defined, constexpr functions.
4361  if (Info.checkingPotentialConstantExpression() && !Definition &&
4362  Declaration->isConstexpr())
4363  return false;
4364 
4365  // Bail out if the function declaration itself is invalid. We will
4366  // have produced a relevant diagnostic while parsing it, so just
4367  // note the problematic sub-expression.
4368  if (Declaration->isInvalidDecl()) {
4369  Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4370  return false;
4371  }
4372 
4373  // Can we evaluate this function call?
4374  if (Definition && Definition->isConstexpr() &&
4375  !Definition->isInvalidDecl() && Body)
4376  return true;
4377 
4378  if (Info.getLangOpts().CPlusPlus11) {
4379  const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4380 
4381  // If this function is not constexpr because it is an inherited
4382  // non-constexpr constructor, diagnose that directly.
4383  auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4384  if (CD && CD->isInheritingConstructor()) {
4385  auto *Inherited = CD->getInheritedConstructor().getConstructor();
4386  if (!Inherited->isConstexpr())
4387  DiagDecl = CD = Inherited;
4388  }
4389 
4390  // FIXME: If DiagDecl is an implicitly-declared special member function
4391  // or an inheriting constructor, we should be much more explicit about why
4392  // it's not constexpr.
4393  if (CD && CD->isInheritingConstructor())
4394  Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4395  << CD->getInheritedConstructor().getConstructor()->getParent();
4396  else
4397  Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4398  << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4399  Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4400  } else {
4401  Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4402  }
4403  return false;
4404 }
4405 
4406 /// Determine if a class has any fields that might need to be copied by a
4407 /// trivial copy or move operation.
4408 static bool hasFields(const CXXRecordDecl *RD) {
4409  if (!RD || RD->isEmpty())
4410  return false;
4411  for (auto *FD : RD->fields()) {
4412  if (FD->isUnnamedBitfield())
4413  continue;
4414  return true;
4415  }
4416  for (auto &Base : RD->bases())
4417  if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4418  return true;
4419  return false;
4420 }
4421 
4422 namespace {
4423 typedef SmallVector<APValue, 8> ArgVector;
4424 }
4425 
4426 /// EvaluateArgs - Evaluate the arguments to a function call.
4427 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4428  EvalInfo &Info) {
4429  bool Success = true;
4430  for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
4431  I != E; ++I) {
4432  if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4433  // If we're checking for a potential constant expression, evaluate all
4434  // initializers even if some of them fail.
4435  if (!Info.noteFailure())
4436  return false;
4437  Success = false;
4438  }
4439  }
4440  return Success;
4441 }
4442 
4443 /// Evaluate a function call.
4445  const FunctionDecl *Callee, const LValue *This,
4446  ArrayRef<const Expr*> Args, const Stmt *Body,
4447  EvalInfo &Info, APValue &Result,
4448  const LValue *ResultSlot) {
4449  ArgVector ArgValues(Args.size());
4450  if (!EvaluateArgs(Args, ArgValues, Info))
4451  return false;
4452 
4453  if (!Info.CheckCallLimit(CallLoc))
4454  return false;
4455 
4456  CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
4457 
4458  // For a trivial copy or move assignment, perform an APValue copy. This is
4459  // essential for unions, where the operations performed by the assignment
4460  // operator cannot be represented as statements.
4461  //
4462  // Skip this for non-union classes with no fields; in that case, the defaulted
4463  // copy/move does not actually read the object.
4464  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
4465  if (MD && MD->isDefaulted() &&
4466  (MD->getParent()->isUnion() ||
4467  (MD->isTrivial() && hasFields(MD->getParent())))) {
4468  assert(This &&
4469  (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4470  LValue RHS;
4471  RHS.setFrom(Info.Ctx, ArgValues[0]);
4472  APValue RHSValue;
4473  if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4474  RHS, RHSValue))
4475  return false;
4476  if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
4477  RHSValue))
4478  return false;
4479  This->moveInto(Result);
4480  return true;
4481  } else if (MD && isLambdaCallOperator(MD)) {
4482  // We're in a lambda; determine the lambda capture field maps unless we're
4483  // just constexpr checking a lambda's call operator. constexpr checking is
4484  // done before the captures have been added to the closure object (unless
4485  // we're inferring constexpr-ness), so we don't have access to them in this
4486  // case. But since we don't need the captures to constexpr check, we can
4487  // just ignore them.
4488  if (!Info.checkingPotentialConstantExpression())
4489  MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4490  Frame.LambdaThisCaptureField);
4491  }
4492 
4493  StmtResult Ret = {Result, ResultSlot};
4494  EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
4495  if (ESR == ESR_Succeeded) {
4496  if (Callee->getReturnType()->isVoidType())
4497  return true;
4498  Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
4499  }
4500  return ESR == ESR_Returned;
4501 }
4502 
4503 /// Evaluate a constructor call.
4504 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4505  APValue *ArgValues,
4506  const CXXConstructorDecl *Definition,
4507  EvalInfo &Info, APValue &Result) {
4508  SourceLocation CallLoc = E->getExprLoc();
4509  if (!Info.CheckCallLimit(CallLoc))
4510  return false;
4511 
4512  const CXXRecordDecl *RD = Definition->getParent();
4513  if (RD->getNumVBases()) {
4514  Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
4515  return false;
4516  }
4517 
4518  EvalInfo::EvaluatingConstructorRAII EvalObj(
4519  Info, {This.getLValueBase(),
4520  {This.getLValueCallIndex(), This.getLValueVersion()}});
4521  CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
4522 
4523  // FIXME: Creating an APValue just to hold a nonexistent return value is
4524  // wasteful.
4525  APValue RetVal;
4526  StmtResult Ret = {RetVal, nullptr};
4527 
4528  // If it's a delegating constructor, delegate.
4529  if (Definition->isDelegatingConstructor()) {
4531  {
4532  FullExpressionRAII InitScope(Info);
4533  if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4534  return false;
4535  }
4536  return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4537  }
4538 
4539  // For a trivial copy or move constructor, perform an APValue copy. This is
4540  // essential for unions (or classes with anonymous union members), where the
4541  // operations performed by the constructor cannot be represented by
4542  // ctor-initializers.
4543  //
4544  // Skip this for empty non-union classes; we should not perform an
4545  // lvalue-to-rvalue conversion on them because their copy constructor does not
4546  // actually read them.
4547  if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
4548  (Definition->getParent()->isUnion() ||
4549  (Definition->isTrivial() && hasFields(Definition->getParent())))) {
4550  LValue RHS;
4551  RHS.setFrom(Info.Ctx, ArgValues[0]);
4553  Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4554  RHS, Result);
4555  }
4556 
4557  // Reserve space for the struct members.
4558  if (!RD->isUnion() && Result.isUninit())
4559  Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4560  std::distance(RD->field_begin(), RD->field_end()));
4561 
4562  if (RD->isInvalidDecl()) return false;
4563  const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4564 
4565  // A scope for temporaries lifetime-extended by reference members.
4566  BlockScopeRAII LifetimeExtendedScope(Info);
4567 
4568  bool Success = true;
4569  unsigned BasesSeen = 0;
4570 #ifndef NDEBUG
4572 #endif
4573  for (const auto *I : Definition->inits()) {
4574  LValue Subobject = This;
4575  LValue SubobjectParent = This;
4576  APValue *Value = &Result;
4577 
4578  // Determine the subobject to initialize.
4579  FieldDecl *FD = nullptr;
4580  if (I->isBaseInitializer()) {
4581  QualType BaseType(I->getBaseClass(), 0);
4582 #ifndef NDEBUG
4583  // Non-virtual base classes are initialized in the order in the class
4584  // definition. We have already checked for virtual base classes.
4585  assert(!BaseIt->isVirtual() && "virtual base for literal type");
4586  assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4587  "base class initializers not in expected order");
4588  ++BaseIt;
4589 #endif
4590  if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
4591  BaseType->getAsCXXRecordDecl(), &Layout))
4592  return false;
4593  Value = &Result.getStructBase(BasesSeen++);
4594  } else if ((FD = I->getMember())) {
4595  if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
4596  return false;
4597  if (RD->isUnion()) {
4598  Result = APValue(FD);
4599  Value = &Result.getUnionValue();
4600  } else {
4601  Value = &Result.getStructField(FD->getFieldIndex());
4602  }
4603  } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
4604  // Walk the indirect field decl's chain to find the object to initialize,
4605  // and make sure we've initialized every step along it.
4606  auto IndirectFieldChain = IFD->chain();
4607  for (auto *C : IndirectFieldChain) {
4608  FD = cast<FieldDecl>(C);
4609  CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4610  // Switch the union field if it differs. This happens if we had
4611  // preceding zero-initialization, and we're now initializing a union
4612  // subobject other than the first.
4613  // FIXME: In this case, the values of the other subobjects are
4614  // specified, since zero-initialization sets all padding bits to zero.
4615  if (Value->isUninit() ||
4616  (Value->isUnion() && Value->getUnionField() != FD)) {
4617  if (CD->isUnion())
4618  *Value = APValue(FD);
4619  else
4620  *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
4621  std::distance(CD->field_begin(), CD->field_end()));
4622  }
4623  // Store Subobject as its parent before updating it for the last element
4624  // in the chain.
4625  if (C == IndirectFieldChain.back())
4626  SubobjectParent = Subobject;
4627  if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
4628  return false;
4629  if (CD->isUnion())
4630  Value = &Value->getUnionValue();
4631  else
4632  Value = &Value->getStructField(FD->getFieldIndex());
4633  }
4634  } else {
4635  llvm_unreachable("unknown base initializer kind");
4636  }
4637 
4638  // Need to override This for implicit field initializers as in this case
4639  // This refers to innermost anonymous struct/union containing initializer,
4640  // not to currently constructed class.
4641  const Expr *Init = I->getInit();
4642  ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
4643  isa<CXXDefaultInitExpr>(Init));
4644  FullExpressionRAII InitScope(Info);
4645  if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
4646  (FD && FD->isBitField() &&
4647  !truncateBitfieldValue(Info, Init, *Value, FD))) {
4648  // If we're checking for a potential constant expression, evaluate all
4649  // initializers even if some of them fail.
4650  if (!Info.noteFailure())
4651  return false;
4652  Success = false;
4653  }
4654  }
4655 
4656  return Success &&
4657  EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4658 }
4659 
4660 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4661  ArrayRef<const Expr*> Args,
4662  const CXXConstructorDecl *Definition,
4663  EvalInfo &Info, APValue &Result) {
4664  ArgVector ArgValues(Args.size());
4665  if (!EvaluateArgs(Args, ArgValues, Info))
4666  return false;
4667 
4668  return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4669  Info, Result);
4670 }
4671 
4672 //===----------------------------------------------------------------------===//
4673 // Generic Evaluation
4674 //===----------------------------------------------------------------------===//
4675 namespace {
4676 
4677 template <class Derived>
4678 class ExprEvaluatorBase
4679  : public ConstStmtVisitor<Derived, bool> {
4680 private:
4681  Derived &getDerived() { return static_cast<Derived&>(*this); }
4682  bool DerivedSuccess(const APValue &V, const Expr *E) {
4683  return getDerived().Success(V, E);
4684  }
4685  bool DerivedZeroInitialization(const Expr *E) {
4686  return getDerived().ZeroInitialization(E);
4687  }
4688 
4689  // Check whether a conditional operator with a non-constant condition is a
4690  // potential constant expression. If neither arm is a potential constant
4691  // expression, then the conditional operator is not either.
4692  template<typename ConditionalOperator>
4693  void CheckPotentialConstantConditional(const ConditionalOperator *E) {
4694  assert(Info.checkingPotentialConstantExpression());
4695 
4696  // Speculatively evaluate both arms.
4698  {
4699  SpeculativeEvaluationRAII Speculate(Info, &Diag);
4700  StmtVisitorTy::Visit(E->getFalseExpr());
4701  if (Diag.empty())
4702  return;
4703  }
4704 
4705  {
4706  SpeculativeEvaluationRAII Speculate(Info, &Diag);
4707  Diag.clear();
4708  StmtVisitorTy::Visit(E->getTrueExpr());
4709  if (Diag.empty())
4710  return;
4711  }
4712 
4713  Error(E, diag::note_constexpr_conditional_never_const);
4714  }
4715 
4716 
4717  template<typename ConditionalOperator>
4718  bool HandleConditionalOperator(const ConditionalOperator *E) {
4719  bool BoolResult;
4720  if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
4721  if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
4722  CheckPotentialConstantConditional(E);
4723  return false;
4724  }
4725  if (Info.noteFailure()) {
4726  StmtVisitorTy::Visit(E->getTrueExpr());
4727  StmtVisitorTy::Visit(E->getFalseExpr());
4728  }
4729  return false;
4730  }
4731 
4732  Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4733  return StmtVisitorTy::Visit(EvalExpr);
4734  }
4735 
4736 protected:
4737  EvalInfo &Info;
4738  typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
4739  typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4740 
4741  OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4742  return Info.CCEDiag(E, D);
4743  }
4744 
4745  bool ZeroInitialization(const Expr *E) { return Error(E); }
4746 
4747 public:
4748  ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4749 
4750  EvalInfo &getEvalInfo() { return Info; }
4751 
4752  /// Report an evaluation error. This should only be called when an error is
4753  /// first discovered. When propagating an error, just return false.
4754  bool Error(const Expr *E, diag::kind D) {
4755  Info.FFDiag(E, D);
4756  return false;
4757  }
4758  bool Error(const Expr *E) {
4759  return Error(E, diag::note_invalid_subexpr_in_const_expr);
4760  }
4761 
4762  bool VisitStmt(const Stmt *) {
4763  llvm_unreachable("Expression evaluator should not be called on stmts");
4764  }
4765  bool VisitExpr(const Expr *E) {
4766  return Error(E);
4767  }
4768 
4769  bool VisitConstantExpr(const ConstantExpr *E)
4770  { return StmtVisitorTy::Visit(E->getSubExpr()); }
4771  bool VisitParenExpr(const ParenExpr *E)
4772  { return StmtVisitorTy::Visit(E->getSubExpr()); }
4773  bool VisitUnaryExtension(const UnaryOperator *E)
4774  { return StmtVisitorTy::Visit(E->getSubExpr()); }
4775  bool VisitUnaryPlus(const UnaryOperator *E)
4776  { return StmtVisitorTy::Visit(E->getSubExpr()); }
4777  bool VisitChooseExpr(const ChooseExpr *E)
4778  { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
4779  bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
4780  { return StmtVisitorTy::Visit(E->getResultExpr()); }
4781  bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
4782  { return StmtVisitorTy::Visit(E->getReplacement()); }
4783  bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
4784  TempVersionRAII RAII(*Info.CurrentCall);
4785  return StmtVisitorTy::Visit(E->getExpr());
4786  }
4787  bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
4788  TempVersionRAII RAII(*Info.CurrentCall);
4789  // The initializer may not have been parsed yet, or might be erroneous.
4790  if (!E->getExpr())
4791  return Error(E);
4792  return StmtVisitorTy::Visit(E->getExpr());
4793  }
4794  // We cannot create any objects for which cleanups are required, so there is
4795  // nothing to do here; all cleanups must come from unevaluated subexpressions.
4796  bool VisitExprWithCleanups(const ExprWithCleanups *E)
4797  { return StmtVisitorTy::Visit(E->getSubExpr()); }
4798 
4799  bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
4800  CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4801  return static_cast<Derived*>(this)->VisitCastExpr(E);
4802  }
4803  bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
4804  CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4805  return static_cast<Derived*>(this)->VisitCastExpr(E);
4806  }
4807 
4808  bool VisitBinaryOperator(const BinaryOperator *E) {
4809  switch (E->getOpcode()) {
4810  default:
4811  return Error(E);
4812 
4813  case BO_Comma:
4814  VisitIgnoredValue(E->getLHS());
4815  return StmtVisitorTy::Visit(E->getRHS());
4816 
4817  case BO_PtrMemD:
4818  case BO_PtrMemI: {
4819  LValue Obj;
4820  if (!HandleMemberPointerAccess(Info, E, Obj))
4821  return false;
4822  APValue Result;
4823  if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
4824  return false;
4825  return DerivedSuccess(Result, E);
4826  }
4827  }
4828  }
4829 
4830  bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
4831  // Evaluate and cache the common expression. We treat it as a temporary,
4832  // even though it's not quite the same thing.
4833  if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
4834  Info, E->getCommon()))
4835  return false;
4836 
4837  return HandleConditionalOperator(E);
4838  }
4839 
4840  bool VisitConditionalOperator(const ConditionalOperator *E) {
4841  bool IsBcpCall = false;
4842  // If the condition (ignoring parens) is a __builtin_constant_p call,
4843  // the result is a constant expression if it can be folded without
4844  // side-effects. This is an important GNU extension. See GCC PR38377
4845  // for discussion.
4846  if (const CallExpr *CallCE =
4847  dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
4848  if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
4849  IsBcpCall = true;
4850 
4851  // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4852  // constant expression; we can't check whether it's potentially foldable.
4853  if (Info.checkingPotentialConstantExpression() && IsBcpCall)
4854  return false;
4855 
4856  FoldConstant Fold(Info, IsBcpCall);
4857  if (!HandleConditionalOperator(E)) {
4858  Fold.keepDiagnostics();
4859  return false;
4860  }
4861 
4862  return true;
4863  }
4864 
4865  bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
4866  if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
4867  return DerivedSuccess(*Value, E);
4868 
4869  const Expr *Source = E->getSourceExpr();
4870  if (!Source)
4871  return Error(E);
4872  if (Source == E) { // sanity checking.
4873  assert(0 && "OpaqueValueExpr recursively refers to itself");
4874  return Error(E);
4875  }
4876  return StmtVisitorTy::Visit(Source);
4877  }
4878 
4879  bool VisitCallExpr(const CallExpr *E) {
4880  APValue Result;
4881  if (!handleCallExpr(E, Result, nullptr))
4882  return false;
4883  return DerivedSuccess(Result, E);
4884  }
4885 
4886  bool handleCallExpr(const CallExpr *E, APValue &Result,
4887  const LValue *ResultSlot) {
4888  const Expr *Callee = E->getCallee()->IgnoreParens();
4889  QualType CalleeType = Callee->getType();
4890 
4891  const FunctionDecl *FD = nullptr;
4892  LValue *This = nullptr, ThisVal;
4893  auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
4894  bool HasQualifier = false;
4895 
4896  // Extract function decl and 'this' pointer from the callee.
4897  if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
4898  const ValueDecl *Member = nullptr;
4899  if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4900  // Explicit bound member calls, such as x.f() or p->g();
4901  if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
4902  return false;
4903  Member = ME->getMemberDecl();
4904  This = &ThisVal;
4905  HasQualifier = ME->hasQualifier();
4906  } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4907  // Indirect bound member calls ('.*' or '->*').
4908  Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4909  if (!Member) return false;
4910  This = &ThisVal;
4911  } else
4912  return Error(Callee);
4913 
4914  FD = dyn_cast<FunctionDecl>(Member);
4915  if (!FD)
4916  return Error(Callee);
4917  } else if (CalleeType->isFunctionPointerType()) {
4918  LValue Call;
4919  if (!EvaluatePointer(Callee, Call, Info))
4920  return false;
4921 
4922  if (!Call.getLValueOffset().isZero())
4923  return Error(Callee);
4924  FD = dyn_cast_or_null<FunctionDecl>(
4925  Call.getLValueBase().dyn_cast<const ValueDecl*>());
4926  if (!FD)
4927  return Error(Callee);
4928  // Don't call function pointers which have been cast to some other type.
4929  // Per DR (no number yet), the caller and callee can differ in noexcept.
4930  if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4931  CalleeType->getPointeeType(), FD->getType())) {
4932  return Error(E);
4933  }
4934 
4935  // Overloaded operator calls to member functions are represented as normal
4936  // calls with '*this' as the first argument.
4937  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4938  if (MD && !MD->isStatic()) {
4939  // FIXME: When selecting an implicit conversion for an overloaded
4940  // operator delete, we sometimes try to evaluate calls to conversion
4941  // operators without a 'this' parameter!
4942  if (Args.empty())
4943  return Error(E);
4944 
4945  if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4946  return false;
4947  This = &ThisVal;
4948  Args = Args.slice(1);
4949  } else if (MD && MD->isLambdaStaticInvoker()) {
4950  // Map the static invoker for the lambda back to the call operator.
4951  // Conveniently, we don't have to slice out the 'this' argument (as is
4952  // being done for the non-static case), since a static member function
4953  // doesn't have an implicit argument passed in.
4954  const CXXRecordDecl *ClosureClass = MD->getParent();
4955  assert(
4956  ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4957  "Number of captures must be zero for conversion to function-ptr");
4958 
4959  const CXXMethodDecl *LambdaCallOp =
4960  ClosureClass->getLambdaCallOperator();
4961 
4962  // Set 'FD', the function that will be called below, to the call
4963  // operator. If the closure object represents a generic lambda, find
4964  // the corresponding specialization of the call operator.
4965 
4966  if (ClosureClass->isGenericLambda()) {
4967  assert(MD->isFunctionTemplateSpecialization() &&
4968  "A generic lambda's static-invoker function must be a "
4969  "template specialization");
4971  FunctionTemplateDecl *CallOpTemplate =
4972  LambdaCallOp->getDescribedFunctionTemplate();
4973  void *InsertPos = nullptr;
4974  FunctionDecl *CorrespondingCallOpSpecialization =
4975  CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4976  assert(CorrespondingCallOpSpecialization &&
4977  "We must always have a function call operator specialization "
4978  "that corresponds to our static invoker specialization");
4979  FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4980  } else
4981  FD = LambdaCallOp;
4982  }
4983 
4984 
4985  } else
4986  return Error(E);
4987 
4988  if (This && !This->checkSubobject(Info, E, CSK_This))
4989  return false;
4990 
4991  // DR1358 allows virtual constexpr functions in some cases. Don't allow
4992  // calls to such functions in constant expressions.
4993  if (This && !HasQualifier &&
4994  isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4995  return Error(E, diag::note_constexpr_virtual_call);
4996 
4997  const FunctionDecl *Definition = nullptr;
4998  Stmt *Body = FD->getBody(Definition);
4999 
5000  if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
5001  !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
5002  Result, ResultSlot))
5003  return false;
5004 
5005  return true;
5006  }
5007 
5008  bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
5009  return StmtVisitorTy::Visit(E->getInitializer());
5010  }
5011  bool VisitInitListExpr(const InitListExpr *E) {
5012  if (E->getNumInits() == 0)
5013  return DerivedZeroInitialization(E);
5014  if (E->getNumInits() == 1)
5015  return StmtVisitorTy::Visit(E->getInit(0));
5016  return Error(E);
5017  }
5018  bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
5019  return DerivedZeroInitialization(E);
5020  }
5021  bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
5022  return DerivedZeroInitialization(E);
5023  }
5024  bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
5025  return DerivedZeroInitialization(E);
5026  }
5027 
5028  /// A member expression where the object is a prvalue is itself a prvalue.
5029  bool VisitMemberExpr(const MemberExpr *E) {
5030  assert(!E->isArrow() && "missing call to bound member function?");
5031 
5032  APValue Val;
5033  if (!Evaluate(Val, Info, E->getBase()))
5034  return false;
5035 
5036  QualType BaseTy = E->getBase()->getType();
5037 
5038  const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
5039  if (!FD) return Error(E);
5040  assert(!FD->getType()->isReferenceType() && "prvalue reference?");
5041  assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5042  FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5043 
5044  CompleteObject Obj(&Val, BaseTy, true);
5045  SubobjectDesignator Designator(BaseTy);
5046  Designator.addDeclUnchecked(FD);
5047 
5048  APValue Result;
5049  return extractSubobject(Info, E, Obj, Designator, Result) &&
5050  DerivedSuccess(Result, E);
5051  }
5052 
5053  bool VisitCastExpr(const CastExpr *E) {
5054  switch (E->getCastKind()) {
5055  default:
5056  break;
5057 
5058  case CK_AtomicToNonAtomic: {
5059  APValue AtomicVal;
5060  // This does not need to be done in place even for class/array types:
5061  // atomic-to-non-atomic conversion implies copying the object
5062  // representation.
5063  if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
5064  return false;
5065  return DerivedSuccess(AtomicVal, E);
5066  }
5067 
5068  case CK_NoOp:
5069  case CK_UserDefinedConversion:
5070  return StmtVisitorTy::Visit(E->getSubExpr());
5071 
5072  case CK_LValueToRValue: {
5073  LValue LVal;
5074  if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
5075  return false;
5076  APValue RVal;
5077  // Note, we use the subexpression's type in order to retain cv-qualifiers.
5078  if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5079  LVal, RVal))
5080  return false;
5081  return DerivedSuccess(RVal, E);
5082  }
5083  }
5084 
5085  return Error(E);
5086  }
5087 
5088  bool VisitUnaryPostInc(const UnaryOperator *UO) {
5089  return VisitUnaryPostIncDec(UO);
5090  }
5091  bool VisitUnaryPostDec(const UnaryOperator *UO) {
5092  return VisitUnaryPostIncDec(UO);
5093  }
5094  bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
5095  if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5096  return Error(UO);
5097 
5098  LValue LVal;
5099  if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
5100  return false;
5101  APValue RVal;
5102  if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
5103  UO->isIncrementOp(), &RVal))
5104  return false;
5105  return DerivedSuccess(RVal, UO);
5106  }
5107 
5108  bool VisitStmtExpr(const StmtExpr *E) {
5109  // We will have checked the full-expressions inside the statement expression
5110  // when they were completed, and don't need to check them again now.
5111  if (Info.checkingForOverflow())
5112  return Error(E);
5113 
5114  BlockScopeRAII Scope(Info);
5115  const CompoundStmt *CS = E->getSubStmt();
5116  if (CS->body_empty())
5117  return true;
5118 
5120  BE = CS->body_end();
5121  /**/; ++BI) {
5122  if (BI + 1 == BE) {
5123  const Expr *FinalExpr = dyn_cast<Expr>(*BI);
5124  if (!FinalExpr) {
5125  Info.FFDiag((*BI)->getBeginLoc(),
5126  diag::note_constexpr_stmt_expr_unsupported);
5127  return false;
5128  }
5129  return this->Visit(FinalExpr);
5130  }
5131 
5132  APValue ReturnValue;
5133  StmtResult Result = { ReturnValue, nullptr };
5134  EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
5135  if (ESR != ESR_Succeeded) {
5136  // FIXME: If the statement-expression terminated due to 'return',
5137  // 'break', or 'continue', it would be nice to propagate that to
5138  // the outer statement evaluation rather than bailing out.
5139  if (ESR != ESR_Failed)
5140  Info.FFDiag((*BI)->getBeginLoc(),
5141  diag::note_constexpr_stmt_expr_unsupported);
5142  return false;
5143  }
5144  }
5145 
5146  llvm_unreachable("Return from function from the loop above.");
5147  }
5148 
5149  /// Visit a value which is evaluated, but whose value is ignored.
5150  void VisitIgnoredValue(const Expr *E) {
5151  EvaluateIgnoredValue(Info, E);
5152  }
5153 
5154  /// Potentially visit a MemberExpr's base expression.
5155  void VisitIgnoredBaseExpression(const Expr *E) {
5156  // While MSVC doesn't evaluate the base expression, it does diagnose the
5157  // presence of side-effecting behavior.
5158  if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
5159  return;
5160  VisitIgnoredValue(E);
5161  }
5162 };
5163 
5164 } // namespace
5165 
5166 //===----------------------------------------------------------------------===//
5167 // Common base class for lvalue and temporary evaluation.
5168 //===----------------------------------------------------------------------===//
5169 namespace {
5170 template<class Derived>
5171 class LValueExprEvaluatorBase
5172  : public ExprEvaluatorBase<Derived> {
5173 protected:
5174  LValue &Result;
5175  bool InvalidBaseOK;
5176  typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
5177  typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
5178 
5179  bool Success(APValue::LValueBase B) {
5180  Result.set(B);
5181  return true;
5182  }
5183 
5184  bool evaluatePointer(const Expr *E, LValue &Result) {
5185  return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
5186  }
5187 
5188 public:
5189  LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5190  : ExprEvaluatorBaseTy(Info), Result(Result),
5191  InvalidBaseOK(InvalidBaseOK) {}
5192 
5193  bool Success(const APValue &V, const Expr *E) {
5194  Result.setFrom(this->Info.Ctx, V);
5195  return true;
5196  }
5197 
5198  bool VisitMemberExpr(const MemberExpr *E) {
5199  // Handle non-static data members.
5200  QualType BaseTy;
5201  bool EvalOK;
5202  if (E->isArrow()) {
5203  EvalOK = evaluatePointer(E->getBase(), Result);
5204  BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
5205  } else if (E->getBase()->isRValue()) {
5206  assert(E->getBase()->getType()->isRecordType());
5207  EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
5208  BaseTy = E->getBase()->getType();
5209  } else {
5210  EvalOK = this->Visit(E->getBase());
5211  BaseTy = E->getBase()->getType();
5212  }
5213  if (!EvalOK) {
5214  if (!InvalidBaseOK)
5215  return false;
5216  Result.setInvalid(E);
5217  return true;
5218  }
5219 
5220  const ValueDecl *MD = E->getMemberDecl();
5221  if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5222  assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5223  FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5224  (void)BaseTy;
5225  if (!HandleLValueMember(this->Info, E, Result, FD))
5226  return false;
5227  } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
5228  if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5229  return false;
5230  } else
5231  return this->Error(E);
5232 
5233  if (MD->getType()->isReferenceType()) {
5234  APValue RefValue;
5235  if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
5236  RefValue))
5237  return false;
5238  return Success(RefValue, E);
5239  }
5240  return true;
5241  }
5242 
5243  bool VisitBinaryOperator(const BinaryOperator *E) {
5244  switch (E->getOpcode()) {
5245  default:
5246  return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5247 
5248  case BO_PtrMemD:
5249  case BO_PtrMemI:
5250  return HandleMemberPointerAccess(this->Info, E, Result);
5251  }
5252  }
5253 
5254  bool VisitCastExpr(const CastExpr *E) {
5255  switch (E->getCastKind()) {
5256  default:
5257  return ExprEvaluatorBaseTy::VisitCastExpr(E);
5258 
5259  case CK_DerivedToBase:
5260  case CK_UncheckedDerivedToBase:
5261  if (!this->Visit(E->getSubExpr()))
5262  return false;
5263 
5264  // Now figure out the necessary offset to add to the base LV to get from
5265  // the derived class to the base class.
5266  return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5267  Result);
5268  }
5269  }
5270 };
5271 }
5272 
5273 //===----------------------------------------------------------------------===//
5274 // LValue Evaluation
5275 //
5276 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5277 // function designators (in C), decl references to void objects (in C), and
5278 // temporaries (if building with -Wno-address-of-temporary).
5279 //
5280 // LValue evaluation produces values comprising a base expression of one of the
5281 // following types:
5282 // - Declarations
5283 // * VarDecl
5284 // * FunctionDecl
5285 // - Literals
5286 // * CompoundLiteralExpr in C (and in global scope in C++)
5287 // * StringLiteral
5288 // * CXXTypeidExpr
5289 // * PredefinedExpr
5290 // * ObjCStringLiteralExpr
5291 // * ObjCEncodeExpr
5292 // * AddrLabelExpr
5293 // * BlockExpr
5294 // * CallExpr for a MakeStringConstant builtin
5295 // - Locals and temporaries
5296 // * MaterializeTemporaryExpr
5297 // * Any Expr, with a CallIndex indicating the function in which the temporary
5298 // was evaluated, for cases where the MaterializeTemporaryExpr is missing
5299 // from the AST (FIXME).
5300 // * A MaterializeTemporaryExpr that has static storage duration, with no
5301 // CallIndex, for a lifetime-extended temporary.
5302 // plus an offset in bytes.
5303 //===----------------------------------------------------------------------===//
5304 namespace {
5305 class LValueExprEvaluator
5306  : public LValueExprEvaluatorBase<LValueExprEvaluator> {
5307 public:
5308  LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5309  LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
5310 
5311  bool VisitVarDecl(const Expr *E, const VarDecl *VD);
5312  bool VisitUnaryPreIncDec(const UnaryOperator *UO);
5313 
5314  bool VisitDeclRefExpr(const DeclRefExpr *E);
5315  bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
5316  bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
5317  bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5318  bool VisitMemberExpr(const MemberExpr *E);
5319  bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5320  bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
5321  bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
5322  bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
5323  bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5324  bool VisitUnaryDeref(const UnaryOperator *E);
5325  bool VisitUnaryReal(const UnaryOperator *E);
5326  bool VisitUnaryImag(const UnaryOperator *E);
5327  bool VisitUnaryPreInc(const UnaryOperator *UO) {
5328  return VisitUnaryPreIncDec(UO);
5329  }
5330  bool VisitUnaryPreDec(const UnaryOperator *UO) {
5331  return VisitUnaryPreIncDec(UO);
5332  }
5333  bool VisitBinAssign(const BinaryOperator *BO);
5334  bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
5335 
5336  bool VisitCastExpr(const CastExpr *E) {
5337  switch (E->getCastKind()) {
5338  default:
5339  return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5340 
5341  case CK_LValueBitCast:
5342  this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5343  if (!Visit(E->getSubExpr()))
5344  return false;
5345  Result.Designator.setInvalid();
5346  return true;
5347 
5348  case CK_BaseToDerived:
5349  if (!Visit(E->getSubExpr()))
5350  return false;
5351  return HandleBaseToDerivedCast(Info, E, Result);
5352  }
5353  }
5354 };
5355 } // end anonymous namespace
5356 
5357 /// Evaluate an expression as an lvalue. This can be legitimately called on
5358 /// expressions which are not glvalues, in three cases:
5359 /// * function designators in C, and
5360 /// * "extern void" objects
5361 /// * @selector() expressions in Objective-C
5362 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5363  bool InvalidBaseOK) {
5364  assert(E->isGLValue() || E->getType()->isFunctionType() ||
5365  E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
5366  return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5367 }
5368 
5369 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
5370  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
5371  return Success(FD);
5372  if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
5373  return VisitVarDecl(E, VD);
5374  if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
5375  return Visit(BD->getBinding());
5376  return Error(E);
5377 }
5378 
5379 
5380 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
5381 
5382  // If we are within a lambda's call operator, check whether the 'VD' referred
5383  // to within 'E' actually represents a lambda-capture that maps to a
5384  // data-member/field within the closure object, and if so, evaluate to the
5385  // field or what the field refers to.
5386  if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
5387  isa<DeclRefExpr>(E) &&
5388  cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
5389  // We don't always have a complete capture-map when checking or inferring if
5390  // the function call operator meets the requirements of a constexpr function
5391  // - but we don't need to evaluate the captures to determine constexprness
5392  // (dcl.constexpr C++17).
5393  if (Info.checkingPotentialConstantExpression())
5394  return false;
5395 
5396  if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5397  // Start with 'Result' referring to the complete closure object...
5398  Result = *Info.CurrentCall->This;
5399  // ... then update it to refer to the field of the closure object
5400  // that represents the capture.
5401  if (!HandleLValueMember(Info, E, Result, FD))
5402  return false;
5403  // And if the field is of reference type, update 'Result' to refer to what
5404  // the field refers to.
5405  if (FD->getType()->isReferenceType()) {
5406  APValue RVal;
5407  if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5408  RVal))
5409  return false;
5410  Result.setFrom(Info.Ctx, RVal);
5411  }
5412  return true;
5413  }
5414  }
5415  CallStackFrame *Frame = nullptr;
5416  if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5417  // Only if a local variable was declared in the function currently being
5418  // evaluated, do we expect to be able to find its value in the current
5419  // frame. (Otherwise it was likely declared in an enclosing context and
5420  // could either have a valid evaluatable value (for e.g. a constexpr
5421  // variable) or be ill-formed (and trigger an appropriate evaluation
5422  // diagnostic)).
5423  if (Info.CurrentCall->Callee &&
5424  Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5425  Frame = Info.CurrentCall;
5426  }
5427  }
5428 
5429  if (!VD->getType()->isReferenceType()) {
5430  if (Frame) {
5431  Result.set({VD, Frame->Index,
5432  Info.CurrentCall->getCurrentTemporaryVersion(VD)});
5433  return true;
5434  }
5435  return Success(VD);
5436  }
5437 
5438  APValue *V;
5439  if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
5440  return false;
5441  if (V->isUninit()) {
5442  if (!Info.checkingPotentialConstantExpression())
5443  Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
5444  return false;
5445  }
5446  return Success(*V, E);
5447 }
5448 
5449 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5450  const MaterializeTemporaryExpr *E) {
5451  // Walk through the expression to find the materialized temporary itself.
5452  SmallVector<const Expr *, 2> CommaLHSs;
5454  const Expr *Inner = E->GetTemporaryExpr()->
5455  skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
5456 
5457  // If we passed any comma operators, evaluate their LHSs.
5458  for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5459  if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5460  return false;
5461 
5462  // A materialized temporary with static storage duration can appear within the
5463  // result of a constant expression evaluation, so we need to preserve its
5464  // value for use outside this evaluation.
5465  APValue *Value;
5466  if (E->getStorageDuration() == SD_Static) {
5467  Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
5468  *Value = APValue();
5469  Result.set(E);
5470  } else {
5472  *Info.CurrentCall);
5473  }
5474 
5475  QualType Type = Inner->getType();
5476 
5477  // Materialize the temporary itself.
5478  if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5479  (E->getStorageDuration() == SD_Static &&
5480  !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5481  *Value = APValue();
5482  return false;
5483  }
5484 
5485  // Adjust our lvalue to refer to the desired subobject.
5486  for (unsigned I = Adjustments.size(); I != 0; /**/) {
5487  --I;
5488  switch (Adjustments[I].Kind) {
5490  if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5491  Type, Result))
5492  return false;
5493  Type = Adjustments[I].DerivedToBase.BasePath->getType();
5494  break;
5495 
5497  if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5498  return false;
5499  Type = Adjustments[I].Field->getType();
5500  break;
5501 
5503  if (!HandleMemberPointerAccess(this->Info, Type, Result,
5504  Adjustments[I].Ptr.RHS))
5505  return false;
5506  Type = Adjustments[I].Ptr.MPT->getPointeeType();
5507  break;
5508  }
5509  }
5510 
5511  return true;
5512 }
5513 
5514 bool
5515 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
5516  assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5517  "lvalue compound literal in c++?");
5518  // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5519  // only see this when folding in C, so there's no standard to follow here.
5520  return Success(E);
5521 }
5522 
5523 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
5524  if (!E->isPotentiallyEvaluated())
5525  return Success(E);
5526 
5527  Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
5528  << E->getExprOperand()->getType()
5529  << E->getExprOperand()->getSourceRange();
5530  return false;
5531 }
5532 
5533 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5534  return Success(E);
5535 }
5536 
5537 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
5538  // Handle static data members.
5539  if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
5540  VisitIgnoredBaseExpression(E->getBase());
5541  return VisitVarDecl(E, VD);
5542  }
5543 
5544  // Handle static member functions.
5545  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5546  if (MD->isStatic()) {
5547  VisitIgnoredBaseExpression(E->getBase());
5548  return Success(MD);
5549  }
5550  }
5551 
5552  // Handle non-static data members.
5553  return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
5554 }
5555 
5556 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
5557  // FIXME: Deal with vectors as array subscript bases.
5558  if (E->getBase()->getType()->isVectorType())
5559  return Error(E);
5560 
5561  bool Success = true;
5562  if (!evaluatePointer(E->getBase(), Result)) {
5563  if (!Info.noteFailure())
5564  return false;
5565  Success = false;
5566  }
5567 
5568  APSInt Index;
5569  if (!EvaluateInteger(E->getIdx(), Index, Info))
5570  return false;
5571 
5572  return Success &&
5573  HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
5574 }
5575 
5576 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
5577  return evaluatePointer(E->getSubExpr(), Result);
5578 }
5579 
5580 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5581  if (!Visit(E->getSubExpr()))
5582  return false;
5583  // __real is a no-op on scalar lvalues.
5584  if (E->getSubExpr()->getType()->isAnyComplexType())
5585  HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5586  return true;
5587 }
5588 
5589 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5590  assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5591  "lvalue __imag__ on scalar?");
5592  if (!Visit(E->getSubExpr()))
5593  return false;
5594  HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5595  return true;
5596 }
5597 
5598 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
5599  if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5600  return Error(UO);
5601 
5602  if (!this->Visit(UO->getSubExpr()))
5603  return false;
5604 
5605  return handleIncDec(
5606  this->Info, UO, Result, UO->getSubExpr()->getType(),
5607  UO->isIncrementOp(), nullptr);
5608 }
5609 
5610 bool LValueExprEvaluator::VisitCompoundAssignOperator(
5611  const CompoundAssignOperator *CAO) {
5612  if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5613  return Error(CAO);
5614 
5615  APValue RHS;
5616 
5617  // The overall lvalue result is the result of evaluating the LHS.
5618  if (!this->Visit(CAO->getLHS())) {
5619  if (Info.noteFailure())
5620  Evaluate(RHS, this->Info, CAO->getRHS());
5621  return false;
5622  }
5623 
5624  if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5625  return false;
5626 
5627  return handleCompoundAssignment(
5628  this->Info, CAO,
5629  Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5630  CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
5631 }
5632 
5633 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
5634  if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5635  return Error(E);
5636 
5637  APValue NewVal;
5638 
5639  if (!this->Visit(E->getLHS())) {
5640  if (Info.noteFailure())
5641  Evaluate(NewVal, this->Info, E->getRHS());
5642  return false;
5643  }
5644 
5645  if (!Evaluate(NewVal, this->Info, E->getRHS()))
5646  return false;
5647 
5648  return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
5649  NewVal);
5650 }
5651 
5652 //===----------------------------------------------------------------------===//
5653 // Pointer Evaluation
5654 //===----------------------------------------------------------------------===//
5655 
5656 /// Attempts to compute the number of bytes available at the pointer
5657 /// returned by a function with the alloc_size attribute. Returns true if we
5658 /// were successful. Places an unsigned number into `Result`.
5659 ///
5660 /// This expects the given CallExpr to be a call to a function with an
5661 /// alloc_size attribute.
5663  const CallExpr *Call,
5664  llvm::APInt &Result) {
5665  const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5666 
5667  assert(AllocSize && AllocSize->getElemSizeParam().isValid());
5668  unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
5669  unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5670  if (Call->getNumArgs() <= SizeArgNo)
5671  return false;
5672 
5673  auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5675  if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
5676  return false;
5677  Into = ExprResult.Val.getInt();
5678  if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5679  return false;
5680  Into = Into.zextOrSelf(BitsInSizeT);
5681  return true;
5682  };
5683 
5684  APSInt SizeOfElem;
5685  if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5686  return false;
5687 
5688  if (!AllocSize->getNumElemsParam().isValid()) {
5689  Result = std::move(SizeOfElem);
5690  return true;
5691  }
5692 
5693  APSInt NumberOfElems;
5694  unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
5695  if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5696  return false;
5697 
5698  bool Overflow;
5699  llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5700  if (Overflow)
5701  return false;
5702 
5703  Result = std::move(BytesAvailable);
5704  return true;
5705 }
5706 
5707 /// Convenience function. LVal's base must be a call to an alloc_size
5708 /// function.
5710  const LValue &LVal,
5711  llvm::APInt &Result) {
5712  assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5713  "Can't get the size of a non alloc_size function");
5714  const auto *Base = LVal.getLValueBase().get<const Expr *>();
5715  const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5716  return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5717 }
5718 
5719 /// Attempts to evaluate the given LValueBase as the result of a call to
5720 /// a function with the alloc_size attribute. If it was possible to do so, this
5721 /// function will return true, make Result's Base point to said function call,
5722 /// and mark Result's Base as invalid.
5723 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5724  LValue &Result) {
5725  if (Base.isNull())
5726  return false;
5727 
5728  // Because we do no form of static analysis, we only support const variables.
5729  //
5730  // Additionally, we can't support parameters, nor can we support static
5731  // variables (in the latter case, use-before-assign isn't UB; in the former,
5732  // we have no clue what they'll be assigned to).
5733  const auto *VD =
5734  dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5735  if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5736  return false;
5737 
5738  const Expr *Init = VD->getAnyInitializer();
5739  if (!Init)
5740  return false;
5741 
5742  const Expr *E = Init->IgnoreParens();
5743  if (!tryUnwrapAllocSizeCall(E))
5744  return false;
5745 
5746  // Store E instead of E unwrapped so that the type of the LValue's base is
5747  // what the user wanted.
5748  Result.setInvalid(E);
5749 
5750  QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5751  Result.addUnsizedArray(Info, E, Pointee);
5752  return true;
5753 }
5754 
5755 namespace {
5756 class PointerExprEvaluator
5757  : public ExprEvaluatorBase<PointerExprEvaluator> {
5758  LValue &Result;
5759  bool InvalidBaseOK;
5760 
5761  bool Success(const Expr *E) {
5762  Result.set(E);
5763  return true;
5764  }
5765 
5766  bool evaluateLValue(const Expr *E, LValue &Result) {
5767  return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5768  }
5769 
5770  bool evaluatePointer(const Expr *E, LValue &Result) {
5771  return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5772  }
5773 
5774  bool visitNonBuiltinCallExpr(const CallExpr *E);
5775 public:
5776 
5777  PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5778  : ExprEvaluatorBaseTy(info), Result(Result),
5779  InvalidBaseOK(InvalidBaseOK) {}
5780 
5781  bool Success(const APValue &V, const Expr *E) {
5782  Result.setFrom(Info.Ctx, V);
5783  return true;
5784  }
5785  bool ZeroInitialization(const Expr *E) {
5786  auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5787  Result.setNull(E->getType(), TargetVal);
5788  return true;
5789  }
5790 
5791  bool VisitBinaryOperator(const BinaryOperator *E);
5792  bool VisitCastExpr(const CastExpr* E);
5793  bool VisitUnaryAddrOf(const UnaryOperator *E);
5794  bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
5795  { return Success(E); }
5796  bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5797  if (Info.noteFailure())
5798  EvaluateIgnoredValue(Info, E->getSubExpr());
5799  return Error(E);
5800  }
5801  bool VisitAddrLabelExpr(const AddrLabelExpr *E)
5802  { return Success(E); }
5803  bool VisitCallExpr(const CallExpr *E);
5804  bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
5805  bool VisitBlockExpr(const BlockExpr *E) {
5806  if (!E->getBlockDecl()->hasCaptures())
5807  return Success(E);
5808  return Error(E);
5809  }
5810  bool VisitCXXThisExpr(const CXXThisExpr *E) {
5811  // Can't look at 'this' when checking a potential constant expression.
5812  if (Info.checkingPotentialConstantExpression())
5813  return false;
5814  if (!Info.CurrentCall->This) {
5815  if (Info.getLangOpts().CPlusPlus11)
5816  Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
5817  else
5818  Info.FFDiag(E);
5819  return false;
5820  }
5821  Result = *Info.CurrentCall->This;
5822  // If we are inside a lambda's call operator, the 'this' expression refers
5823  // to the enclosing '*this' object (either by value or reference) which is
5824  // either copied into the closure object's field that represents the '*this'
5825  // or refers to '*this'.
5826  if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5827  // Update 'Result' to refer to the data member/field of the closure object
5828  // that represents the '*this' capture.
5829  if (!HandleLValueMember(Info, E, Result,
5830  Info.CurrentCall->LambdaThisCaptureField))
5831  return false;
5832  // If we captured '*this' by reference, replace the field with its referent.
5833  if (Info.CurrentCall->LambdaThisCaptureField->getType()
5834  ->isPointerType()) {
5835  APValue RVal;
5836  if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5837  RVal))
5838  return false;
5839 
5840  Result.setFrom(Info.Ctx, RVal);
5841  }
5842  }
5843  return true;
5844  }
5845 
5846  // FIXME: Missing: @protocol, @selector
5847 };
5848 } // end anonymous namespace
5849 
5850 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5851  bool InvalidBaseOK) {
5852  assert(E->isRValue() && E->getType()->hasPointerRepresentation());
5853  return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5854 }
5855 
5856 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5857  if (E->getOpcode() != BO_Add &&
5858  E->getOpcode() != BO_Sub)
5859  return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5860 
5861  const Expr *PExp = E->getLHS();
5862  const Expr *IExp = E->getRHS();
5863  if (IExp->getType()->isPointerType())
5864  std::swap(PExp, IExp);
5865 
5866  bool EvalPtrOK = evaluatePointer(PExp, Result);
5867  if (!EvalPtrOK && !Info.noteFailure())
5868  return false;
5869 
5870  llvm::APSInt Offset;
5871  if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
5872  return false;
5873 
5874  if (E->getOpcode() == BO_Sub)
5875  negateAsSigned(Offset);
5876 
5877  QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
5878  return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
5879 }
5880 
5881 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5882  return evaluateLValue(E->getSubExpr(), Result);
5883 }
5884 
5885 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5886  const Expr *SubExpr = E->getSubExpr();
5887 
5888  switch (E->getCastKind()) {
5889  default:
5890  break;
5891 
5892  case CK_BitCast:
5893  case CK_CPointerToObjCPointerCast:
5894  case CK_BlockPointerToObjCPointerCast:
5895  case CK_AnyPointerToBlockPointerCast:
5896  case CK_AddressSpaceConversion:
5897  if (!Visit(SubExpr))
5898  return false;
5899  // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5900  // permitted in constant expressions in C++11. Bitcasts from cv void* are
5901  // also static_casts, but we disallow them as a resolution to DR1312.
5902  if (!E->getType()->isVoidPointerType()) {
5903  Result.Designator.setInvalid();
5904  if (SubExpr->getType()->isVoidPointerType())
5905  CCEDiag(E, diag::note_constexpr_invalid_cast)
5906  << 3 << SubExpr->getType();
5907  else
5908  CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5909  }
5910  if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5911  ZeroInitialization(E);
5912  return true;
5913 
5914  case CK_DerivedToBase:
5915  case CK_UncheckedDerivedToBase:
5916  if (!evaluatePointer(E->getSubExpr(), Result))
5917  return false;
5918  if (!Result.Base && Result.Offset.isZero())
5919  return true;
5920 
5921  // Now figure out the necessary offset to add to the base LV to get from
5922  // the derived class to the base class.
5923  return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5924  castAs<PointerType>()->getPointeeType(),
5925  Result);
5926 
5927  case CK_BaseToDerived:
5928  if (!Visit(E->getSubExpr()))
5929  return false;
5930  if (!Result.Base && Result.Offset.isZero())
5931  return true;
5932  return HandleBaseToDerivedCast(Info, E, Result);
5933 
5934  case CK_NullToPointer:
5935  VisitIgnoredValue(E->getSubExpr());
5936  return ZeroInitialization(E);
5937 
5938  case CK_IntegralToPointer: {
5939  CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5940 
5941  APValue Value;
5942  if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
5943  break;
5944 
5945  if (Value.isInt()) {
5946  unsigned Size = Info.Ctx.getTypeSize(E->getType());
5947  uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
5948  Result.Base = (Expr*)nullptr;
5949  Result.InvalidBase = false;
5950  Result.Offset = CharUnits::fromQuantity(N);
5951  Result.Designator.setInvalid();
5952  Result.IsNullPtr = false;
5953  return true;
5954  } else {
5955  // Cast is of an lvalue, no need to change value.
5956  Result.setFrom(Info.Ctx, Value);
5957  return true;
5958  }
5959  }
5960 
5961  case CK_ArrayToPointerDecay: {
5962  if (SubExpr->isGLValue()) {
5963  if (!evaluateLValue(SubExpr, Result))
5964  return false;
5965  } else {
5966  APValue &Value = createTemporary(SubExpr, false, Result,
5967  *Info.CurrentCall);
5968  if (!EvaluateInPlace(Value, Info, Result, SubExpr))
5969  return false;
5970  }
5971  // The result is a pointer to the first element of the array.
5972  auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5973  if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
5974  Result.addArray(Info, E, CAT);
5975  else
5976  Result.addUnsizedArray(Info, E, AT->getElementType());
5977  return true;
5978  }
5979 
5980  case CK_FunctionToPointerDecay:
5981  return evaluateLValue(SubExpr, Result);
5982 
5983  case CK_LValueToRValue: {
5984  LValue LVal;
5985  if (!evaluateLValue(E->getSubExpr(), LVal))
5986  return false;
5987 
5988  APValue RVal;
5989  // Note, we use the subexpression's type in order to retain cv-qualifiers.
5990  if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5991  LVal, RVal))
5992