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