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